rajesh
rajesh

Reputation: 249

How to add headers in Guzzle http

I'm building a small application in Laravel 5.5 where I'm using Guzzle Http to get call the api url and get the response, Few of the api calls have certain condition to have headers which works as authorization of the request generated. I'm trying to place the header something like this:

public function post(Request $request)
{
    try {
        if ($request->url_method == 'get') {
            $request = $this->client->get($request->url, [ 'headers' => [ 'access_token' => $request->headers->access_token]]);
        }
        else if ($request->url_method == 'post')
        {  $request = $this->client->post($request->url, [$request->request_data]);  }
        else { return response()->json(['data' => 'Invalid Method'],500);   }

        $response = \GuzzleHttp\json_decode($request->getBody());
        return response()->json(['data' => json_decode($response->d)], $request->getStatusCode());
    }
    catch (ClientException $e) {
        return response()->json(['data' => 'Invalid Request.'], $request->getStatusCode());
    }
}

But this is giving me errors:

Undefined property: Symfony\Component\HttpFoundation\HeaderBag::$access_token

Please checkout the screenshot:

Guzzle HTTP client error

Also when calling through the browser in console it gives me the same error:

Browser console error

Help me out in this, Thanks.

Upvotes: 15

Views: 41141

Answers (2)

Shamim Shams
Shamim Shams

Reputation: 181

Try to add bearer in all small cases before access token like following -

$access_token = 'bearer '.$request->headers->access_token

Upvotes: 0

Bhaumik Pandhi
Bhaumik Pandhi

Reputation: 2673

try this code

use GuzzleHttp\Client as GuzzleClient;
..
..
..
$headers = [
    'Content-Type' => 'application/json',
    'AccessToken' => 'key',
    'Authorization' => 'Bearer token',
];

$client = new GuzzleClient([
    'headers' => $headers
]);

$body = '{
    "key1" : '.$value1.',
    "key2" : '.$value2.',
}';

$r = $client->request('POST', 'http://example.com/api/postCall', [
    'body' => $body
]);
$response = $r->getBody()->getContents();

Upvotes: 26

Related Questions