When you need to fetch data from some API, you’ll often need to set the Authorization header in your HTTP client.
Here is how to do it using Guzzle.
First, have your token ready:
$token = 'someToken';
Create a Guzzle HTTP client with a base URI:
$client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']);
Next, prepare your headers and include the Authorization header. Note that we simply concatenate ‘Bearer ‘ and $token (include the space between them). In this example we also set the ‘Accept’ header to ‘application/json’, which is a common case:
$headers = [ 'Authorization' => 'Bearer ' . $token, 'Accept' => 'application/json', ];
Next, use your $client to send a request to https://foo.com/api/bar. Include your headers in the request:
$response = $client->request('GET', 'bar', [ 'headers' => $headers ]);
7 thoughts on “Set the Authorization Bearer header in Guzzle HTTP client”
Hi I tried but it never worked for me could you please help?
What error do you get?
I have not been able to get guzzle to work on POST request with Authorization header equals Bearer token and a body component. I could extend the explanation for POST request a bit.
Do you get any specific error?
I tried to set header but.. my url dont redirect. Please I need ur urgent help
This worked perfectly well, thank you!!
ty so much this worked perfect