I'm trying to figure out a way to make a request to a REST api using some PHP client.
Authorization: Token token="CREDENTIALS"
I can successfully curl it by using
$ curl -H 'Authorization: Token token="CREDENTIALS" https://uriexample.com
But I can't figure out a way to set this header in any PHP client I tried (Guzzle and Httpful).
Would anyone know how can I do this with ANY PHP client? I just don't wanna code this client from scratch :(
The Guzzle docs have loads of examples if you dig into them a little.
http://docs.guzzlephp.org/en/latest/quickstart.html#making-a-request
http://docs.guzzlephp.org/en/latest/request-options.html#headers
<?php
// Create HTTP client with headers for all requests
$client = new GuzzleHttp\Client([
'base_uri' => 'https://uriexample.com',
'headers' => [
'Authorization' => 'Token token="CREDENTIALS"',
],
]);
// Dispatch GET request
$client->request('GET', '/');
// OR
// Create HTTP client
$client = new GuzzleHttp\Client([
'base_uri' => 'https://uriexample.com',
]);
// Dispatch GET request with specific headers
$client->request('GET', '/', [
'headers' => [
'Authorization' => 'Token token="CREDENTIALS"',
],
]);
Related
First time using HTTP Client and Spotify API in Laravel.
The first step is to get a code by visiting
https://accounts.spotify.com/authorize?client_id=c1990...deed3&response_type=code&redirect_uri=http%3A%2F%2Fexample.test%2F&scope=user-read-currently-playing%20user-top-read
I then copy the code from the url after being redirected.
Then using curl -
curl -H "Authorization: Basic YzE5OT...Q2ZjA=" -d grant_type=authorization_code -d code=AQBX...X5zg -d redirect_uri=http%3A%2F%2Fexample.test%2F https://accounts.spotify.com/api/token
This returns the refresh token in JSON format -
{
"access_token":"BQBQL...vNDQ",
"token_type":"Bearer",
"expires_in":3600,
"refresh_token":"AQCy...areM",
"scope":"user-read-currently-playing user-top-read"
}
But then I can't seem to get an access token using the refresh_token.
I'm getting "Bad Request" statusCode: 400 in my app
$response = Http::withHeaders([
'Authorization' => `Basic YzE5O...Q2ZjA`,
'Content-Type' => 'application/x-www-form-urlencoded'
])
->asForm()
->post(
'https://accounts.spotify.com/api/token',
[
'grant_type' => 'refresh_token',
'refresh_token' => 'AQC7...YphY'
]
);
Here is the documentation https://developer.spotify.com/documentation/general/guides/authorization/code-flow/.
Has anyone implemented this before in Laravel and if so how?
I have no idea about the Spotify API, but I am 99% sure your error is ->asForm(), you are sending that as a form instead of a normal request... so your code may need to be like this:
$response = Http::withToken('YzE5O...Q2ZjA')
->post(
'https://accounts.spotify.com/api/token',
[
'grant_type' => 'refresh_token',
'refresh_token' => 'AQC7...YphY'
]
);
See that I have removed ->asForm() and Content-Type (not sure why you are using that, it is a normal API... and ->asForm() already sets the same content you have manually set...
This is the Spotify API and I do not see any need to set the Conetnt-Type.
My bad, you need to set the ->asForm(), so the code should be:
$response = Http::withToken('YzE5O...Q2ZjA')
->asForm()
->post(
'https://accounts.spotify.com/api/token',
[
'grant_type' => 'refresh_token',
'refresh_token' => 'AQC7...YphY'
]
);
But I still think you are missing something. Check that your refresh_token is correct. Also lookf for more debugging output
This worked for me.
'Content-Type' => 'application/x-www-form-urlencoded' was removed from withHeaders
$response = Http::withHeaders([
'Authorization' => 'Basic ' . 123...123,
])
->asForm()
->post(
'https://accounts.spotify.com/api/token',
[
'grant_type' => 'refresh_token',
'refresh_token' => 123...456
]
);
I try to get a list of messages from the currently logged in user. I am using Guzzle client to make a request. Unfortunately I don't quite understand the Google docs about the API.
This is what I have so far:
$client = new Client;
$headers = [
'content-type' => 'application/json',
'Authorization' => 'Bearer '.$token->access_token
];
$params = [
'maxResults' => 10,
'client_id' => config('gmail.clientId'),
'client_secret' => config('gmail.clientSecret'),
];
$response = $client->get('https://www.googleapis.com/gmail/v1/users/me/messages', [
$headers,
$params
]);
With this code I receive a message "Error 401 - Login Required". How can I achieve this? In my application every user is connected to their own Gmail account. The access_tokens are saved in a database.
I'm not sure about the Google API that you are using, but you definitely have a Guzzle-related mistake:
$response = $client->get('https://www.googleapis.com/gmail/v1/users/me/messages', [
'headers' => $headers,
'query' => $params,
]);
Also according to the docs, you don't need to supply client_id and client_secret upon every request. Take a look at Google's official auth lib for PHP, or/and at the complete SDK.
I am trying to make a post on laravel using Guzzle. I already got one post working but that one doesn't have a header that I need. The problem is when I try to include that same header and raw JSON body I always get the error: MethodNotAllowedHttpException. From my understanding this is the post request function with some structural error (just my thinking).
My code is the following:
$response = $client->request('POST', $url, [
'headers' => [
'Content-Type' => 'application/json',
'x-auth-token' => $token,
],
'body' => $body
]);
The code above is returning the error.
The following code (from a different function with different goals) just doesn't have the 'x-auth-token' header and it is working just fine:
$response = $client->request('POST', $url, [
'headers' => [
'Content-Type' => 'application/json',
],
'body' => $body
]);
$token = $response->getHeader('X-Subject-Token')[0];
Update: The error that i get is: Expecting to find auth in request body. The server could not comply with the request sin.
I have a problem with translating curl to guzzle request.
In docs to create a user i just need to post:
$ curl -XPOST -d '{"username":"test", "password":"super_secret_password"}' -H "Content-Type:application/json" -u "$CLOUDMQTT_USER:$CLOUDMQTT_PASSWORD" https://api.cloudmqtt.com/user
In my project I cannot use curl, so i use guzzle:
$client = new Client();
$res = $client->post('https://api.cloudmqtt.com/user', ['auth' => ['xxx', 'xxx'], 'body' => ["username"=>"user", "password"=>"super_secret_password"]]);
And user is created, I can see new user on the users list on panel, but server is responsing with 500 when creating the user. What am I doing wrong? Maybe my guzzle request is wrong format? I have no idea
https://www.cloudmqtt.com/docs-api.html link to API
This will match up your Guzzle request to the curl request, although I can't say for sure that will solve your 500 error:
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$response = $client->post('https://api.cloudmqtt.com/user',
[
'auth' => ['xxx', 'xxx'],
'body' => json_encode(
[
"username"=>"user",
"password"=>"super_secret_password"
]
)
]
);
The differences here include setting the Content-Type header and also encoding the body to json instead of an array (which may not have an effect here?).
EDIT:
It looks like the json parameter will automatically set the header and json_encode the body for you:
$client = new Client();
$response = $client->post('https://api.cloudmqtt.com/user',
[
'auth' => ['xxx', 'xxx'],
'json' =>
[
"username"=>"user",
"password"=>"super_secret_password"
]
]
);
Docs
I'm trying to make a connection with infojobs-api, the documentation explian how to make it in this way:
GET /api/1/application HTTP/1.1
Host: api.infojobs.net
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==,Bearer 07d18fac-77ea-461f-9bfe-a5e9d98deb3d
(https://developer.infojobs.net/documentation/user-oauth2/index.xhtml)
And this is my code:
$basicauth = new Client(['base_uri' => 'https://api.infojobs.net']);
$credentials = base64_encode(CLIENT_ID .':' . CLIENT_SECRET ) ;
$newresponse = $basicauth->request(
'GET',
'api/1/curriculum',
['debug' => true],
['auth' =>
['Basic', $credentials] ,
['Bearer', $acceso->access_token]
]
)->getBody()->getContents();
d($newresponse);
The API/Guzlle give me back this error:
Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: GET https://api.infojobs.net/api/1/curriculum resulted in a 401 No Autorizado response:
{"error":"102","error_description":"Client credentials not valid","timestamp":"2016-06-25T14:08:54.774Z"}
in /app/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:107
So I'm doing something wrong, but I don't find what it's wrong.
Any idea, thanks.
Oskar
As I'm seeing your request's HTTP headers:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==,Bearer 07d18fac-77ea-461f-9bfe-a5e9d98deb3d
You have an Authorization header which contains a comma separated value. They are not apart from each other. So you can't benefit from Guzzle's auth key like what you have done.
What you should do is setting Authorization header manually:
$newresponse = $basicauth->request(
'GET',
'api/1/curriculum',
['debug' => true],
['headers' =>
[
'Authorization' => "Basic {$credentials},Bearer {$acceso->access_token}"
]
]
)->getBody()->getContents();
For a post call this works for me:
$guzzle = new Client(['base_uri' => self::APIURL]);
$raw_response = $guzzle->post($endpoint, [
'headers' => [ 'Authorization' => 'Bearer ' . $publicKey ],
'body' => json_encode($data),
]);
$response = $raw_response->getBody()->getContents();