Skip to content
Tutorials Center
My learning

Topics

Lesson 132 of 147 ยท Projects

Project: REST API

Build a JSON REST API for books in PHP in four stages - routing, PDO with pagination, validated create/update/delete with correct status codes, auth and errors.

Most PHP code written today doesn't produce HTML pages at all. It answers requests from mobile apps, JavaScript front ends and other servers with JSON. An API like that has no forms to re-display and no templates, but it has stricter rules of its own: every response needs the right status code, every error must be machine-readable, and clients will send you every kind of malformed input you can imagine.

In this project you'll build a JSON API for a small library of books, in four stages, each a complete program. First you'll write the request and response objects and a router that answers GET requests. Then you'll move the books into SQLite with PDO and add filtering and pagination. Then you'll add creating, replacing, updating and deleting books, with validation and the correct status codes for every outcome. Finally you'll add API-key authentication and a safety net that turns unexpected errors into clean 500 responses. The project builds on Building a JSON API, JSON and Front Controllers and Routing.

Our editor runs PHP on the command line, so there's no web server and no network. Each demo simulates HTTP requests with a Request object (method, URL, headers and body) and prints the response the API would send. The last section shows the few lines that connect the same code to a real server, and the curl commands you'd use to call it.

The plan

The API manages one resource, books, at the URL /books:

Method and path Action Success status
GET /books list books (filter by author, paginate with page and per_page) 200 OK
GET /books/{id} one book 200 OK
POST /books create a book from a JSON body 201 Created, with a Location header
PUT /books/{id} replace a book (all fields required) 200 OK
PATCH /books/{id} change some fields 200 OK
DELETE /books/{id} delete a book 204 No Content

A book looks like this in JSON:

JSON
{"id": 3, "title": "Frankenstein", "author": "Mary Shelley", "year": 1818}

Errors always have the same shape, so clients can handle them with one piece of code: {"error": "message"}, plus a details object with one message per field for validation errors. And the API uses the status codes that HTTP defines for each failure: 400 for a malformed request, 401 for a missing or wrong API key, 404 for a missing book, 405 for an unsupported method, 415 for a body that isn't JSON, 422 for JSON that fails validation and 500 for our own bugs.

Stage 1: requests, responses and a router

The first stage sets up the three building blocks.

Request is a readonly class holding the method, the path, the query parameters, the headers and the raw body. Header names are lowercased, because HTTP header names are case-insensitive (Content-Type and content-type are the same header). Request::simulate() builds one from a URL string, using parse_url and parse_str exactly as PHP does when it fills $_GET.

Response holds a status code, headers and a body. Response::json() encodes data with JSON_THROW_ON_ERROR, so an encoding problem becomes an exception instead of a silent false, plus JSON_UNESCAPED_SLASHES and JSON_UNESCAPED_UNICODE to keep URLs and accented letters readable.

Router maps a method and path pattern like /books/{id} to a handler. The placeholder becomes the regular expression group (?<id>\d+), so only digits match: /books/abc is a 404 without the handler ever running. If the path matches but the method doesn't, the router answers 405 with an Allow header.

In this stage the books are a plain PHP array.

PHP Stage 1: a router that answers with JSON

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 output reads like a conversation with the server: > lines are the request, < lines the response. The list and the single book come back with 200 and a Content-Type: application/json header. Les Misรฉrables keeps its accent thanks to JSON_UNESCAPED_UNICODE (without it you'd see Les Misรฉrables, which is equally valid JSON, just harder to read). Book 99 is a 404 with a specific message, /books/abc is a generic 404 from the router, and DELETE is a 405 with Allow: GET, because no DELETE route exists yet.

Why wrap the list in {"data": [...]} instead of returning a bare array? Because it leaves room to grow. In stage 2 the list response gains a meta object with pagination details, and existing clients that read data keep working.

Stage 2: books in SQLite, with filtering and pagination

Now the books move into a database. BookRepository contains all the SQL, as in the earlier projects, and the handlers only call its methods.

The list endpoint accepts three optional query parameters:

  • author filters by author, ignoring case (COLLATE NOCASE in SQLite).
  • page (default 1) and per_page (default 3, at most 50) select one page. The maximum matters: without it, a client could ask for per_page=10000000 and make your server load the whole table into memory.

Invalid values aren't silently replaced with defaults. A request for page=0 or per_page=500 gets a 400 Bad Request that says what's wrong, which is much easier to debug for the developer writing the client than results that quietly don't match what they asked for.

The response includes a meta object with the page, the page size, the total number of matching books and the number of pages, so a client can draw page links without counting anything itself.

Building the WHERE clause dynamically deserves a careful look. The code collects SQL fragments in $where and values in $params. Fragments are fixed strings written by us; values are always passed separately to execute(). That's how you build a flexible query without ever putting user input into SQL text. Pagination, Search and Database Patterns shows the pattern with more filters.

PHP Stage 2: a PDO repository with pagination

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.

This stage leaves the router out so you can focus on the queries; stage 3 brings it back. Seven books with three per page make three pages: page 1 has books 1 to 3, and page 3 has only Mathilda, with "total": 7, "total_pages": 3 in the meta. The author filter finds Mary Shelley's three books even though the URL says mary shelley in lowercase, and per_page=2 returns the first two. page=0 and per_page=500 are 400s with precise messages. author[]=x is a sneaky one: PHP turns it into an array, which the handler rejects instead of passing it to SQL. Single books work as before: book 6 is Middlemarch, book 60 is a 404.

year comes back as a JSON number (1818, not "1818"). Since PHP 8.1 the SQLite and MySQL drivers return integer columns as PHP integers, and json_encode writes them as numbers. Clients written in typed languages care about that difference.

Stage 3: create, replace, update and delete

Writing data is where most of an API's logic lives. Every write request carries a JSON body, and four different things can be wrong with it, each with its own status code:

  1. The Content-Type header isn't application/json โ†’ 415 Unsupported Media Type. Clients sometimes post form data by mistake; telling them clearly saves time.
  2. The body isn't valid JSON โ†’ 400 Bad Request. json_decode with JSON_THROW_ON_ERROR throws a JsonException whose message says what's wrong ("Syntax error").
  3. The JSON isn't an object (for example [1, 2] or "hello") โ†’ 400 as well. Decoding with objects rather than arrays makes this easy to check: a JSON object becomes a stdClass, anything else doesn't.
  4. The object fails validation โ†’ 422 Unprocessable Content, with a message per field in details.

To avoid checking for errors after every step, the helper functions throw an HttpError exception carrying the status code, and dispatch catches it and turns it into a JSON error response. This keeps each handler short and linear. Custom Exceptions discusses this "exceptions for control flow at the boundary" style.

Validation is strict about types. "year": "1818" (a string) is refused, not converted, because an API's contract is the JSON types themselves; a client that sends strings has a bug it should hear about. Unknown fields are refused too, so a typo like "tilte" is reported instead of silently ignored.

PUT and PATCH share the validator with a $partial flag. PUT replaces the book, so every field is required. PATCH changes only the fields it receives, so missing fields are fine, but at least one must be present. Both respond with the updated book, so the client doesn't need a second request to see the result.

A successful POST answers 201 Created with a Location header holding the new book's URL, and DELETE answers 204 No Content with an empty body.

PHP Stage 3: validated writes with correct status codes

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.

Work through the output:

  • The first POST creates book 1 with the title trimmed to Persuasion and answers 201 with Location: /books/1.
  • The form-encoded post is a 415. The trailing comma in {"title": "Emma",} is a 400 with "Invalid JSON: Syntax error", because JSON, unlike PHP, doesn't allow trailing commas. The JSON array is a 400 too.
  • The next post gets a 422 with four entries in details, one per problem field: the typo tilte is unknown, the empty title is too short, author is required and year is a string instead of a number.
  • PATCH with only a year changes the year and returns the whole updated book. PUT with only a title is a 422, because a replacement needs every field, and an empty PATCH is a 422 asking for at least one field.
  • DELETE answers 204 with no body, and the following GET is a 404.

The update() method builds SET title = :title, year = :year from the keys of the validated array. That's safe only because validation has already rejected unknown fields: every key is one of our three column names. Never build SQL from the keys of unvalidated input, or a client could send {"id = 0; --": 1}.

$statement->fetch() ?: throw new HttpError(...) uses throw as an expression (PHP 8.0) after the short ternary ?:. It reads like a sentence: "fetch the row, or else throw a 404". See Exceptions.

Stage 4: authentication and a safety net

Two things separate this API from one you could put online.

Authentication. Anyone may read books, but only clients with an API key may change them. The client sends the key in the standard header Authorization: Bearer <key>. The server stores only a SHA-256 hash of each valid key, like the remember-me validators in the login system project, so a leaked config file or database doesn't hand out working keys. The check uses hash_equals. A missing or wrong key gets 401 Unauthorized with a WWW-Authenticate: Bearer header, which is how HTTP says "you need credentials of this kind". (If a valid key lacked permission for an action, the right code would be 403 Forbidden.)

A safety net. Some errors aren't the client's fault: a database that's down, a bug in our code. dispatch catches every Throwable that isn't an HttpError, logs the real message for you, and sends the client a plain 500 with a generic message. Never send exception messages or stack traces to API clients: they reveal file paths, SQL and library versions to attackers, and they're useless to legitimate users anyway. The demo provokes such an error on purpose by dropping the books table before the last request.

The app is now assembled in one function, createApp(), which returns the router. In the real index.php, that's the only thing you'd call, as the next section shows.

PHP Stage 4: API keys and a 500 safety net

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.

Reading books needs no key, so the first GET works. The POST without a key and the one with a wrong key both get 401 with WWW-Authenticate: Bearer, and the one with the right key creates book 2. The first DELETE sends the key without the Bearer prefix, which isn't the expected format, so it's a 401 as well; with the prefix, book 1 is deleted. PUT isn't supported in this stage, so it's a 405 with Allow: GET, DELETE. Finally, after the table is dropped, GET /books/2 fails inside PDO. The client only sees {"error":"Internal server error"} with status 500, while the server log holds the real cause: a PDOException saying there's no such table.

Notice that authentication runs before the handler and only for routes marked protected: true, a named argument that makes the route list self-explanatory. And the 401 check happens even before the JSON body is parsed, so unauthenticated clients learn nothing about what a valid body looks like.

Running it on a real server

public/index.php converts PHP's view of the request into a Request, dispatches it and sends the Response:

PHP
<?php

declare(strict_types=1);

require __DIR__ . '/../src/api.php';   // Request, Response, Router, createApp(), ...

$pdo = new PDO('sqlite:' . __DIR__ . '/../data/books.sqlite', options: [
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$headers = array_change_key_case(getallheaders());          // all request headers
$request = new Request(
    $_SERVER['REQUEST_METHOD'],
    parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?: '/',
    $headers,
    file_get_contents('php://input'),                        // the raw request body
);

$app = createApp($pdo, fn (string $line) => error_log($line));
$keyHashes = explode(',', getenv('API_KEY_HASHES') ?: '');
$response = $app->dispatch($request, apiKeyChecker($keyHashes));

http_response_code($response->status);
foreach ($response->headers as $name => $value) {
    header("$name: $value");
}
echo $response->body;

php://input is the raw body of the request; $_POST is only filled for form-encoded bodies, never for JSON. The Streams and Wrappers lesson covers it. getallheaders() is available under the built-in server, Apache and PHP-FPM; the same headers are also in $_SERVER as HTTP_AUTHORIZATION, CONTENT_TYPE and so on.

Start the server with php -S localhost:8000 -t public public/index.php, then call the API from another terminal with curl:

Terminal
curl -i http://localhost:8000/books/1

curl -i -X POST http://localhost:8000/books \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer demo-key-7f3a91' \
  -d '{"title": "Kidnapped", "author": "Robert Louis Stevenson", "year": 1886}'

curl -i -X DELETE http://localhost:8000/books/1 -H 'Authorization: Bearer demo-key-7f3a91'

-i prints the status line and headers, so you can check the 201 and the Location header. Calling the API from PHP itself works with the curl extension or file_get_contents with a stream context, as shown in Building a JSON API.

If a JavaScript front end on another domain calls your API, browsers will block the responses unless the API sends CORS headers such as Access-Control-Allow-Origin and answers the browser's preflight OPTIONS requests. Add an OPTIONS route and the headers in dispatch when you need them, allowing only the origins you trust.

Ideas for extending the API

  • Merge stages 2 to 4 into one complete API with listing, filtering, pagination, all write methods and authentication.
  • Search: GET /books?q=night with LIKE and proper escaping of % and _.
  • ETags: send ETag: "<hash of the body>" and answer 304 Not Modified when the client's If-None-Match matches.
  • Rate limiting per API key, with a 429 Too Many Requests status and a Retry-After header.
  • An OpenAPI description of the endpoints, so clients can generate code and documentation from it.
  • Tests: because dispatch takes a Request and returns a Response, you can test every endpoint without a server. See Testing PHP Code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A client posts a valid JSON object that is missing the required author field. Which status code should the API return?

    The request is well-formed JSON, but its content fails validation. 422 says exactly that, with per-field details; 400 is for bodies that can't be parsed at all.
  2. 2. What should a successful POST /books return?

    201 tells the client a resource was created, and Location gives its URL. Returning the book in the body saves the client another request.
  3. 3. Why does the validator reject "year": "1818" instead of converting it to an integer?

    Strict types make the API predictable. Silently converting values hides client bugs and leads to surprises with values like "1818abc".
  4. 4. The database fails while handling a request. What does the client receive?

    Internal details help attackers and confuse users. Log the real cause for yourself and send a generic 500 to the client.
  5. 5. Why is it safe for update() to build the SET clause from the keys of the validated fields?

    Placeholders can only hold values, not column names. Building SQL from keys is safe only when every key has been checked against a whitelist, which validateBook does.

Summary

  • Model HTTP with small Request and Response objects; return responses from handlers instead of echoing, so every endpoint can be tested with simulated requests.
  • Route by method and path; answer 404 for unknown paths and 405 with Allow for unsupported methods.
  • Encode with JSON_THROW_ON_ERROR; read request bodies from php://input and check the content type, the JSON syntax and that the body is an object.
  • Use the right status codes: 200, 201 with Location, 204, 400, 401, 404, 405, 415, 422 and 500.
  • Validate strictly (types, ranges, required and unknown fields) and return per-field errors in a consistent JSON shape.
  • Limit page sizes, build dynamic SQL only from whitelisted fragments and keys, and bind every value.
  • Protect write endpoints with hashed API keys checked by hash_equals, and turn unexpected exceptions into logged, generic 500 responses.

Next: Project: Shopping Cart