Guzzle: Set a header, after instancation?

Created on 17 Sep 2016  路  2Comments  路  Source: guzzle/guzzle

Hello guys,

Sorry for my lack of knowledge of the library. I'm trying to set a header after some actions.

I'm currently working on building a small package for Laravel to make some requests to an API.

Because not all requests will require authentication, I have created a method named login() which I would like to set a header on the GuzzleHttp\Client after it's originally instanciated.

Here's what I currently have, take a closer look at the search() method. This will require authentication and I will need the Authorization header set with a token. So I call the aforementioned login() method before I make my request to set this header.

I'm having trouble finding a way to set a header. Can you help?

<?php

namespace Dawson\TVDB;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

class TVDB
{
    protected $token;

    public function __construct()
    {
        $this->username = config('tvdb.username');
        $this->userkey = config('tvdb.userkey');
        $this->apikey = config('tvdb.apikey');

        $this->client = new Client([
            'base_uri' => 'api.domain.com',
            'headers'  => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
            ]
        ]);
    }

    public function search($name)
    {
        $this->login();

        try {
            return $this->client->get('search/series?name=' . $name)->getBody();
        } catch(ClientException $e) {
            throw new TVDBException($e);
        }
    }

    private function login()
    {
        try {
            $response = $this->client->post('login', ['json' => [
                'apikey'   => $this->apikey,
                'username' => $this->username,
                'userkey'  => $this->userkey
            ]])->getBody();

            $this->token = json_decode($response->getContents())->token;

            // Set a header here?
            $this->client->setHeader('Authorization', 'Bearer' . $this->token);
        } catch(ClientException $e) {
            throw new TVDBException($e);
        }
    }
}

Most helpful comment

Solved this by using a handler.

/** 
 * Handle Authorization Header
 */
private function handleAuthorizationHeader()
{
    return function (callable $handler)
    {
        return function (RequestInterface $request, array $options) use ($handler)
        {
            if($this->token) {
                $request = $request->withHeader('Authorization', 'Bearer ' . $this->token);
            }

            return $handler($request, $options);
        };
    };
}

Then added the handler stack to the Client.

$this->stack = new HandlerStack();
$this->stack->setHandler(new CurlHandler());
$this->stack->push($this->handleAuthorizationHeader());

$this->client = new Client([
    'handler'  => $this->stack,
    'base_uri' => 'https://api.domain.com',
    'headers'  => [
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
    ]
]);

All 2 comments

Solved this by using a handler.

/** 
 * Handle Authorization Header
 */
private function handleAuthorizationHeader()
{
    return function (callable $handler)
    {
        return function (RequestInterface $request, array $options) use ($handler)
        {
            if($this->token) {
                $request = $request->withHeader('Authorization', 'Bearer ' . $this->token);
            }

            return $handler($request, $options);
        };
    };
}

Then added the handler stack to the Client.

$this->stack = new HandlerStack();
$this->stack->setHandler(new CurlHandler());
$this->stack->push($this->handleAuthorizationHeader());

$this->client = new Client([
    'handler'  => $this->stack,
    'base_uri' => 'https://api.domain.com',
    'headers'  => [
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
    ]
]);

@joedawson thanks, it worked for me.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

pionl picture pionl  路  4Comments

novuscom picture novuscom  路  3Comments

Anan5a picture Anan5a  路  4Comments

dapphp picture dapphp  路  3Comments

BentCoder picture BentCoder  路  3Comments