Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 427
rajesh Avatar asked Jan 24 '18 09:01

rajesh


1 Answers

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();
like image 129
Bhaumik Pandhi Avatar answered Oct 14 '22 00:10

Bhaumik Pandhi