Skip to content
Tutorials Center
My learning

Topics

Lesson 81 of 147 ยท PHP and the Web

Building a JSON API

Build a JSON API in plain PHP: send JSON responses, read request bodies from php://input, map HTTP methods to CRUD, choose status codes and call other APIs with curl.

Not every request wants an HTML page. A JavaScript front end, a mobile app or another server usually wants data, and today that data almost always travels as JSON. A PHP script that answers such requests is a JSON API: it reads JSON (or query parameters) from the request and replies with JSON plus an HTTP status code that says how things went.

You already have every piece you need. JSON taught you json_encode() and json_decode(), HTTP Headers, Status Codes and Redirects covered status codes and headers, and Front Controllers and Routing showed how to dispatch by method and path. This lesson puts them together into a small but well-behaved API, following the conventions known as REST: URLs name resources (/books, /books/7), and HTTP methods say what to do with them.

Our editor runs PHP on the command line without a web server, so the API demos call their handlers with simulated requests (a method, a path and a body string) and print the response that a real server would send.

Sending a JSON response

A JSON response needs three things: the right status code, a Content-Type: application/json header, and a body produced by json_encode(). Wrapping them in one function keeps every endpoint consistent:

PHP
<?php
function sendJson(mixed $data, int $status = 200): never
{
    http_response_code($status);
    header('Content-Type: application/json');
    echo json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

sendJson(['id' => 7, 'title' => 'Dune'], 200);

The never return type (PHP 8.1) documents that the function doesn't return: it ends the request with exit. The flags matter too:

  • JSON_THROW_ON_ERROR turns encoding failures (such as invalid UTF-8 in a string) into a JsonException instead of a silent false.
  • JSON_UNESCAPED_SLASHES writes /books/7 instead of \/books\/7.
  • JSON_UNESCAPED_UNICODE writes "Cafรฉ" instead of "Cafรฉ". Both are valid JSON; the unescaped form is smaller and easier to read.

Since the editor can't send real headers, the demo returns the response as an array and prints it in HTTP format:

PHP Building JSON responses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last line shows a classic JSON API trap: PHP has one array type, and json_encode() turns an empty array into []. If a client expects an object ({}), cast it with (object) [] or pass new stdClass(). Similarly, an array whose keys aren't 0, 1, 2, โ€ฆ in order becomes an object, so run array_values() on a filtered list before encoding it.

Reading a JSON request body

When a browser submits a classic HTML form, PHP parses the body into $_POST. When a client sends JSON, it doesn't: $_POST stays empty, because PHP only parses form encodings. You read the raw body yourself from the php://input stream and decode it:

PHP
<?php
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (!str_starts_with($contentType, 'application/json')) {
    sendJson(['error' => 'Send the body as application/json'], 415);
}

$raw = file_get_contents('php://input');
try {
    $data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException) {
    sendJson(['error' => 'The request body is not valid JSON'], 400);
}

The second argument true gives you associative arrays instead of stdClass objects, which are easier to validate. But decoding isn't validation: valid JSON can still be a number, a string or a list instead of the object you expect, and fields can be missing or have the wrong type. Check the shape before trusting it:

PHP Decoding and validating request bodies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

array_is_list() (PHP 8.1) tells a JSON array ([1, 2, 3]) apart from a JSON object. Notice that "1965" in quotes is rejected: in JSON, a string isn't a number, and a strict API says so rather than guessing. The usual status codes are 400 Bad Request when the body can't be parsed at all and 422 Unprocessable Content when it parses but fails validation. Form Validation covers more validation techniques that apply just as well to JSON.

Methods, URLs and status codes

REST maps the four CRUD operations onto HTTP methods applied to resource URLs. Here's the contract for a typical books API. The next demo implements all of it except PUT, so you can also see a 405 answer:

Request Meaning Success Common errors
GET /books List books 200 with an array
GET /books/7 Fetch one book 200 with the book 404
POST /books Create a book 201 + Location header 400, 422
PUT /books/7 Replace book 7 200 with the book 404, 422
PATCH /books/7 Change some fields 200 with the book 404, 422
DELETE /books/7 Delete book 7 204, no body 404
DELETE /books Not supported 405 + Allow header

A few conventions make APIs pleasant to use:

  • GET never changes data. Browsers, caches and crawlers may repeat GET requests freely.
  • PUT and DELETE are idempotent: sending the same request twice leaves the same result as sending it once. POST isn't: two POSTs create two books.
  • Errors have a consistent shape. Pick one format, such as {"error": "..."} or the standard "problem details" format (Content-Type: application/problem+json with type, title, status and detail fields), and use it everywhere.

A complete CRUD handler

This demo is a whole API in one class. It keeps books in an array so it runs anywhere; in CRUD with PDO you'll store the same data in a database. The handle() method takes the simulated request and returns the response that a front controller would send:

PHP A books API tested with simulated requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the output line by line against the table above: 201 with a Location header for the new book, 422 for the incomplete one, 204 with no body for the delete, 404 afterwards, and 405 with an Allow header for PUT, which this API doesn't support. Note array_values() in the list endpoint: after book 1 is deleted, the array's keys start at 2, and without array_values() the list would be encoded as a JSON object.

Some simulated requests have no body, so they have only two elements. Destructuring them straight into three variables would raise an "Undefined array key 2" warning; $request + [2 => ''] uses the array union operator to fill in an empty body first.

On a real server, the front controller would feed handle() with $_SERVER['REQUEST_METHOD'], the path from $_SERVER['REQUEST_URI'] and file_get_contents('php://input'), then send the status, headers and json_encode($data).

Authentication with tokens

APIs usually don't use cookies and sessions. Instead, the client sends a token in the Authorization header on every request: Authorization: Bearer 7c1f.... PHP exposes it as $_SERVER['HTTP_AUTHORIZATION'] (some Apache setups need extra configuration to pass it through). Compare tokens with hash_equals(), which takes the same time whether the strings match early or late, so attackers can't guess a token character by character from response times:

PHP Checking a Bearer token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Storing only a hash of each token means a database leak doesn't hand attackers working tokens, the same idea as password hashing (a fast hash like SHA-256 is fine here because tokens are long random strings, unlike passwords). A missing, malformed or unknown token gets 401 Unauthorized: "I don't know who you are". A valid token without the needed permission gets 403 Forbidden: "I know who you are, and you may not do this". Real tokens should be long and random, for example bin2hex(random_bytes(32)); the short ones here just keep the demo readable.

CORS in one paragraph

If a JavaScript app on https://app.example calls your API on https://api.example, the browser blocks the response unless the API allows that origin with CORS headers. For requests with JSON bodies or an Authorization header, the browser first sends an OPTIONS "preflight" request, and your front controller answers it with a 204 and headers such as:

TEXT
Access-Control-Allow-Origin: https://app.example
Access-Control-Allow-Methods: GET, POST, PATCH, DELETE
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 600

CORS is a browser rule only. It doesn't protect your API from scripts, curl or other servers, so it never replaces authentication.

Pagination and query parameters

A list endpoint shouldn't return 100,000 books in one response. Accept ?page= and ?per_page= query parameters, validate them, and include paging details in the response so clients know whether there's more. On a real server the values come from $_GET; here they're simulated arrays:

PHP Paginating a list endpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

filter_var() with FILTER_VALIDATE_INT and a range rejects 0, negative numbers, 'abc' and absurdly large page sizes in one step (see Handling Forms). Capping per_page protects your server from clients that ask for everything at once. With a database you'd use LIMIT and OFFSET instead of array_slice(), as shown in Pagination, Search and Database Patterns.

Calling other APIs from PHP

PHP is often the client too: charging a card, sending an email through a provider, fetching exchange rates. Our sandbox has no network access, so these examples are read-only. With the curl extension:

PHP
<?php
$ch = curl_init('https://api.example.com/v1/rates?base=EUR');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,          // return the body instead of printing it
    CURLOPT_TIMEOUT => 10,                   // never wait forever
    CURLOPT_HTTPHEADER => ['Accept: application/json', 'Authorization: Bearer ' . $apiKey],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);

if ($body === false) {
    throw new RuntimeException('Request failed: ' . curl_error($ch));
}
$rates = json_decode($body, true, 512, JSON_THROW_ON_ERROR);

Without curl, file_get_contents() with a stream context can send any method and body (see Streams and Wrappers):

PHP
<?php
$context = stream_context_create(['http' => [
    'method' => 'POST',
    'header' => "Content-Type: application/json\r\nAccept: application/json",
    'content' => json_encode(['title' => 'Kindred', 'year' => 1979]),
    'timeout' => 10,
    'ignore_errors' => true,   // still read the body of 4xx/5xx responses
]]);
$body = file_get_contents('https://api.example.com/books', false, $context);

In larger projects most developers use an HTTP client library such as Guzzle or Symfony HttpClient, installed with Composer, which adds retries, middleware and nicer error handling on top of the same ideas. Whatever you use: set a timeout, check the status code, and decode with JSON_THROW_ON_ERROR.

Version your API from day one, for example with a /v1/ prefix in the URL. When you later need a breaking change, /v2/ can live alongside it while existing clients keep working.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A client POSTs a JSON body with Content-Type: application/json. Where does PHP put the data?

    PHP only parses form encodings into $_POST. For JSON, read the raw body with file_get_contents('php://input') and decode it yourself.
  2. 2. What does json_encode(['items' => []]) produce?

    An empty PHP array encodes as a JSON array. Use (object) [] or new stdClass() when the client expects an empty object.
  3. 3. Which response fits a successful POST /books that created book 8?

    201 Created plus a Location header is the standard answer. 204 means there is no body at all.
  4. 4. The body parses as JSON, but the required "year" field is missing. Which status code is most appropriate?

    The request was understood but failed validation. 400 is used when the body can't be parsed at all; 5xx codes are for server failures.
  5. 5. Why does the token check use hash_equals() instead of ===?

    hash_equals() takes the same time regardless of where the strings differ, which defeats timing attacks.

Summary

  • A JSON API answers with a status code, Content-Type: application/json and a body from json_encode() (use JSON_THROW_ON_ERROR, and JSON_UNESCAPED_SLASHES/JSON_UNESCAPED_UNICODE for readable output).
  • JSON request bodies don't fill $_POST: read php://input, decode with json_decode($raw, true, 512, JSON_THROW_ON_ERROR), and validate the shape and types.
  • Map CRUD to methods on resource URLs: GET lists and reads, POST creates (201 + Location), PUT/PATCH update, DELETE removes (204). Use 400, 401, 403, 404, 405, 415 and 422 for the different failures, with one consistent error format.
  • Watch PHP's array-to-JSON rules: empty arrays become [], and non-sequential keys become objects unless you call array_values().
  • Authenticate with tokens in the Authorization header, store token hashes and compare with hash_equals(). CORS only controls what browsers may read.
  • Validate pagination parameters, cap page sizes, and when calling other APIs with curl or stream contexts, always set a timeout and check the status code.

Next: PHP and Databases