Why is my Authorization Header giving me a 401 in Guzzle? - php

I am getting a 401 on Guzzle 4.2 and the same setup works on Postman. Code below.
// Create a client with a base URL
$client = new GuzzleHttp\Client(['base_url' => 'cloud.feedly.com/v3/streams/contents?streamId=user/user-id/category/global.all&count=1']);
// Send a request to https://github.com/notifications
$response = $client->get();
//Auth
$response->addHeader('Authorization', "auth-code");
//send
$r = $response->send();
dd($r->json());
The error is:
GuzzleHttp \ Exception \ ClientException (401)
Client error response [url] cloud.feedly.com/v3/streams/contents?streamId=user/user-id/global.all&count=1 [status code] 401 [reason phrase] Unauthorized

Looking at the documentation page as per this line:
$response = $client->get();
It will send a get request, with no authorisation, hence the 401 response.
Try the following instead
// Create a client with a base URL.
$client = new GuzzleHttp\Client();
$request = $client-> createRequest('GET', 'cloud.feedly.com/v3/streams/contents?streamId=user/user-id/category/global.all&count=1');
$request->setHeader('Authorization', "auth-code");
// Send.
$response = $client->send($request);
dd($response->json());
The above creates a request, set the authorisation header on it. Then once prepared it actually sends it.
I think it worked in Postman because your headers are set, if you remove the authorization header it will likely fail there too.
I have not tested this but think it will work.

$response = $client->get('GET', 'cloud.feedly.com/v3/streams/contents?streamId=user/user-id/category/global.all&count=1', ['auth' => ['YOUR_USERNAME', 'YOUR_PASSWORD']]);
The 401 error means you should authenticate yourself with a valid username and password
Regards

Related

response bad request in http request with php

When i try to send a http request it return me a status 400 (Bad request , invalid headers)
the API require an access token and Content Type:application/x-www-form-urlencoded
this is my code :
the access token is very long
please help me
$response = Http::contentType('application/x-www-form-urlencoded')
->withToken($access_token)
->timeout('2000')
->get('https://example /.../...',[
]);`
use withHeaders() ref link https://laravel.com/docs/8.x/http-client#headers
$response = Http::withHeaders(["Content-Type"=>"application/x-www-form-urlencoded"])
->withToken($access_token)
->timeout('2000')
->get('https://example /.../...',[
]);`

How to handle 401 Response from Guzzle Client

I make a Guzzle 6 request, and this request responses with a 401.
$client = new Client();
$response = $client->request('GET', ....
....
My Script will stop then and will return a error message.
GuzzleHttp \ Exception \ ClientException (401)
Client error: GET https://.....?lang=de resulted in a 401 Unauthorized response: Unauthorized
Try catch does not work.
How can I intercept the error message?
Thanks for help!
I found the error.
I have added the parameter
'http_errors' => false
http://docs.guzzlephp.org/en/stable/request-options.html#http-errors
Now I can check the response status:
if ($response->getStatusCode() != 200) {
echo "error";
}
We need more code to help you, which parameters you use, what is your request, etc ...
You can try to send your request with Postman to check if your parameter are correcly sended

Get Request Information from Promise Or Response Guzzle 6.0

I want to get information about the request I have sent, such as url, body sent etc. I am using the Async feature which uses promises (example below)
$client = new \GuzzleHttp\Client();
return new \GuzzleHttp\Psr7\Request\Request('POST', $this->getUrl(), $this->getHeaders(), $this->getBody());
Is there a way where I can get request information from the promise or from the response?
Reason I am asking this is because I need to store some information about the request in the database later on, which can not be done before I sent the request.
What I tried so far is
Getting the information from the promise with the following methods
$promise->getRequest()
$pomise->Request
$promise->request
$promise->getHandlers()
Thank you
When you initialize a new Request then you have to send it. It's not sent by default. A request is sent when a Client calls send method on it. When request is completed you have access to all information about response:
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Client;
$client = new Client();
$request = new Request('GET', 'https://www.google.com');
$response = $client->send($request);
$response->getHeaders(); // array of all retreived headers
$response->getStatusCode(); // http status code
$response->getReasonPhrase(); // http status phrase
and you initialized a wrong Request object, Guzzle is not shipped with \GuzzleHttp\Psr7\Request\Request but \GuzzleHttp\Psr7\Request.
Now with a correct way of sending a request, getting request information is as simple as below:
print_r($request->getHeaders()); // array of all sent headers
echo $request->getUri(); // requested URI

Guzzle throws 401 or 406 exception

cURL works fine:
curl -H "X-ApiToken: myapitoken" https://api.fulcrumapp.com/api/v2/records
Guzzle does not:
$client = new Client();
$request = $client->createRequest('GET', "https://api.fulcrumapp.com/api/v2/records");
$request->setHeader("X-ApiToken:" , "myapitoken");
$response = $client->send($request);
This responds with a 401 error: not authorized. This is my first time using Guzzle but in my searches I haven't seen this error. Seems like a simple request so I'm not sure why it is failing.
Thank you!
I had to add another header to explicitly tell it to handle json
$request->setHeader("Accept" , "application/json");
Thank you for pointing out that the 401 was a false error - the real error was the 406, which made me read how to actually fix that.
The setHeader method takes the header name without the colon. Change "X-ApiToken:" to "X-ApiToken".

Guzzle and Stack Exchange API, parsing error "JSON_ERROR_UTF8"

I'm trying to consume the Stack Exchange API with Guzzle. I am facing an issue where I can't get the JSON response back: it apparently fails when parsing it.
Here is my code:
$client = new GuzzleHttp\Client();
$parameters = ['pagesize'=>'2','order'=>'desc','sort'=> 'activity','q'=>'laravel eloquent','site'=>'stackoverflow'];
$response = $client->get('http://api.stackexchange.com/2.2/search/advanced',['query' => $parameters ]);
The resultant effective URL that Guzzle creates is correct: if you open the link in your browser you'll see that it works fine and returns the requested data.
However, Guzzle fails with this error when trying to access the JSON with $response->json():
GuzzleHttp \ Exception \ ParseException
Unable to parse JSON data: JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded
After reading the documentation again, I believe that the request is compressed and I am not passing the appropriate content header. If this is so, can you please let me know which header I should be passing to get the correct response?
Ok so the following code works for me.
$client = new GuzzleHttp\Client();
$parameters = ['pagesize'=>'2','order'=>'desc','sort'=> 'activity','q'=>'laravel eloquent','site'=>'stackoverflow'];
$params = http_build_query($parameters);
$request = $client->createRequest('GET', 'http://api.stackexchange.com/2.2/search/advanced?'.$params);
$request->addHeader('Accept-Encoding','GZIP');
$request->addHeader('Content-Type','application/json');
$response = $client->send($request);
var_dump($response->json());

Categories