JSON controllers

$this->json()

API actions return data, not pages. The $this->json helper converts arrays and objects into a response with the right content type headers.

Pass any nested array and it just works. The helper lives on the base controller, so every action can call it directly.

return $this->json(["name" => "Symfony", "runs" => "everywhere"]);

Status codes

The second argument sets the HTTP status. Browsers and API clients read that number before they read the body.

Return 201 after a create and 404 for a missing item. The default is 200, so successful reads need no second argument.

return $this->json(["created" => true], 201); return $this->json(["error" => "Missing product"], 404);

Serialization groups preview

Objects serialize every field by default, including internal ones. Groups mark the fields that belong to one answer shape.

The context argument carries the group list. The next lesson shows how groups attach to properties.

return $this->json($product, 200, [], ["groups" => ["product_show"]]);

Error JSON shape

Keep errors predictable: the same keys on every endpoint. Clients parse one shape instead of guessing per action.

An error key with human words plus a numeric code covers most cases. Match the code inside the body with the real HTTP status.

return $this->json(["error" => "Not found", "code" => 404], 404);

Next: Serializer

Article author: Arthur Isaev