JSON controllers

Contents
$this->json()
Status codes
Serialization groups preview
Error JSON shape

$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

Related articles
Development with PHP
What is Symfony and where it runs
Install Symfony
Your first page
Routes
Controllers
Twig basics
Twig advanced
Doctrine setup
Entities
Migrations
Repositories
Relations
Forms
Validation
Services and DI
JSON controllers
Serializer
Security intro
Users
Login form
Voters
Console commands
Events
Messenger
Mailer
Cache
Sessions
CSRF
Translations
Dotenv and env
Profiler
Testing
Fixtures
Pagination
File uploads
API Platform in one lesson
DQL
Transactions
Migrations advanced
Security advanced
HTTP client
Scheduler
Webhooks
Asset Mapper
Deployment
Performance
Capstone: blog
Capstone: JSON API
Modern Symfony tour
Hero roadmap: the whole course on one page
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: