Set the Authorization Bearer header in Guzzle HTTP client

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' => '']);

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 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”

  1. 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.


Leave a Reply to cicnavi Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: