This is the error I'm getting, as you can see there is a parameter in the URL, but the error says there weren't any parameters given. Can anbody help me out?
Client error: PUT https://webapi.teamviewer.com/api/v1/devices/d38237721?alias=laptop-test resulted in a 400 Bad Request response:
{"error":"invalid_request","error_description":"no parameters were given.","error_code":1}
This is my code
public function update($device_id, $options)
{
$token = 'thereisatokenhere';
$client = new Client(['base_uri' => 'https://webapi.teamviewer.com/api/v1/']);
$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept-Language' => 'en-US',
'Content-Type' => 'application/json'
];
$response = $client->request('PUT', 'devices/' . $options['device_id'], [
'headers' => $headers,
'form_params' => [
'alias' => $options['alias'],
],
]);
$response = json_decode($response->getBody()->getContents(), true);
$deviceIdsAPI = $response['devices'];
return $deviceIdsAPI;
}
2nd
$request = new Request('PUT', 'https://webapi.teamviewer.com/api/v1/devices/' . $options['device_id'], ['alias' => $options['alias']]);
$response = $client->send($request, ['timeout' => 2, 'headers' => $headers]);
Here is an example of a PUT request in Guzzle:
$client->put('devices/' . $options['device_id'], [
'body' => [
'alias' => $options['alias'],
'other_field' => '123'
],
'headers' => $headers,
'allow_redirects' => false,
'timeout' => 5
]);
Update:
In the latest version (Guzzle 6) it should be like this:
use GuzzleHttp\Psr7\Request;
$request = new Request('PUT', 'http://httpbin.org/put', ['test' => '123']);
$response = $client->send($request, ['timeout' => 2, 'headers' => $headers]);
See this answer and here is the official Guzzle documentation
Related
I'm trying to send this request to the server, but with a 401 error
Which part of the code can the problem be?
"guzzle version 6.3"
try {
$urlDoPayment = 'https://api.example.com/v1/pay';
$client = new Client();
try {
$response = $client->request('POST', $urlDoPayment, [
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'amount' => 100,
'returnUrl' => "https://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]
]);
$statusCode = $response->getStatusCode();
$content = $response->getBody();
dd($content);
} catch (GuzzleException $e) {
dd($e->getMessage());
}
} catch (\Exception $exception) {
dd($exception->getCode());
}
The headers in the request are nested in the wrong part of the request options. That should at least fix the 401 error if the token is valid.
Try:
$response = $client->request('POST', $urlDoPayment, [
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'amount' => 100,
'returnUrl' => "https://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
// headers should not be here
], // json post body params end
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]);
This problem solved using this code
$response = $client->request('POST', $urlDoPayment, [
'json' => [
'amount' => 100,
'returnUrl' => "http://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]);
I suspect that the problem lays in undefined port or protocol. Headers content wasn't an issue for me. I resolved same problem by changing:
115.12.3.44 to 115.12.3.44:80
also tested
115.12.3.44 to http://115.12.3.44
or
google.com to http://google.com
I have a problem with my Bearer-Authorization in Guzzle-HTTP.
I use it to test my PHP-REST-API with PHPUnit.
here is my test method:
public function testGetMe()
{
$client = new Client([
'base_uri' => $this->apiBaseURL
]);
$data = ['email' => $email, 'password' => '12345'];
$client->post('register', [
'form_params' => $data]
);
$responseJson = json_decode($response->getBody());
$myToken = $responseJson->data->token;
$response = $client->request('GET', 'users', [
'headers' => [
'Authorization' => 'Bearer '.$myToken
],
'debug' => true
]);
}
But if I set the token hard coded like this:
public function testGetMe()
{
$client = new Client([
'base_uri' => $this->apiBaseURL
]);
$data = ['email' => $email, 'password' => '12345'];
$client->post('register', [
'form_params' => $data]
);
$responseJson = json_decode($response->getBody());
$myToken = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE0NjQ5NzExMzQsImp0aSI6IjByR3FpOW15Rm1rRGo2TU9sMVhkK3dRU3p1V0pWejM1UEhiU2dTMmg5SEU9IiwiaXNzIjoiQXBwTmFtZSIsIm5iZiI6MTQ2NDk3MTE0NCwiZXhwIjoxNDY0OTczMTQ0LCJzdWIiOiJ0ZXN0QG1haWwuZGUifQ.yA4a_S6ILCeqENm00H712g9uF5g9eSz_BmnaMDdZ2r4p5e1q88g0T09IG2WKCi1oExoBfQ8VTmKeX6ZQv0RydQ;
$response = $client->request('GET', 'users', [
'headers' => [
'Authorization' => 'Bearer '.$myToken
],
'debug' => true
]);
}
and also with Postman, it is working.
It's the same token which I receive from my REST-API.
Do you have any ideas what's wrong?
My working Guzzle5 code looks roughly as follows:
$guzzle = new \GuzzleHttp\Client();
$request = $guzzle->createRequest('POST', $url);
$request->setHeader('Authorization', 'Bearer ' . $token);
$postBody = $request->getBody();
$postBody->setField('name', 'content');//several times
if (check for file) {
$postBody->addFile(new \GuzzleHttp\Post\PostFile('name', fopen(...));
}
$response = $guzzle->send($request);
What with setting a header and maybe adding a file, I’m not sure how to do this with Guzzle6.
Here an example from the official documentation how can you set headers and adding file into your POST request with Guzzle 6:
$client = new \GuzzleHttp\Client();
$client->post('/post', [
'multipart' => [
[
'name' => 'foo',
'contents' => 'data',
'headers' => ['X-Baz' => 'bar']
],
[
'name' => 'baz',
'contents' => fopen('/path/to/file', 'r')
],
[
'name' => 'qux',
'contents' => fopen('/path/to/file', 'r'),
'filename' => 'custom_filename.txt'
],
]
]);
The multipart option sets the body of the request to a multipart/form-data form, if you don't need to work with files you can just use form_params instead of multipart option.
Any headers you can easy set with help headers option.
Additional info you can find here Guzzle Upgrade Guide (5.0 to 6.0)
Here is some code copied from one of my projects:
$client = new GuzzleHttp\Client();
$url = 'someurl.com/api';
$body = json_encode([
'variable1' => 'this',
'variable2' => 'that'
]);
$response = $client->post($url, [
'headers' => [
'header_variable1' => 'foo',
'header_variable2' => 'bar'
],
'json' => true,
'timeout' => 3,
'body' => $body
]);
$data = $response->json();
I'm trying to request this way:
$body = [];
$body['holder_name'] = $full_name;
$body['bank_code'] = $bank_number;
$body['routing_number'] = $branch_number;
$body['account_number'] = $account_number;
$body['type'] = 'checking';
$client = new GuzzleHttp\Client([
'base_url' => [$url, []],
'headers' => ['content-type' => 'application/json', 'Accept' => 'application/json'],
'defaults' => [
'auth' => [$publishable_key, ''],
],
'body' => json_encode($body),
]);
The problem is that this request is being set without Content-Type.
What am I doing wrong?
Ok .. the problem was that I was setting body and headers outside of defautls. the solution is:
$client = new GuzzleHttp\Client([
'base_url' => [$url, []],
'defaults' => [
'auth' => [$publishable_key, ''],
'headers' => ['content-type' => 'application/json', 'Accept' => 'application/json'],
'body' => json_encode($body),
],
]);
Guzzle 6
Guzzle will set the Content-Type header to
application/x-www-form-urlencoded when no Content-Type header is
already present.
You have 2 options.
Option 1: On the Client directly
$client = new GuzzleHttp\Client(
['headers' => [
'Content-Type' => 'application/json'
]
]
);
Option 2: On a Per Request basis
// Set various headers on a request
$client = new GuzzleHttp\Client();
$client->request('GET', '/whatever', [
'headers' => [
'Content-Type' => 'application/json'
]
]);
You can refer to Guzzle 6: Request Options
I was encountering the same issue with the Hubspot API that requires to set application/json as Content-Type for POST requests.
I fixed it this way
$client = new Client([
'base_uri' => 'https://api.hubapi.com/',
'timeout' => 5,
'headers' => ['Content-Type' => 'application/json']
]);
And then performing my requests the regular way
try
{
$response = $client->request('POST', '/contacts/v1/contact/email/test#test.com/profile',
['query' => MY_HUBSPOT_API_KEY, 'body' => $body]);
}
catch (RequestException $e) { print_r($e); }
I hope this helps.
I have this code for sending parameters for a POST request, which works:
$client = new GuzzleHttp\Client();
$request = $client->createRequest('POST', 'http://example.com/test.php');
$body = $request->getBody();
$request->getBody()->replaceFields([
'name' => 'Bob'
]);
However, when I change POST to PUT, I get this error:
Call to a member function replaceFields() on a non-object
This is because getBody is returning null.
Is it actually correct to send PUT parameters in the body? Or should I do it in the URL?
According to the manual,
The body option is used to control the body of an entity enclosing
request (e.g., PUT, POST, PATCH).
The documented method of put'ing is:
$client = new GuzzleHttp\Client();
$client->put('http://httpbin.org', [
'headers' => ['X-Foo' => 'Bar'],
'body' => [
'field' => 'abc',
'other_field' => '123'
],
'allow_redirects' => false,
'timeout' => 5
]);
Edit
Based on your comment:
You are missing the third parameter of the createRequest function - an array of key/value pairs making up the post or put data:
$request = $client->createRequest('PUT', '/put', ['body' => ['foo' => 'bar']]);
when service ise waiting json raw data
$request = $client->createRequest('PUT', '/yourpath', ['json' => ['key' => 'value']]);
or
$request = $client->createRequest('PUT', '/yourpath', ['body' => ['value']]);
If you're using Guzzle version 6 you can make PUT request this way:
$client = new \GuzzleHttp\Client();
$response = $client->put('http://example.com/book/1', [
'query' => [
'price' => '50',
]
]);
print_r($response->getBody()->getContents());
In Guzzle 6, if you want to pass JSON data to your PUT request then you can achieve it as below:
$aObj = ['name' => 'sdfsd', 'language' => 'En'];
$headers = [
"User-Agent" => AGENT,
"Expect" => "100-continue",
"api-origin" => "LTc",
"Connection" => "Keep-Alive",
"accept" => "application/json",
"Host" => "xyz.com",
"Accept-Encoding"=> " gzip, deflate",
"Cache-Control"=> "no-cache",
"verify" => false,
"Content-Type" => "application/json"
];
$client = new GuzzleHttp\Client([
'auth' => ['testUsername', 'testPassword'],
'timeout' => '10000',
'base_uri' => YOUR_API_URL,
'headers' => $headers
]);
$oResponse = $client->request('PUT', '/user/UpdateUser?format=json', ['body' => json_encode( $aObj, JSON_UNESCAPED_SLASHES)]);
$oUser = json_decode( $oResponse->getBody());