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