Error consuming API endpoint using GuzzleHttp - php

I am using Guzzle to consume an API but for some reasons, I get this error:
http_build_query(): Parameter 1 expected to be Array or Object. Incorrect value given.
I don't know what I might be doing wrong. This is my code:
$data = ["name" => "joe doe"];
$jsData = json_encode($data);
$headers = [
'content-type' => 'application/json',
'Authorization' => "Bearer {$token}"
];
$call = $this->client->post(env('URL'),[
"headers" => $headers,
'form_params' => $jsData
]);
$response = json_decode($call->getBody()->getContents(), true);
Edit
$data = ["name" => "joe doe"];
$headers = [
'content-type' => 'application/json',
'Authorization' => "Bearer {$token}"
];
$call = $this->client->post(env('URL'),[
"headers" => $headers,
'form_params' => $$data
]);
$response = dd($call->getBody()->getContents(), true);
Client error: POST http://localhost/send resulted in a 400 BAD REQUEST response: { "error": { "code": 400, "message": "Failed to decode JSON object: No JSON object could be decoded", "u (truncated...)

The reason you're seeing the error is that form_params should be an array but you're running the array through json_encode which returns a string:
$data = ["name" => "joe doe"];
$jsData = json_encode($data);
// ...
'form_params' => $jsonData
You should simply pass the data through as an array, without running it through json_encode:
$data = ["name" => "joe doe"];
// ...
$call = $this->client->post(env('URL'), [
"headers" => $headers,
'form_params' => $data
]);

Related

Guzzle: Call to undefined method GuzzleHttp\\\\Psr7\\\\Stream::getStatusCode()

I'm trying out guzzle in mu laravel app in order to use FCM notifications, for some reason I'm getting the following error when I try to get response status code, also am I using guzzle correct syntax? they seem to have updated theirs.
Call to undefined method GuzzleHttp\\\\Psr7\\\\Stream::getStatusCode()
My method:
public function send($user,$title,$body, $data = false , $type, $image='')
{
$client = new Client();
$url = 'https://fcm.googleapis.com/fcm/send';
$serverKey = config('services.firebase.api_key');
$headers =
[
'Content-Type' => 'application/json',
'Authorization' => 'key='.$serverKey,
];
$fields =
[
'registration_ids' => [ $user['fcm_token'] ],
'to' => $user['fcm_token'],
"notification" =>
[
"title" => $title,
"body" => $body,
"sound" => "default",
],
"priority" => 10,
'data' => $data,
"android" => [ "priority" => "high" ]
];
$fields = json_encode ( $fields );
try
{
$response = $client->request('POST',$url,[
'headers' => $headers,
"body" => $fields,
]);
$response = $response->getBody();
$statusCode = $response->getStatusCode();
}
catch (ClientException $e)
{
$response = $e->getResponse();
$response = $response->getBody()->getContents();
$statusCode = $response->getStatusCode();
}
$result =
[
'response' => $response,
'statusCode' => $statusCode
];
return $result;
}
Thanks in advance
You are overwriting the response and then trying to get the status code from the stream. You should instead do
$response = $e->getResponse();
$statusCode = $response->getStatusCode();
$response = $response->getBody()->getContents();
Notice I moved the getStatus method
above the getBody.

How to get response of content type application/x-www-form-urlencoded by passing parameters in laravel

I have used Api on to Single Sign In Opt with in Laravel https://sso/{custom_path}/token like this Api created using jwt.
And on my end in web application passing access token and content type in header to Api call using http client guzzle.
With content type application/x-www-form-urlencoded with parameters in form_params.
But in response i am getting missing grant_type. As i am passing grant_type in form_parms array. Is there any other way to resolve this issue. Any valueable response will be considered.
Code:
$uri = $this->userTokenAuthencticateUrl();
$token = session('token')->access_token;
$params['header'] = [
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Bearer $token"
];
$params['form_params'] = array(
'grant_type' => 'xxxxx',
'response_include_resource_name' => 'xxx',
'audience' => 'xxxx',
'permission' => 'xxxxxx',
);
$response = Http::post($uri, $params);
dd($response->json());
Ressponse:
array:2 [▼
"error" => "invalid_request"
"error_description" => "Missing form parameter: grant_type"
]
As you are using HTTP Client. You need to change your code. You do not need to pass Content-Type as application/x-www-form-urlencoded in your header and I believe the Authorization token is passed separately in headers you can pas it in your params.
$uri = $this->userTokenAuthencticateUrl();
$token = session('token')->access_token;
$params = array(
'grant_type' => 'xxxxx',
'response_include_resource_name' => 'xxx',
'audience' => 'xxxx',
'permission' => 'xxxxxx',
);
$response = Http::asForm()->withHeaders([
'Authorization' => 'Bearer ' . $token
])->post($uri, $params);
dd($response->json());
Method 2:
It is also mentioned in docs
If you would like to quickly add an Authorization bearer token header to the request, you may use the withToken method
so you can do like this as well
$uri = $this->userTokenAuthencticateUrl();
$token = session('token')->access_token;
$params = array(
'grant_type' => 'xxxxx',
'response_include_resource_name' => 'xxx',
'audience' => 'xxxx',
'permission' => 'xxxxxx',
);
$response = Http::asForm()->withToken($token)->post($uri, $params);
dd($response->json());
See the doc for more details
Method 3:
You can even directly use guzzle as well.
define("form_params", \GuzzleHttp\RequestOptions::FORM_PARAMS );
try{
$client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer ' . $token]]);
$guzzleResponse = $client->post(
$api_url, [
'form_params' => [
'grant_type' => 'xxxxx',
'response_include_resource_name' => 'xxx',
'audience' => 'xxxx',
'permission' => '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 400 response errors and 500 response errors
// see this https://stackoverflow.com/questions/25040436/guzzle-handle-400-bad-request/25040600
}catch(Exception $e){
//other errors
}

Using Guzzle to send POST request with JSON

$client = new Client();
$url = 'api-url';
$request = $client->post($url, [
'headers' => ['Content-Type' => 'application/json'],
'json' => ['token' => 'foo']
]);
return $request;
And I get back 502 Bad Gateway and Resource interpreted as Document but transferred with MIME type application/json
I need to make a POST request with some json. How can I do that with Guzzle in Laravel?
Give it a try
$response = $client->post('http://api.example.com', [
'json' => [
'key' => 'value'
]
]);
dd($response->getBody()->getContents());
Take a look..
$client = new Client();
$url = 'api-url';
$headers = array('Content-Type: application/json');
$data = array('json' => array('token' => 'foo'));
$request = new Request("POST", $url, $headers, json_encode($data));
$response = $client->send($request, ['timeout' => 10]);
$data = $response->getBody()->getContents();
you can also try this solution. that is working on my end. I am using Laravel 5.7.
This is an easy solution of Make a POST Request from PHP With Guzzle
function callThirdPartyPostAPI( $url,$postField )
{
$client = new Client();
$response = $client->post($url , [
//'debug' => TRUE,
'form_params' => $postField,
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
]
]);
return $body = $response->getBody();
}
For Use this method
$query['schoolCode'] =$req->schoolCode;
$query['token']=rand(19999,99999);
$query['cid'] =$req->cid;
$query['examId'] =$req->examId;
$query['userId'] =$req->userId;
$tURL = "https://www.XXXXXXXXXX/tabulation/update";
$response = callThirdPartyPostAPI($tURL,$query);
if( json_decode($response,true)['status'] )
{
return success(["data"=>json_decode($response,true)['data']]);
}

Guzzle not sending POST parameters

I am sending this as a test to a test webserver, but the response although its a 201 which means it got it, it does not show the posted data I want to send:
<?php
$url = "https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = array('color' => 'red');
$response = $client->request('POST', $url, [
'form_params' => $post_data,
'verify' => false
]);
$body = $response->getBody();
dsm($body);
?>
Is the format of the request I made incorrect?
I can see that it is not getting the post data because when I do a dsm of the response body, it isn't there.
This worked for me, looks like I needed to add the headers:
$url="https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = $form_state->cleanValues()->getValues();
$response = $client->request('POST', $url, [
'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
'form_params' => $post_data,
'verify'=>false,
]);
$body = $response->getBody()->getContents();
$status = $response->getStatusCode();
dsm($body);
dsm($status);

Guzzle to ryver api

Hello guys i've been pulling my hair for this problem. I'm accessing an api from ryver to send post chat messages for automated notification. I'm following this doc https://support.ryver.com/chatmessage-api/ and I'm using laravel 5.1 with Guzzle and here's my code if it helps
$client = new Client();
$postData = \GuzzleHttp\json_encode(['JSON Payload' => ['body' => 'test123']]);
$options = [
'json' => $postData
];
$request = $client->post('https://somecompany.ryver.com/api/1/odata.svc/workrooms(1099207)/Chat.PostMessage()', $options);
$request->setHeader('Content-Type', 'application/json');
$request->setHeader('Accept', 'application/json');
$request->setHeader('Authorization', 'Basic Base64codehere');
$response = $request->send();
It always returns a [status code] 400, Please help :( Thank you and have a great day!
You may try sending the API request using this params
$postData = \GuzzleHttp\json_encode(['body' => 'test123']);
$options = [
'JSON Payload' => $postData
];
Fixed it :) I just need to stringfy the JSON to make it work and set body the JSON. here's the code.
$client = new Client();
$postData = '{
"body":"**Update!**\n> ** Test success for ryver integration.",
"extras": {
"from": {
"__descriptor":"Developer",
"avatarUrl":"https://cdn2.f-cdn.com/ppic/4973381/logo/4389970/developer_avatar.png"
}
}
}';
$request = $client->post('https://company.ryver.com/api/1/odata.svc/workrooms(1098712)/Chat.PostMessage()',[
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Authorization' => 'Basic base64'
]);
$request->setBody($postData);
$response = $request->send();

Categories