I'm trying to post a JSON variable and a string variable via HTTP Guzzle. It gives Internal Server Error stating unexpected ' (which is apparently ').
Here is what I have tried so far-
HTTP Guzzle Code
$data = $_GET['data'];
$email = $_GET['email'];
$client = new Client();
$response = $client->request('POST', 'http://someurlhere.com', [
'data' => $data, // this is json variable
'email' => $email // this is string variable
]);
if($response = $request->send()){
// redirect somewhere
}
I have also tried wrapping the JSON variable in 'json' => ['data' => $data], but nothing desirable happened and the error remained the same.
Also, the variables are not getting set via a form. So I have not wrapped them inside form_params.
I found what I was doing wrong there. The code is perfect. The only reason that was causing that problem was the errors I had on my other server, where I am doing the POST request.
This answer is just for my future reference and to help many others out there that might be facing the same problem or may face in the coming future.
I think you can use:
//Guzzle version ~6.3
$response = (new Client())->request("post", $uri, [
'json' => $formParams
]);
Check you $uri response directly with post man and resolve problem if it needed.
Related
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).
I'm sure this is going to be marked as a duplicate, but I've looked through all the given questions on the same subject and tried many of the suggested solutions, and they haven't worked.
I'm in a laravel project and I have a post request going out through guzzle.
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', $url, [
'headers' => [
'Authorization' => 'Bearer ' . $apiToken,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'allow_redirects' => false,
// 'allow_redirects'=>['strict'=>true]
],
'json' => json_decode($logText, true)
]);
I keep on getting the response back "message": "The GET method is not supported for this route. Supported methods: POST."
I've checked and indeed, it's sending a GET request to the same $url specified above.
I didn't have those allow_redirects settings at first, but both settings were offered up as potential solutions when I googled around. Unfortunately, both options result in the same error message: The GET method is not supported for this route.
Why in the world is my POST request changing to a GET request?
I've also tried $client->post instead, and THAT became a GET request as well.
I've also double checked that the GET error message isn't actually coming from inside the POST request: it's not. The POST route isn't being hit at all.
PHP version 7.2, Laravel version 6.0.2, Guzzle version 6.5.3
Check for redirects on the server, such as HTTP -> HTTPS. Redirects are always a GET request, which will mess up non-GET routing. Using the correct protocol all the way through (such as always use HTTPS) will bypass the redirect.
So I'm integrating an API from a 3rd party company and I'm facing this strange situation.
I fetch the endpoint with the following code
$client = $this->client = new Client([
'base_uri' => 'https://xxx.xxxxxxxxxx.com/api/',
'timeout' => 15
]);
$this->requestConfig = [
'auth' => [
'xxxx#xx.xxx',
'xxxxx'
],
'headers' => [
'cache-control' => 'no-cache',
'content-type' => 'application/x-www-form-urlencoded'
],
];
$response = $this->client->get($url, $this->requestConfig);
$content = $response->getBody()->getContents();
Now the fun comes, if I var_dump content I get:
string(66) ""[{\"ExternalId\":\"38\",\"AgencyReference\":\"45436070356676\"}]""
Now I know this response is bad, response type if not set a json, json is URL encoded and everything smells bad.
I've been trying to parse this string for a while.
urldecode doesn't work either.
Question is simple, given a response like that, how can I get a normal array?
Currently using PHP 7.1
So finally found this:
Remove backslash \ from string using preg replace of php
To solve my issue.
In this case it was that the escaped quotes where malforming the json. My final code looks like this.
$response = $response->getBody()->getContents();
$clean = stripslashes($response);
$clean = substr($clean, 1, -1);
dd(json_decode($clean));
Please never write your API's like this...
Just looks awfull
BTW, Content-Type makes sense when you send (in request or response) some content. But you send a GET request, that has no content.
And to specify preferred content type for the response, you should use Accept HTTP header, Accept: application/json for example.
I'm not sure this will solve your problem, but just make things clear and correct ;)
I have to do a DELETE request, with parameters, in the CodeIgnitor platform. First, I tried using cURL, but I switched to Guzzle.
An example of the request in the console is:
curl -X DELETE -d '{"username":"test"}' http://example.net/resource/id
But in the documentation of Guzzle they use parameters just like GET, like DELETE http://example.net/resource/id?username=test, and I don't want to do that.
I tried with:
$client = new GuzzleHttp\Client();
$client->request('DELETE', $url, $data);
but the request just calls DELETE http://example.com/resource/id without any parameters.
If I interpret your curl request properly, you are attempting to send json data as the body of your delete request.
// turn on debugging mode. This will force guzzle to dump the request and response.
$client = new GuzzleHttp\Client(['debug' => true,]);
// this option will also set the 'Content-Type' header.
$response = $client->delete($uri, [
'json' => $data,
]);
coming late on this question after having same.
Prefered solution, avoiding debug mode is to pass params in 'query' as :
$response = $client->request('DELETE', $uri, ['query' => $datas]);
$datas is an array
Guzzle V6
$response = json_decode($this->client->delete($uri,$params)->getStatusCode());
echo $response;
This will also give the status of the response as 204 or 404
I'm trying to consume the Stack Exchange API with Guzzle. I am facing an issue where I can't get the JSON response back: it apparently fails when parsing it.
Here is my code:
$client = new GuzzleHttp\Client();
$parameters = ['pagesize'=>'2','order'=>'desc','sort'=> 'activity','q'=>'laravel eloquent','site'=>'stackoverflow'];
$response = $client->get('http://api.stackexchange.com/2.2/search/advanced',['query' => $parameters ]);
The resultant effective URL that Guzzle creates is correct: if you open the link in your browser you'll see that it works fine and returns the requested data.
However, Guzzle fails with this error when trying to access the JSON with $response->json():
GuzzleHttp \ Exception \ ParseException
Unable to parse JSON data: JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded
After reading the documentation again, I believe that the request is compressed and I am not passing the appropriate content header. If this is so, can you please let me know which header I should be passing to get the correct response?
Ok so the following code works for me.
$client = new GuzzleHttp\Client();
$parameters = ['pagesize'=>'2','order'=>'desc','sort'=> 'activity','q'=>'laravel eloquent','site'=>'stackoverflow'];
$params = http_build_query($parameters);
$request = $client->createRequest('GET', 'http://api.stackexchange.com/2.2/search/advanced?'.$params);
$request->addHeader('Accept-Encoding','GZIP');
$request->addHeader('Content-Type','application/json');
$response = $client->send($request);
var_dump($response->json());