Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony Http Client default headers not added

Tags:

http

symfony

I'm using the Http Client to send a request to an external API. According to the documentation I can add default headers to a specific route like so:

framework:
  http_client:
    scoped_clients:
      the_api:
        base_uri: '%env(the_url)%'
        headers:
          Authorization: 'Bearer %env(my_token)%'

That doesn't work for me. I also tried this option:

auth_bearer: '%env(my_token)%'

same effect.

In the service I use to make the request I have:

$response = $client->request('POST', $theUrl, [
    'body' => $dataArray
]);

With the above configuration I get a 403 response, as if the token is not sent. If I add it to the request() function however it works:

$response = $client->request('POST', $theUrl, [
    'body' => $dataArray,
    'headers' => [
        'Authorization' => 'Bearer ' . $myToken
    ]
]);

I'm looking for a way to avoid fetching the token in my service or controller. In the future I might send other requests to the API (or a different API) and I don't want to set the token for each one.

If it matters $theUrl is https. Symfony and Http Client versions: 4.4

like image 388
Martin M. Avatar asked Jul 08 '20 08:07

Martin M.


1 Answers

You must use the client name the_api in your case.

#config/packages/framework.yaml
framework:
    http_client:
        scoped_clients:
            name_client:
                base_uri: 'http://ip:port/'
                auth_basic: 'user:password'

client name here name_client

#src/Controller/MyController.php
...
public function __construct(HttpClientInterface $name_client)
{
    $this->client = $name_client;
}
...

$name_client will contain an instance of the ScopingHttpClient class with the specified parameters

Enjoy!

like image 94
Денисов Иван Avatar answered Oct 24 '22 17:10

Денисов Иван