How do you return a JSON response from a Symfony controller?

How do you return a JSON response from a Symfony controller?

To return a JSON response from a Symfony controller, follow these minimal steps:

1. Use the JsonResponse Class

Import the JsonResponse class in your controller:

Example

<?php
use Symfony\Component\HttpFoundation\JsonResponse;
?>

2. Create a Method in Your Controller

Define a method in your controller that generates the JSON response:

Example

<?php
// src/Controller/ApiController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;

class ApiController extends AbstractController
{
    public function getData()
    {
        $data = [
            'message' => 'Hello, World!',
            'status' => 'success'
        ];

        return new JsonResponse($data);
    }
}
?>

3. Define the Route

Add a route for your controller method:

Example

<?php
// config/routes.yaml
api_data:
    path: /api/data
    controller: App\Controller\ApiController::getData
?>

Related Questions & Topics