How to Set Custom Status Code in Symfony (with Examples)

Updated: January 14, 2024 By: Guest Contributor Post a comment

Introduction

When building web applications with Symfony, one of the powerful features at our disposal is the ability to control HTTP response status codes. These status codes are essential in communicating the status of the request between the server and the client. Symfony makes setting custom status codes straightforward and, in this tutorial, we will delve into how to set custom status codes in Symfony.

Understanding HTTP Status Codes

HTTP status codes are issued by a server in response to a client’s request to the server. The codes are divided into five categories:

  • 1xx (Informational): The request was received, continuing process.
  • 2xx (Success): The action was successfully received, understood, and accepted.
  • 3xx (Redirection): Further action needs to be taken to complete the request.
  • 4xx (Client Error): The request contains bad syntax or cannot be fulfilled.
  • 5xx (Server Error): The server failed to fulfill an apparently valid request.

Setting Custom Status Codes in Symfony

To set a custom status code in Symfony, you’ll usually modify the Response object. The Symfony Response class is part of the HttpFoundation component which makes managing HTTP messages a breeze.

Basic Response with Custom Status

Here’s the simplest way to return a custom status code:

use Symfony\Component\HttpFoundation\Response;

public function index(): Response
{
   $response = new Response();
   $response->setStatusCode(Response::HTTP_CREATED);  // sets status to 201 Created
   return $response;
}

Alternatively, you can set the status code directly when creating the response like so:

use Symfony\Component\HttpFoundation\Response;

public function index(): Response
{
   return new Response('', Response::HTTP_CREATED);
}

Returning JSON Response with Status Code

Let’s say we are working with an API and want to return a JSON response with a custom status code. You can use the JsonResponse class to achieve this:

use Symfony\Component\HttpFoundation\JsonResponse;

public function apiResponse(): JsonResponse
{
   $data = [
      'success' => true,
      'data' => $yourDataHere,
   ];
   return new JsonResponse($data, Response::HTTP_OK);  // 200 status code
}

To indicate a different status, for example when a resource is not found:

use Symfony\Component\HttpFoundation\JsonResponse;

public function notFoundResponse(): JsonResponse
{
   $data = ['error' => 'Resource not found'];
   return new JsonResponse($data, Response::HTTP_NOT_FOUND);  // 404 status code
}

Advanced Customizations

Sometimes setting just the status code isn’t enough. Symfony also allows you to set headers and content. Here is an example of returning a custom header alongside the status code:

use Symfony\Component\HttpFoundation\Response;

public function customHeaderResponse(): Response
{
   $response = new Response();
   $response->headers->set('Custom-Header', 'value');
   $response->setStatusCode(Response::HTTP_ACCEPTED);
   return $response;
}

And if you need to send custom content along with the status code:

use Symfony\Component\HttpFoundation\Response;

public function customContentResponse(): Response
{
   $content = 'Custom content goes here';
   $response = new Response($content, Response::HTTP_NON_AUTHORITATIVE_INFORMATION);
   $response->headers->set('Content-Type', 'text/plain');
   return $response;
}

Setting Status Codes in Controllers

In Symfony controllers, setting status codes can be part of controller action logic. For clarity, the Symfony AbstractController offers helper methods to streamline this process. Here is an example using the createNotFoundException which automatically sets a 404 status:

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class MyController extends AbstractController
{
   public function someAction($id)
   {
      $entity = $this->getDoctrine()->getRepository(Entity::class)->find($id);
      if (!$entity) {
         throw $this->createNotFoundException('The entity does not exist.');
      }
      // ... return a response if the entity exists
   }
}

Exception Handling and Status Codes

In Symfony, exception handling is a powerful feature for fluid control flow. Custom exceptions can be used to render a response with a desired status code as part of an exception’s handling strategy. Have a look at this custom exception handler implementation:

use Symfony\Component\HttpKernel\Exception\HttpException;

// ... within your controller method

if ($someConditionIsNotMet) {
   throw new HttpException(Response::HTTP_BAD_REQUEST, 'Invalid request parameters');
}

Additionally, you can handle exceptions globally by creating an event listener or subscriber that listens to the kernel.exception event. In the event handler, you can set the response along with the appropriate status code based on the exception triggered.

Conclusion

Setting custom status codes in Symfony is essential for proper RESTful API development and enhances the communication between your application and its clients. By leveraging Symfony’s Response and JsonResponse classes, along with handling exceptions, you can effectively manage and signal the status of HTTP requests. Remember to use appropriate status codes to convey the accurate status of each request, and be mindful of the associated semantics of each code.

With this guide, you are now more prepared to tackle status code management in your Symfony projects. Happy coding!