I'm using such structure of request
$client = new Client(['base_uri' => 'http://api.brain.com.ua/']);
$request = new Request('POST', 'auth', [
'headers' => [
'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding' => 'gzip, deflate, br',
'Accept-Language' => 'ru,en-US;q=0.7,en;q=0.3',
'Upgrade-Insecure-Requests' => '1',
],
'form_params' => ['login' => $this->login, 'password' =>md5($this->password)]]);
$response = $client->send($request, ['timeout' => 2]);
server returnns 200
but method $response->getBody() returns an empty result
while the cURL returns normal answer {"status":1,"result":"gpkavk4s0aciujg6m698gev040"}
how can i get the same result using GuzzleHttp ?
Related
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
I have a curl request like the following in Codeigniter :
$order = [
'index' => 'Value',
'index2' => 'Value2'
];
$this->curl->create($this->base_url.'order/');
$this->curl->http_login($creds['username'], $creds['password']);
$this->curl->ssl(TRUE, 2, 'certificates/certificate.pem');
$this->curl->option(CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json'));
$this->curl->option(CURLOPT_FAILONERROR, FALSE);
$this->curl->post(json_encode($order));
$data = $this->curl->execute();
Now I need to issue same request in Laravel, where I am using Guzzle. How can I convert this to a Guzzle request ?
Very, very easy:
$client = new GuzzleHttp\Client(['base_uri' => $this->base_url]);
$response = $client->request('POST', 'order/', [
'form_params' => $order,
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json'
],
'auth' => [$creds['username'], $creds['password']],
'http_errors' => false,
'verify' => 'certificates/certificate.pem'
]);
echo $response->getBody();
Note that this has nothing to do with Laravel, it's just Guzzle. Laravel doesn't affect Guzzle API in any way.
It appear Accept: application/json has not been set for the request header. I am not getting json response.
$params = [
'client_id' => 'xxxx',
'client_secret' => 'xxxxxxxxxx',
'code' => $request->get('code'),
'state' => $request->get('state'),
];
$client = new Client(['headers' => ['Accept: application/json']]);
$response = $client->post($tokenUrl, [
'form_params' => $params,
]);
echo $response->getBody();
How do I solve this?
You should write the headers as an associative array, according to http://docs.guzzlephp.org/en/latest/request-options.html.
So, try
$client = new Client(['headers' => ['Accept' => 'application/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());