Issue
I am trying to process a GET request in symfony 4 with a JSON response of some kind of string array. How can I handle the request in my Symfony 4 app? Do I use a controller or a service?
Solution
I would suggest you to first decide your code structure and stick to it.
It a advisable to use Controller which gives you extra benefits by extending AbstractController.php.
A controller is a PHP function you create that reads information from the Request object and creates and returns a Response object. The response could be an HTML page, JSON, XML, a file download, a redirect, a 404 error or anything else. The controller executes whatever arbitrary logic your application needs to render the content of a page. Source
<?php
declare(strict_types=1);
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class TestController
* @package App\Controller
*/
class TestController extends AbstractController
{
/**
* @Route(path="test", name="test", methods={"GET"})
* @param Request $request
* @return JsonResponse
*/
public function index(Request $request): JsonResponse
{
$test['a'] = 'A';
$test['b'] = 'B';
$test['c'] = 'C';
return new JsonResponse($test);
}
}
Hope this helps!
Answered By - ts-navghane