Home > Enterprise >  setStatusCode() in a JSON is returning headers inside the body
setStatusCode() in a JSON is returning headers inside the body

Time:10-21

I'm developing an API using PHP and Symfony 5.

In the authentication method, I need to return a JWT Token, and the headers with code 201 Created, so I used this code:

// RETURN MESSAGE
$body = [
    'auth_token' => $jwt,
];
$json = new JsonResponse($body);
$json->setStatusCode(201, "Created");
return new Response($json);

Where $jwt was generated previously.

With this, I was expecting to get a header with the 201 Created code, and a body with the JWT token, but what I am getting (using Postman) is this:

enter image description here

As you can see, everything is getting inside the body and the header real code is 200 Ok. Am I missing something?

CodePudding user response:

You should be returning the JsonResponse.

But you are for some reason wrapping the JsonResponse on another Response object.

Just do:

$body = [
        'auth_token' => $jwt,
];

$json = new JsonResponse($body);
$json->setStatusCode(201, "Created");

return $json;

A JsonResponse object already extends Response, it's simply a convenient way to create a response with application/json Content-Type headers, and to automatically encode to JSON whatever payload you want to return.

  • Related