Converting a curl into guzzle code in php - php

I have a curl code like this which I am trying to convert into guzzle like so
$response = $client->post(self::$url, [
'query' => array(
'app_id' => "app-id",
'included_segments' => array('All'),
'contents' => $content,
'headings' => $headings) ],
['headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Basic api key'
]
]);
But when I try to run this I get this error
...` resulted in a `400 Bad Request` response:\n{\"errors\":[\"Please include a case-sensitive header of Authorization: Basic <YOUR-REST-API-KEY-HERE> with a valid REST AP (truncated...)
CURL
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8','Authorization: Basic api key'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

Which version of Guzzle is this? Because the latest is different.
$client = new GuzzleHttp\Client();
$req = $client->request('POST', self::$url, [
'json' => ['app_id' => '...', 'foo' => 'bar'],
'headers' => ['Authorization' => 'Basic api key']
]);
$res = $client->getBody()->getContents();
I'm pretty sure that 'json' adds automatically the specific header, otherwise transform 'json' in 'form_params' and add the header (content-type).

Related

Upload Image with Guzzle 7

I'm trying to upload an image using guzzlehttp/guzzle v7.2. The curl command works correctly as:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://31.207.77.245/services/update?id=' . $s2jsonResponse->hits[0]->id,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('Filedata'=> new CURLFILE($hit->metadata->path)),
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer ' . $authToken
),
));
$response = curl_exec($curl);
curl_close($curl);
while when using guzzle:
$client = new GuzzleHttp\Client();
$headers = [];
$headers['Authorization'] = 'Bearer ' . $authToken;
$request = $client->request('POST', 'http://31.207.77.245/services/update?id=' . $s2jsonResponse->hits[0]->id,
['multipart' =>[
[
'name' => 'Filedata',
'contents' => fopen($hit->metadata->filename, 'rb'),
'headers' => $headers
]
]]);
$urequest->getBody();
it fails with the error message:
Fatal error: Uncaught GuzzleHttp\Exception\RequestException: cURL error 55: Send failure: Broken pipe (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for http://31.207.77.245/services/update?id=B9l8TjX1a0A93YMSF6IDoH in /Users/augusto/Documents/assets/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php:211
It worked as:
$client = new GuzzleHttp\Client();
$headers = [];
$headers['Authorization'] = 'Bearer ' . $authToken;
$request = $client->request('POST', 'http://31.207.77.245/services/update?id=' . $s2jsonResponse->hits[0]->id, [
'headers' => $headers,
'multipart' => [
[
'name' => 'Filedata',
'contents' => fopen($hit->metadata->filename, 'rb')
]
]]);
$urequest->getBody();

API error no parameters when there are parameters given

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

guzzle POST returns an empty body

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 ?

Convert cURL request to Guzzle in Laravel

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.

How to use linkedin and guzzle?

How do I make calls to the linkedin api using guzzle? So far I've tried
$client = new \GuzzleHttp\Client(['base_uri' => 'https://api.linkedin.com']);
$access_token = 'the_access_token';
$req = $client->request('POST', '/v1/people/~?format=json', [
'headers' => ["Authorization" => "Bearer " . $access_token,
"Content-Type" => "application/json", "x-li-format"=>"json"],
'client_id' => 'the_client_id',
'client_secret' => 'the_client_secret',
'connection' => 'Keep-Alive'
]);
dd($req);
but I just get an error that reads:
Client error: POST https://api.linkedin.com/v1/people/~?format=json resulted in a 405
Im working with laravel 5.1 and guzzle 6.2.
Silly mistake simply had to change $client->request('POST', from POST to GET so it would be:
$client = new \GuzzleHttp\Client(['base_uri' => 'https://api.linkedin.com']);
$access_token = 'the_access_token';
$req = $client->request('GET', '/v1/people/~?format=json', [
'headers' => ["Authorization" => "Bearer " . $access_token,
"Content-Type" => "application/json", "x-li-format"=>"json"],
'client_id' => 'the_client_id',
'client_secret' => 'the_client_secret',
'connection' => 'Keep-Alive'
]);
dd($req);
I also decoded the response which makes it readable by using json_decode($request->getBody()).
Hope it helps if someone else gets stuck on the same problem.

Categories