convert CURL get request to guzzlehttp client Laravel - laravel

This is the curl that I want to execute:
curl -X GET \
-H "X-ABC-Application-Id: 12345asdfg" \
-H "X-ABC-REST-API-Key: 12345asdfg" \
-G \
--data-urlencode "where={ \"SKU\":\"A string\",\"QTY\":1 }" \
example.com/product/inventory
This is what I have tried:
$endpoint = "example.com";
$client = new Client();
$body = ['where' => ['SKU' => 'A string']];
$headers = [
'X-ABC-Application-Id' => '12345asdfg',
'X-ABC-REST-API-Key' => '12345asdfg'
];
$response = $client->get($endpoint, [
'query' => $body,
'headers' => $headers,
]);
$statusCode = $response->getStatusCode();
$content = $response->getBody();
dd($statusCode,$content,$response);
After executing it I got an error (exception) as follows:
400 Bad Request response:
{"code":102,"error":"Invalid parameter for query: 0"}

The misconception is that get() doesn't take headers. You have to pass them by calling withHeaders() before you fire the request and only pass $body directly as the second parameter to get() without wrapping it into an array.
$endpoint = "example.com";
$client = new Client();
$body = ['where' => ['SKU' => 'A string']];
$headers = [
'X-ABC-Application-Id' => '12345asdfg',
'X-ABC-REST-API-Key' => '12345asdfg'
];
$response = $client->withHeaders($headers)->get($endpoint, $body);
$statusCode = $response->getStatusCode();
$content = $response->getBody();
dd($statusCode,$content,$response);

Related

How to post request with query params in laravel 9

I am trying to send post request with query params. just like this screenshot
I used Http::post but it supports only json as far as I know. I just want to send request just like the screenshot. cause API data only supports parameter wise. Here What I tried but failed to achieve that.
FormController.php:
public function post_parameter_wise(Request $request,$lp_campaign_id, $lp_campaign_key, $first_name, $last_name, $email, $phone, $zip_code){
$form = new Form();
$fName = $form->first_name = $request->get($first_name);
$lName = $form->last_name = $request->get($last_name);
$cCmail = $form->email = $request->get($email);
$cPhone = $form->phone = $request->get($phone);
$zCode = $form->zip_code = $request->get($zip_code);
$response = Http::post("https://t.vivint.com/post.do", [
"lp_campaign_id" => $lp_campaign_id,
"lp_campaign_key" => $lp_campaign_key,
// "lp_supplier_id" => "",
"first_name" => $fName,
"last_name" => $lName,
"email" => $cCmail,
"phone" => $cPhone,
"zip_code" => $zCode
]);
dd($response);
Can't leave a comment so disregard this as the answer
Preferably, you just need to change it from a Post request to a Get request and it will work
$response = Http::get("https://t.vivint.com/post.do", [...
But a post request will contain the data as a post request should.
If you have to use post and define the query params then you should do it as follows
public function post_parameter_wise(Request $request,$lp_campaign_id, $lp_campaign_key, $first_name, $last_name, $email, $phone, $zip_code){
$form = new Form();
$fName = $form->first_name = $request->get($first_name);
$lName = $form->last_name = $request->get($last_name);
$cCmail = $form->email = $request->get($email);
$cPhone = $form->phone = $request->get($phone);
$zCode = $form->zip_code = $request->get($zip_code);
$response = Http::post("https://t.vivint.com/post.do?lp_campaign_id=".$lp_campaign_id."&lp_campaign_key=".$lp_campaign_key."&first_name=".$fName."&last_name=".$lName."&email=".$cCmail."&phone=".$cPhone."&zip_code=".$zCode, []);
dd($response);
Although this is really just forcing it to

How to make post request to get data Laravel Guzzle?

Let say, the Secret Key is XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX and md5key is YYYYYYYY.
I made a Query String QS
Qs = “method=RegUserInfo&Key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&Time=20140101123456&Username=DemoUser001”;
After urlencode I got q='j4tjorjwarfj3trwise0safrwg2wt4awari0fwjfeoh'
I made MD5 String for building the signature (QS + md5key + Time + Key):
s = BuildMD5(QS + “YYYYYYYY” + “20140101123456” + “XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX”);
I got s='1234567890abcdef'
So will get q=j4tjorjwarfj3trwise0safrwg2wt4awari0fwjfeoh&s=1234567890abcdef
How to resulting POST method query (using “Content-Type: application/x-www-form-urlencoded”)
by POST to http://xxxxx.com/api/api.aspx
My code is
$param = "q=".$q."&s=".$s;
$client = new Client(['headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
]]);
try{
$response = $client->request('POST','http://xxxxxx.com/api/api.aspx', [
'query' => [$param],
]);
}catch(ClientException $e){
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
dd($responseBodyAsString);
}
}
but I get 403 Forbidden
If you want Content-Type: application/x-www-form-urlencoded you need to use form_params request option.
try{
$client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer ' . $your_token]]);
$guzzleResponse = $client->post(
$api_url, [
'form_params' => [
'grant_type' => 'xxxxx',
'key' => 'xxx',
'time' => 'xxxx',
'username' => 'xxxxxx'
]
]);
if ($guzzleResponse->getStatusCode() == 200) {
$response = json_decode($guzzleResponse->getBody(),true);
//perform your action with $response
}
}
catch(\GuzzleHttp\Exception\RequestException $e){
// you can catch here 40X response errors and 500 response errors
}catch(Exception $e){
//other errors
}
know more about form_params

Laravel patch external API

I'm getting data from an external API source.
Im using this to retrieve my orders
$data = Http::get(
$this->URL .'orders?language=nl_NL&limit=100&format=json&status_changed_start_date='
. $last_poll
. '&ordering=asc&partner_token='.$this->PARTNERKEY.'&token='.$this->MERCHANTTOKEN.''
)->json();
following the guide on the partner site I should use this format to update a specific record.
curl -X PATCH $this->URL ."orders/2?language=nl_NL&format=json&override_minimum=false&override_stock=false&mutate_stock=true&partner_token='.$this->PARTNERKEY.'&token='.$this->MERCHANTTOKEN.'" \
-H "accept: application/json" \
-H "Content-Type: application/json" \
-d "{\"status\":2,\"archived\":true,\"comments\":{\"internal\":\"Owner's commentary\"}}"
How would I implement this within a Laravel controller ?
Use the HTTP Client provide by Laravel:
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
class MyController
{
public function update (Request $request)
{
// Maybe use from $request?
$id = 2;
Http::patch($this->url . "/orders/" . $id, [
'version' => 1,
'order_number' => 2,
'language' => 'nl_NL',
'format' => 'json',
'override_minimum' => false,
// .. put here the other parameters
]);
}
}
Hi Here is my final code.
this seems to be working as I needed
$client = new Client([
// Base URI is used with relative requests
'base_uri' => $this->URL,
]);
$response = $client->request('PATCH', 'orders/' . $item['number'] .'?language=nl_NL&format=json&override_minimum=false&override_stock=false&mutate_stock=true&partner_token='.$this->PARTNERKEY.'&token='.$this->MERCHANTTOKEN, [
'json' => [
'status' => 2,
'archived' => true,
'comments' => ['internal' => $comment]],
]);

Error: Pass content as json or plain text

I am using guzzle to post data to the api as below. When i post, the api returns Error: Pass content as json or plain text. Is it possible to convert content to JSON or Plain Text in the code below
How can I resolve this?
Controller
$headers = [
'Content-Type' => 'application/x-www-form-urlencoded',
];
$client = new \GuzzleHttp\Client([
'headers' => $headers
]);
$body = '{
"item" : Summer-Jacket,
"content" : Hi
}';
$url = "https://api.com";
$request = $client->post($url,
[
'body' => $body
] );
$response = $request->send();
Firstly your body is not even valid JSON. Strings needs to have "string" around them
To post JSON with guzzle, you can instead use the RequestOptions for exactly that.
$result = $client->post("https://api.com", [
RequestOptions::JSON => [
'item' => 'Summer-Jacket',
'content' => 'hi',
]
)->getBody();

Guzzle POST request: required body when execute request

I have a POST request with Guzzle like this:
// Return a collection
$cart = $this->getCart('2019-10-08 07:08:39');
//Return first entry of the collection with first()
$template = $this->getTemplate($config->key);
$isDetail = null;
foreach ($cart as $item) {
try {
$client = $this->getClient();
$headers = ['Content-Type' => 'application/json'];
$body = [
'user_id' => $item->mystore_user_id,
'title' => $template->title,
'message' => $template->message,
'avatar' => $template->avatar,
'detail_id' => $isDetail,
'schedule' => null
];
print_r($body);
$response = $client->post('push-noti/unicast', $headers, $body);
print_r(response()->json(json_decode($response->getBody(), true)));
} catch (QueryException | \Exception $ex) {
echo "Error!";
}
}
My body variable value is exist in each loop when it printed. But when I use it in $client->post, my request return error with user_id, title, message is required. I really don't know why is it?
Can you tell me what's wrong in my code?
Thank you!
Try
$response = $client->post('push-noti/unicast', ['body' => $body , 'headers' => $headers]);
If you are calling a third party API, replace push-noti/unicast with complete URL.

Resources