Search code examples
symfonyheaderfosrestbundle

Symfony FOSRestBundle add custom header to response


I use FOSRestBundle in Symfony 4 to API project. I use annotations and in controller I have for example

use FOS\RestBundle\Controller\Annotations as Rest;

/**
 * @Rest\Get("/api/user", name="index",)
 * @param UserRepository $userRepository
 * @return array
 */
public function index(UserRepository $userRepository): array
{
return ['status' => 'OK', 'data' => ['users' => $userRepository->findAll()]];
}

config/packages/fos_rest.yaml

fos_rest:
    body_listener: true
    format_listener:
        rules:
            - { path: '^/api', priorities: ['json'], fallback_format: json, prefer_extension: false }
    param_fetcher_listener: true
    view:
        view_response_listener: 'force'
        formats:
            json: true

Now I'd like to add custom header 'X-Total-Found' to my response. How to do it?


Solution

  • You are relying in FOSRestBundle ViewListener, so that gives you limited options, like not being able to pass custom headers. In order to achieve what you want, you will need to call $this->handleView() from your controller and pass it a valid View instance.

    You can use the View::create() factory method or the controller $this->view() shortcut. Both take as arguments the array of your data, the status code, and a response headers array. Then, you can set up your custom header there, but you will have to do that for every call.

    The other option you have, which is more maintainable, is register a on_kernel_response event listener/subscriber and somehow pass it the value of your custom header (you could store it in a request attribute for example).

    Those are the two options you have. You may have a third one, but I cannot come up with it at the minute.