15

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.

Community
  • 1
  • 1
rajesh
  • 239
  • 2
  • 6
  • 21

2 Answers2

26

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();
Bhaumik Pandhi
  • 2,655
  • 2
  • 21
  • 38
0

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

$access_token = 'bearer '.$request->headers->access_token
Shamim Shams
  • 151
  • 1
  • 8