Skip to content
Advertisement

Use a request header with HTTP Client to external Api server

Consider the following request to a Symfony controller:

JavaScript
JavaScript

This code snippet is a minimal example for the usage in a controller. The controller accepts a Request, and uses the x-token header for authenticating against the 3rd Party Api (here: localhost:3001).

Is there a way, to automate this process? So basically – listen to incoming requests and inject the x-token header into a specific Scoped Client or the default client in Symfony.

The goal is, not to do this in every usage of the Http Client, but have a configured client service.

The client will be used all over the codebase, not just in a controller like in this minimal example.

I know that I can use Service Decoration and extend the clients in use. I fail how to connect the dots and make this work.

Advertisement

Answer

Have you tried using symfony kernel events?

First of all, if you are calling some 3rd-party api, I’d suggest you to create a separate class at the infrastructure layer, for example MyApiProvider. Using HttpClient right from your controller is not smart, because you may also want to adjust something (for example api host, etc). So it’s gonna look like this:

JavaScript

Then you need to use symfony’s kernel.request event to inject token to your provider from the request:

JavaScript

And finally your controller:

JavaScript

So your provider is gonna have token context during each request, if the token is passed.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement