Convert cURL request to Guzzle in Laravel - php

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.

Related

PHP GuzzleHttp . How to send a json post?

I have this post:
{"latitude":"","longitude":"","countryCode":"ES","filterPostalCode":"","filterCity":"","filterCountryCode":"ES","searchText":"","nextPageToken":0,"storeType":"normal","checkStoreAvailability":false}
And i'm trying to send it like this on Guzzle 6.0+
'headers' => [
'Content-Type' => 'application/json',
'Referer' => 'https://www.rituals.com/es-es/stores'],
'body' => '{"latitude":"","longitude":"","countryCode":"ES","filterPostalCode":"","filterCity":"","filterCountryCode":"ES","searchText":"","nextPageToken":0,"storeType":"normal","checkStoreAvailability":false}']
But it's not working, any way to send everything without formating it like I posted? thanks!
First of create Client object
$client = new Client([
'http_errors' => false,
'verify' => false,
]);
And then your request with params
$response = $client->request($requestMethod, $url, array_merge(
['json' => $body],
['headers' => $headers]
));

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 ?

Converting a curl into guzzle code in 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).

Can't set Guzzle Content Type

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.

Categories