I am working on project that uses Guzzle3 (v3.9.3), I would like to know how to send a raw post request, I have tried these solutions but none of them worked for me. I am using this Guzzle3 manual.
Solution :
$client = new Client();
$client->setDefaultOption('headers', array(
'Authorization' => 'Bearer '.$token,
'Accept' => 'application/json'
));
$body = '{"filter_":{"user":{"email":"aaa#test.com"}}}';
$req = $client->post($url, array(), $body,
array(
'cert' => array($certification, 'password'),
)
);
$response = json_decode($client->send($req)->getBody(true));
Solution 2 :
$client = new Client();
$client->setDefaultOption('headers', array(
'Authorization' => 'Bearer '.$token,
'Accept' => 'application/json'
));
$body = '{"filter_":{"user":{"email":"aaa#test.com"}}}';
$req = $client->post($url, array(), array(),
array(
'cert' => array($certification, 'password'),
)
);
$req->setBody($body);
$response = json_decode($client->send($req)->getBody(true));
None of them worked for me,
Error : Client error response [status code] 404 [reason phrase] Not Found [url]
I have tried some solutions found in the internet (but for Guzzle6) it works but I don't get the right results (it doesn't take in consideration the filter that I have sent , which is the mail address, so I get all results)
...
$body = array(
'filter_' => array(
'user' => array( "email" => $email )
)
);
$req = $client->post($url, array(),array('body'=> $body),
array(
'cert' => array($certification, 'password'),
)
);
...
On postman the call to WS work.
Thanks in advance
I'm posting the response in case someone need , I had to put all the bloc between try catch
try{
$client = new Client();
$client->setDefaultOption('headers', array(
'Authorization' => 'Bearer '.$token,
));
$body = '{"filter_":{"user":{"email":"aaa#test.com"}}}';
$req = $client->post($url, array(), $body,
array(
'cert' => array($certification, 'password'),
)
);
$response = json_decode($client->send($req)->getBody(true));
catch(Guzzle\Http\Exception\BadResponseException $e){
$response = json_decode($e->getResponse()->getBody(),true);
}
Related
I am unable to call Mailchimps API 3.0 endpoints such as /lists using OAuth 2 tokens.
I already have the token and have the endpoint from the /metadata call however, when I attempt to access /lists using the below
//Get lists
$client = new \GuzzleHttp\Client(['base_uri' => $datacenter]);
$headers = [
'Authorization' => 'OAuth ' . $token,
'Accept' => 'application/json',
'Host' => $client_endpoint,
'User-Agent' => 'oauth2-draft-v10'
];
$response = $client->request('GET', 'lists', [
'headers' => $headers
]);
$lists = json_decode($response->getBody());
Surely there is a simple solution, I am new to OAuth 2 and MailChimp, and struggling to find any information about MailChimp calls using OAuth2 tokens.
I have also tried the below...
//Get list data
$client = new \GuzzleHttp\Client(['base_uri' => $client_endpoint]);
$headers = [
'Authorization' => 'OAuth ' . $token
];
$response = $client->request('GET', 'lists',[
'user' => 'anystring:' . $token,
'headers' => $headers
]);
Log::debug($response);
Any help from here would be extremely useful
It seems that providing the token in the headers in the format Authorization: OAuth [token] doesn't work as expected.
I completed the following request using PostMan, code provided for ease of use:
// GET https://us1.api.mailchimp.com/3.0/lists
// authorization:"Bearer 0319[redacted]f966"
$response = $client->get( $datacenter.'/3.0/lists', [
'headers' => ['Authorization' => 'Bearer ' . $token]
]);
$lists = json_decode($response->getBody());
Note: the code is untested, the request is tested
I'm trying to use ZohoMail's API to send email through my application. But it keeps giving me:
"{errorCode":"INVALID_METHOD"},"status":{"code":404,"description":"Invalid Input"}}
Here's the link to the Call that I'm trying to make: https://www.zoho.com/mail/help/api/post-send-an-email.html#Request_Body
Here's my function:
public static function sendEmail ($AccountId, $AuthCode, $FromAddress, $ToAddress, $Subject, $Content){
$client = new Client(); //GuzzleHttp\Client
$URI = 'http://mail.zoho.com/api/accounts/' . $AccountId . '/messages';
$headers = ['Content-Type' => 'application/json', 'Authorization' => 'Zoho-authtoken ' . $AuthCode];
$body = array('fromAddress' => $FromAddress, 'toAddress' => $ToAddress, 'subject' => $Subject, 'content' => $Content);
$Nbody = json_encode($body);
$response = $client->post($URI, $headers, $Nbody);
echo "DONE!";
}
I've tried changing the way I'm making the call but it doesn't seem like that's the problem. I've tested the call in PostMan and it works fine so there is probably something wrong with the way I'm making the call. Any help would be much appreciated.
You need to create data and headers in the same array and pass as a second argument. Use like this.
$client = new Client();
$URI = 'http://mail.zoho.com/api/accounts/'.$AccountId.'/messages';
$params['headers'] = ['Content-Type' => 'application/json', 'Authorization' => 'Zoho-authtoken ' . $AuthCode];
$params['form_params'] = array('fromAddress' => $FromAddress, 'toAddress' => $ToAddress, 'subject' => $Subject, 'content' => $Content);
$response = $client->post($URI, $params);
echo "DONE!";
Good Luck!
$client = new \GuzzleHttp\Client();
$response = $client->post(
'url',
[
GuzzleHttp\RequestOptions::JSON =>
['key' => 'value']
],
['Content-Type' => 'application/json']
);
$responseJSON = json_decode($response->getBody(), true);
$this->clients = new Client(['base_uri' => 'Url', 'timeout' => 2.0]);
$params['headers'] = ['Content-Type' => 'application/json'];
$params['json'] = array(
'parama1'=>$req->parama1,
'parama1'=>$req->parama2,
'parama3'=>$req->parama3,
);
$response = $this->clients->get('SearchBiz',$params);
$business = $response->getBody();
return View("myviewbiz")->with('business',json_decode($business));
Ty to use:
$response = $client->post($URI, $headers, ['json' => $body]);
instead of
$Nbody = json_encode($body);
$response = $client->post($URI, $headers, $Nbody);
After testing with cURL, I found that the URL had been 'moved' to https instead of http. Using just http, the call was going through in Postman but not with Guzzle. The only change I made was to make the URL:
https://mail.zoho.com/api/accounts/
The website lists it as just http and the request does go through with PostMan. I have made prior calls with just http in Guzzle from the same API and they went through. If someone could help me understand why this happened and why this specific call when using http works in PostMan and not in Guzzle, that'd be great.
This works anywhere place
use GuzzleHttp\Client;
$client = new Client();
$options = [];
$options['form_params'] = $data;
$options['http_errors'] = false; // for get exception y api response
$options['timeout'] = 5; // milliseconds
$client->request('PUT', $uri , $options);
$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']]);
}
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);
I humbly come before the people for some much needed assistance with this..
I am using (or trying to use) the skyscanner API - http://partners.api.skyscanner.net/apiservices/pricing/v1.0 as documented here. But I am coming up against this error:
HTTP request failed! HTTP/1.1 411 Length Required
PHP attempt 1
function getSkyScanner() {
$url = 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0?apiKey=MY-API-KEY';
$headers = array( 'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/xml');
$contextData = array (
'method' => 'POST',
'header' => $headers);
$context = stream_context_create (array ( 'http' => $contextData ));
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo 'error'; }
var_dump($result);
}
My server doesn't support cURL so I'm in need of a solution without it. I'm using localhost with WAMP but I have also tried a live version which comes up with the same error and seemingly same problem. I have tried almost every combination of variables in order to correct the error with a discouraging amount of success (none). This is one such variation including the form contents that I am attempting to send.
PHP attempt 2
function getSkyScanner() {
$url = 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0?apiKey=MY-API-KEY';
$params = array( 'country' => 'GB',
'currency' => 'GBP',
'locale' => 'en-GB',
'originplace' => 'LHR',
'destinationplace' => 'EDI',
'outbounddate' => '2016-10-10',
'adults' => '1'
);
$query = http_build_query($params);
$headers = array( 'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/xml');
$contextData = array (
'method' => 'POST',
'header' => $headers,
'content' => $query );
$context = stream_context_create (array ( 'http' => $contextData ));
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo 'error'; }
var_dump($result);
}
This throws out:
Content-type not specified
Followed by:
HTTP/1.1 400 Bad Request
If you can help I would appreciate some insight right about now.
Many thanks!
You create headers in a wrong way - instead of an array, headers should be passed as a string.
$headers = "Content-Type: application/x-www-form-urlencoded\r\n" .
"Accept: application/xml\r\n";
You can use below snippet to create the correct request:
function prepare_headers($headers) {
return
implode('', array_map(function($key, $value) {
return "$key: $value\r\n";
}, array_keys($headers), array_values($headers))
);
}
function http_post($url, $data, $ignore_errors = false) {
$data_query = http_build_query($data);
$data_len = strlen($data_query);
$headers = array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/xml',
'Content-Length' => $data_len
);
$response =
file_get_contents($url, false, stream_context_create(
array('http' => array(
'method' => 'POST',
'header' => prepare_headers($headers),
'content' => $data_query,
'ignore_errors' => $ignore_errors
)
)
));
return (false === $response) ? false :
array(
'headers' => $http_response_header,
'body' => $response
);
}
Example usage of http_post method:
$result = http_post('http://business.skyscanner.net/apiservices/pricing/v1.0', array(
'apiKey' => 'YOUR_API_KEY',
'country' => 'UK',
'currency' => 'GBP',
'locale' => 'en-GB',
'locationSchema' => 'iata',
'originplace' => 'EDI',
'destinationplace' => 'LHR',
'outbounddate' => '2016-10-10',
'adults' => '1'
), false);
Parameter $ignore_errors in http_post method is reponsible for fetching the content even on failure status codes (400, 500, etc.). If you receive Bad request, set ignore_errors = true -> you'll receive full response from server.