Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 62 ยท APIs

Building JSON APIs

Design a JSON API in Symfony: JsonResponse, honest status codes, one error format, pagination and versioning, plus a runnable mini API stand-in.

A JSON API is a web application whose clients are programs: a mobile app, a single-page front end, another server. There is no HTML to look at, so the contract is everything: the URLs, the methods, the shape of the JSON, the status codes and the error format. If that contract is predictable, client developers can guess most of it without reading the docs.

Symfony gives you the pieces: routing, the request object, JsonResponse, validation and the serializer. This lesson is about using them well: resource-oriented URLs, status codes that tell the truth, one error shape for every failure, pagination, and versioning. At the end you will run a tiny API stand-in in plain PHP.

Resources, methods and status codes

Model your API around nouns (resources) and let the HTTP method be the verb:

Request Meaning Success status
GET /api/books List books 200
GET /api/books/7 Show one book 200
POST /api/books Create a book 201 plus a Location header
PUT /api/books/7 Replace a book 200
PATCH /api/books/7 Change some fields 200
DELETE /api/books/7 Remove a book 204 with no body

The failure statuses matter just as much:

  • 400: the request itself is broken (invalid JSON).
  • 401: the client did not prove who it is. 403: it did, but is not allowed.
  • 404: no such resource. 405: the method is not allowed on this URL.
  • 409: a conflict, such as a duplicate ISBN.
  • 422: the JSON is well formed but fails validation.
  • 500: a bug on your side. Never use it for client mistakes.

Do not answer 200 with {"success": false}. HTTP clients, caches, monitoring tools and retry logic all read the status code. Make it carry the outcome.

A controller in real Symfony

Here is a small controller as you would write it with the Serializer and Validator installed. It is read-only on this site because Symfony cannot run in the browser.

PHP
// src/Controller/BookApiController.php (real Symfony, read-only)
namespace App\Controller;

use App\Dto\CreateBook;
use App\Repository\BookRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/api/books')]
final class BookApiController
{
    public function __construct(private BookRepository $books)
    {
    }

    #[Route('', methods: ['GET'])]
    public function list(): JsonResponse
    {
        return new JsonResponse(['data' => $this->books->findAllAsArrays()]);
    }

    #[Route('/{id<\d+>}', methods: ['GET'])]
    public function show(int $id): JsonResponse
    {
        $book = $this->books->find($id);

        if ($book === null) {
            return new JsonResponse(
                ['error' => ['code' => 'not_found', 'message' => 'Book not found.']],
                Response::HTTP_NOT_FOUND,
            );
        }

        return new JsonResponse(['data' => $book]);
    }

    #[Route('', methods: ['POST'])]
    public function create(#[MapRequestPayload] CreateBook $input): JsonResponse
    {
        $book = $this->books->add($input->title, $input->author);

        return new JsonResponse(
            ['data' => $book],
            Response::HTTP_CREATED,
            ['Location' => '/api/books/'.$book['id']],
        );
    }

    #[Route('/{id<\d+>}', methods: ['DELETE'])]
    public function delete(int $id): Response
    {
        $this->books->remove($id);

        return new Response(null, Response::HTTP_NO_CONTENT);
    }
}

Three habits are visible here. The class-level #[Route('/api/books')] prefixes every method. The constants on Response (HTTP_CREATED, HTTP_NO_CONTENT) read better than bare numbers. And the controller returns arrays or objects, never echoes.

JsonResponse encodes the data with json_encode, sets Content-Type: application/json and, by default, escapes characters such as < and & so the output is safe to embed in HTML. When your data is an object graph rather than an array, the shortcut $this->json($data) from AbstractController runs it through the Serializer when that component is installed. The next lesson covers it.

One error format for everything

The most useful thing you can do for client developers is to make every failure look the same. Pick a shape and use it for 404s, validation errors and crashes:

JSON
{
  "error": {
    "code": "validation_failed",
    "message": "The request body is invalid.",
    "details": { "title": "must not be blank" }
  }
}

code is for programs (stable, machine-readable), message is for humans, and details is optional extra data. A standard alternative is problem details (RFC 9457, the application/problem+json media type), and Symfony's Serializer ships an error normalizer that can produce it. Either is fine; consistency is what counts.

Instead of building error responses in every controller, throw an exception and convert it in one place. In Symfony that place is a listener on the kernel.exception event (see events), which receives the exception and may set a response. Controllers can then throw NotFoundHttpException or UnprocessableEntityHttpException and stay short.

flowchart LR
    C["Client"] --> K["Kernel"]
    K --> A["Controller"]
    A -->|returns data| R["JsonResponse 200/201"]
    A -->|throws HttpException| L["Exception listener"]
    L --> E["JsonResponse with error shape<br/>(404, 422, ...)"]
    R --> C
    E --> C

Successful results and thrown exceptions both end as a JSON response with a meaningful status code.

Pagination, filtering and versioning

Never return an unbounded list. Accept page and limit (or a cursor), cap the limit, and return enough metadata for the client to continue:

JSON
{
  "data": [ ... ],
  "meta": { "page": 2, "per_page": 10, "total": 37 }
}

#[MapQueryString] from the mapping lesson is a neat way to validate ?page=2&limit=500 before your controller sees it.

For versioning, the simplest approach that works is a version in the path: /api/v1/books. In Symfony you put #[Route('/api/v1/books')] on the controller, or load a whole controller directory with a prefix in config/routes.yaml. Alternatives are a custom header or media type, but they are harder to try in a browser and to cache. Keep changes within a version backwards compatible (add fields, never rename or remove them), and only create v2 for a real breaking change.

A runnable mini API

The stand-in below is not Symfony. It is a tiny router plus a handler per route that returns [status, headers, body], with the same error shape everywhere. It shows what your controllers should look like from the outside.

PHP A mini JSON API with one error format (stand-in)

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 from top to bottom. The list and the show return 200; the unknown id returns 404 in the standard error shape; the successful POST returns 201 with a Location header; a blank title gives 422 with a details object; broken JSON gives 400; a wrong method gives 405; and DELETE returns 204 with no body at all. Every failure has the same error object, which is exactly what an exception listener would produce in a real application.

Keeping responses consistent with a helper

When a project grows, put the repeated parts in one place so no controller formats errors by hand. The next example turns the pagination rules from earlier into code: it clamps the page size, calculates the metadata and builds a stable envelope.

PHP A paginated envelope with a capped page size

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.

Notice that asking for limit=500 is silently reduced to the cap of 5, and that page 9 (past the end) is clamped to the last page. Some APIs prefer to return an empty list or a 400 for an out-of-range page; what matters is that the rule is documented and the same everywhere.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A client sends a JSON body that is valid JSON but has a blank required field. Which status fits best?

    The request is well formed but fails validation, which is what 422 means. 500 is reserved for bugs on the server.
  2. 2. What should a successful POST that creates a resource normally return?

    201 tells the client something was created, and the Location header says where to find it.
  3. 3. Why is it better to throw HTTP exceptions and convert them in one listener than to build error responses in each controller?

    A single place that turns exceptions into JSON keeps the error format consistent and the controllers focused on the happy path.
  4. 4. Which versioning approach is the simplest to use and test in a browser?

    A path prefix is visible, easy to route in Symfony and easy to cache. Breaking changes belong in a new version.

Summary

  • Design around resources and let the HTTP method be the verb; return 201 for creation, 204 for empty success and 404, 405, 409 or 422 for the matching failures.
  • Status codes carry the outcome: do not hide errors inside a 200 response.
  • Use one error shape (code, message, optional details, or RFC 9457 problem details) and produce it in a single exception listener.
  • Paginate every list, cap the page size and return metadata.
  • Version in the path, and keep changes inside a version additive.
  • The runnable examples are plain-PHP stand-ins; the controller code is real Symfony and read-only here.

Next up: The Serializer Component.