Guzzle post with cookie and data - php

Current curl format
curl -v --cookie "JSESSIONID=xxxxxxxxx" -X POST --data "[\"test\",\"password\"]" http://domain.com/register
How do I validate cookie & post the data using Guzzle?
$url = 'http://domain.com/register';
$client = new GuzzleHttp\Client();
$jar = new \GuzzleHttp\Cookie\CookieJar();
$register = $client->post($url, ['cookies' => $jar, 'http_errors' => false]);

Use form_params request option to post data.
Use debug request option to compare your request from Guzzle to the curl request.
There are plenty of examples within SO and the Guzzle documentation explains things very well.

Related

viewing guzzle post request

i would like to see the post request packet before i send it as there is an error in the req and a the api is a general descript 500
error so i cant tell where y request is failing. i mnow the xml is formatted wrong as it works on postman from chrome.
$client = new GuzzleHttp\Client([
'base_uri' => 'https://elstestserver.endicia.com',
]);
$xml = 'changePassPhraseRequestXML=<ChangePassPhraseRequest> <RequesterID>lxxx</RequesterID><RequestID>1263055835</RequestID><CertifiedIntermediary><AccountID>lxxx</AccountID><PassPhrase>dfdsfsd</PassPhrase></CertifiedIntermediary><NewPassPhrase>fdfdsfdsfs</NewPassPhrase></ChangePassPhraseRequest>';
$data = array("ChangePassPhraseXML" => $xml);
$response = $client->post("/LabelService/EwsLabelService.asmx/ChangePassPhraseXML", [
'form_params' => $data
]);
this request works in postman for chrome the heres a working example of the xml
changePassPhraseRequestXML=<ChangePassPhraseRequest><RequesterID>lxxx</RequesterID><RequestID>1263055835</RequestID><CertifiedIntermediary><AccountID>lxxx</AccountID><PassPhrase>dfdsfsd</PassPhrase></CertifiedIntermediary><NewPassPhrase>fdsfdsfds</NewPassPhrase></ChangePassPhraseRequest>
Use Logger middleware
About middlewares for guzzle
Also, 500 error is server fail, not yours.

DELETE request with parameters using Guzzle

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

POST json returns 400 with curl but functional test working

I am trying to build the POST of an API using Symfony2 and FOSRestBundle. The following functional test returns OK.
public function testPostArticleAction(){
$this->client->request(
'POST',
'/api/v1/articles.json',
array(),
array(),
array('CONTENT_TYPE' => 'application/json'),
'{"articleContent":"The content of the content"}'
);
$response = $this->client->getResponse();
$this->assertJsonResponse($response,201, false);
}
But when I try to send a request via Curl with the same request body, it gives me a 400 invalid json message:
{"code":400,"message":"Invalid json message received"}
Here are the curl commands I have tried:
curl -X POST -d '{"articleContent":"title1"}'
http://localhost:8000/api/v1/articles --header
"Content-type:application/json"
curl -X POST -d '{"articleContent":"title1"}'
http://localhost:8000/api/v1/articles.json
Please to note that the GET returns to me a json like:
{"id":68,"article_content":"contents contents"}
But my field is articleContent in my doctrine mapping file. What am I missing?
Your help is much appreciated.
Try updating your header option to:
"Content-Type: application/json"
Additionally - does this request require any type of authentication? You'd need to pass in an auth cookie if so.

attach file as multipart/form-data content-type - Laravel

I am using FreshDesk API as a ticketing system. When trying to send an attachment, it was stated that it should be sent as multipart/form-data content-type. Could someone explain how this is done?!
How I am sending attachments:
$json = json_encode(
array(
"helpdesk_note" => array(
"body" => Input::get('reply'),
"user_id" => $requester_id,
"attachments" => Input::get('photo'),
"private" => true
)
)
);
I don't know how you're querying the API but in case you're using CURL, just set the appropriate header:
curl_setopt($ch , CURL_HTTPHEADER , "Content-Type: multipart/form-data" );
Personally I would recommend Guzzle which has a clean and straightforward API.
In Guzzle you can modify your headers in a more OO-Way. There are several ways to accomplish your task. On possible approach could be:
$client = new GuzzleHttp\Client();
$request = $client->createRequest('POST', 'https://url.com/to/post/to');
$request->setHeader('content-type', 'multipart/form-data');
// Set the data you need to
$response = $client->send($request);
var_dump($response);
Guzzle btw, is a piece of cake to integrate with Laravel. Just require it in your composer.json and you're good to go!

Guzzle and Stack Exchange API, parsing error "JSON_ERROR_UTF8"

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());

Categories