I am trying to post some data using a Guzzle Client Http request in Laravel. But for some reason the server respons with the message that it can't find the property Id in the JSON object, while the property Id is clearly in the request. The Guzzle documentation says that assigning the array to a json property in the request will result in a Json object being sent.
$url = "https://blablabla.com/api";
$key = "1234";
$data = [
'Id' => "4"
];
$response = Http::withHeaders([
"Authorization" => $key
])->post($url, [
'json' => $data
]);
Now I have tested the api in Postman and don't experience any problems. I even use the same api in a different php application using curl and it works perfect. So obviously there is something wrong with lines of code above and not with the api. I have tried different things but nothing works.. I have a feeling that the solution is so simple.. but for the last 6 hours I couldn't figure it out.. So please help before I go crazy :)
Laravel documentation on page HTTP Client says: "By default, data will be sent using the application/json content type". So you don't need to use 'json' property in post data. Just sent it directly: ->post($url, $data).
Related
I'm trying to use Guzzle to make multiple requests, but when I try to get the response I keep getting a cURL 77 error. I'm connecting to Zoom API using JWT. I have an array of 700 items, so for each item, I'm trying to create a request using getAsync passing the jwt token.
My code is like this:
foreach ($agrupado as $registro) {
$requestArr[$registro['id']] = $cliente->getAsync('https://api.zoom.us/v2/webinars/'.$id.'/registrants/'.$registro['id'], [
'headers' => [
'Authorization' => 'Bearer '.$jwt
]]);
}
$respostas = \GuzzleHttp\Promise\unwrap($requestArr);
var_dump($respostas);
If I do the same request, using the get method, and same token, it works. I get the response, with no problem. It's very weird.
I found this tutorial and now I'm able to make multiple requests using Guzzle to Zoom's API.
I think that the problem was that I was making a lot of request, and the API at some point was rejecting the calls. I know that because I tested it with a few request, like 5, or 10. And it was fine. When I did 30 request, I get the certificate error.
So, I implemented the example on this tutorial (Concurrency in Promise) using Guzzle's promises and the EachPromise class. I keep a low number of concurrency and use the method wait at the end of the script. Now everything is working.
I develop at php Laravel.
I receiving GuzzleHttp response from Mailgun as Object and can't to get from it the status.
the Object is:
O:8:"stdClass":2:{s:18:"http_response_body";O:8:"stdClass":2:{s:6:"member";O:8:"stdClass":4:{s:7:"address";s:24:"test_of_json-4#zapara.fr";s:4:"name";s:10:"not filled";s:10:"subscribed";b:1;s:4:"vars";O:8:"stdClass":0:{}}s:7:"message";s:36:"Mailing list member has been created";}s:18:"http_response_code";i:200;}
I need just last data pair:
"http_response_code";i:200;
to get it into variable, like:
$http_response_code = 200;
or even just its value.
To get string as I cited above I use
$result_ser = serialize($result);
but yet can't to extract value of variable.
Also I tried this:
$this->resultString .= \GuzzleHttp\json_decode($result_ser, true);
and get error.
Please, explain me , How to get/extract value I needed?
To take the response status code you can use the function getStatusCode :
$response = $client->request();
$statusCode = $response->getStatusCode();
while to take the body of response you can use :
$contents = $response->getBody()->getContents();
let's consider your request is something like
$response = $client->get("https://example.com");
if ( $object_res->getStatusCode() == 200 ) { // here you are checking your http status code
}
$object_res->getStatusCode() is the method to get http status code.
refer docs, there is simple example in this page.
I found that 'mailgun/mailgun' package uses its own HTTP client which also uses 'RestClient' and these classes are return stdObject.
In that Object there is property 'http_response_code' containing HTTP response code like 200, 400, 401 etc.
This property accessible by standard way $object->property and it's a solution of my query in this case.
For anybody who will read this question and answers I should to explain one thing that I not cleared in question.
I made request to the Mailgun API for subscribing member to mailing list. The API returns stdObject, not JSON or XML data.
But also there is one more strange thing - stdObject returned when request is successful only. If request fails you'll get just Exception thrown with message and without code. This forced me, if fail, to parse message body instead of get and resolve error code.
$responseObj->getStatusCode();
This should be soo simple but I have spent hours searching for the answer and am truly stuck. I am building a basic Laravel application and am using Guzzle to replace the CURL request I am making at the moment.
actually I want to send data as JSON in request Body , in PUT method ,using Guzzel PHP client. please anyone help me how can i send.
please share complete code , i am new to using it.
According to the doc of guzzle
$response = $client->request('PUT', '/put', ['json' => ['foo' => 'bar']]);
What version of guzzle do you have and what did you try ?
I use Unirest for PHP to do some HTTP Requests. Everything works fine, until I want to pass a fairly complex JSON to my Node.js router.
First I do a GET request that returns a JSON Object, then I extend this JSON object (needs to be done, I know it sucks) and want to feed it back into my other http POST request... and here is where the trouble starts:
I echoed the JSON that is returned and copied the output into postman -> works fine. If I want use the JSON directly in PHP in next request:
$teamsMemberOf is the variable which is containing the GET response.
$headers = array("Accept" => "application/json");
$newBody = '{"team":'.$teamsMemberOf->raw_body.'}';
$relevantBoxesAmount = Unirest\Request::post("http://localhost:3001/my/route/".$result['_id']."/get-something-from-server", $headers, $newBody);
and it doesn't work.
Error is 500 and 'Cannot read property '0' of undefined' which is certainly related to something in the JSON object.
Does someone have an idea how to fix it?
I am working with a third party service that requires me to authenticate through OAuth1 to make requests. I can successfully authenticate and get data back with most of their calls using GET, however some calls they require POST and this is where the problem lies. To authenticate I am using the below:
$oauth = new OAuth(MY_KEY,MY_SECRET);
$oauth->setNonce(rand());
$oauth->setToken('','');
Then for a GET call I am doing something like below:
$array = array(
'partnerId'=>'1234'
);
$call = $oauth->fetch("https://domain.co.uk/api/getInfo/",$array);
$data = $oauth->getLastResponse();
This all works perfectly, and I can print out the $data
However with POST calls:
$oauth = new OAuth(MY_KEY,MY_SECRET);
$oauth->setNonce(rand());
$oauth->setToken('','');
$oauth->enableDebug();
$oauth->setAuthType(OAUTH_AUTH_TYPE_AUTHORIZATION);
$array = array(
'rid' => "$restaurantId",
'datetime' => "$datetime",
'partysize' => $covers,
'timesecurityID' => "$securityId",
'resultskey' => "$resultskey"
);
$call = $oauth->fetch("https://domain.co.uk/api/booking/?pid=1234&st=0",$array,OAUTH_HTTP_METHOD_POST);
$data = $oauth->getLastResponse();
I keep getting the error: Invalid Consumer Signature
Speaking to their tech guy he suggested
Your sbs value indicates that you’re signing with all of the POST
parameters, whereas you only need to sign with the query string. In
this case it would be “pid=1234&st=0”. Unfortunately, I’m not
familiar with the PHP libs and don’t have any recommendations on how
to alter the behavior.
and also mentioned common previous problems with a PHP implementation are:
The PHP HTTP lib will drop the query string once the method is
changed from GET to POST.
The PHP oAuth lib will use the post data
to sign the request rather than the query string or maybe both.
If I dump out the headers I get:
[sbs] => POST&https%3A%2F%2Fdomain.co.uk%2Fapi%2Fbooking%2F&datetime%3D2013-02-21T10%253A30%253A00%26oauth_consumer_key%3DMySiteV3TT%26oauth_nonce%3D1213111151%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1360835965%26oauth_token%3D%26oauth_version%3D1.0%26partysize%3D2%26pid%3D1531%26resultskey%3DfoqgEnYK%25252bIzRd6BV3T8eGQ%25253d%25253d%26rid%3D31852%26st%3D0%26timesecurityID%3D349367809
[headers_sent] => POST /api/booking/?pid=1234&st=0 HTTP/1.1
It looks like it is sending the OAuth data with the rest of the post, I just want this sent in the Authorization header (which it is also sending)
Authorization: OAuth oauth_consumer_key="MySite",oauth_signature_method="HMAC-SHA1",oauth_nonce="1772854358",oauth_timestamp="1360768712",oauth_version="1.0",oauth_token="",oauth_signature="2%2B7xb%2BJ5cdbUDC5UHfsdfsNpFM1pE%3D"
So I think I need to strip the OAuth data from the post request but keep it as a Authorization Header but just can't find the magic way to do that!
I've seen this. In fetch(), try urlencoding your $array and passing it in as a string of the form:
rid=[restaurantId]&datetime=[datetime]&...
Also give the header (final parameter of fetch()):
Content-Type: application/x-www-form-urlencoded