I'm trying to use an API with wp_remote_get which requires pagination.
Currently, my WordPress plugin calls the API the following way
$response = wp_remote_get( "https://api.xyz.com/v1/products" ,
array( 'timeout' => 10,
'headers' => array(
'Authorization' => 'Bearer xyz',
'accept' => 'application/json',
'content-type' => 'application/json'
)
));
$body = wp_remote_retrieve_body( $response );
return json_decode($body);
Now, if I change the URL from /products to /products?page_size=5&page=2, which works fine in Postman and other programs, i am not getting a response. Why is that? I checked the API documentation of wp_remote_get but am not figuring it out.
Typically you use curl command to GET the response but I would recommend you to use Guzzle PHP HTTP client to make your calls if you are making multiple of them.
You will have to compser install Guzzle.
composer require guzzlehttp/guzzle:^7.0
I am expecting that the autoloader class is loaded.
Once installed and you can use it as follows.
use GuzzleHttp\Client;
$client = new Client(
[
// Base URI is used with relative requests.
'base_uri' => https://api.xyz.com/v1/,
// You can set any number of default request options.
'timeout' => 10.0,
]
);
$url = 'products';
$payload = array(
'page_size' => 5,
'page' => 2,
);
try {
$request = $client->request(
'GET',
$url,
[
'query' => $payload,
]
);
$status = $request->getStatusCode();
$response = json_decode( $request->getBody() );
if ( 200 === $status ) {
echo $response;
}
} catch ( Exception $e ) {
echo $e;
}
You can change the $url and $payload for other queries.
Related
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);
}
Context:
I've been working on figuring out how to make this work for a while, and I simply don't understand why Guzzle isn't working for this particular request. The same initialization and request structure works in some basic unit tests I have, but when it comes to API to API communication, Guzzle just is not cooperating.
Problem:
What I mean by that is, it's not including the headers I'm setting in the $headers array, and the request body is empty.
Desired result:
To confirm this is an issue with Guzzle, I've written out the request with typical cURL syntax, and the request goes through fine. I just need some guidance on how to make this work with Guzzle, as I like the abstraction Guzzle offers over verbose cURL requests.
Working cURL request:
$headers = array(
'Authorization: Bearer '.$sharedSecret,
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
'Content-Length: '.strlen($loginDetails),
);
$curlOptions = array(
CURLOPT_URL => API_URL.'member/SessionManager',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => FALSE,
CURLOPT_HEADER => FALSE,
CURLOPT_FOLLOWLOCATION => FALSE,
CURLOPT_ENCODING => "",
CURLOPT_USERAGENT => "PORTAL",
CURLOPT_AUTOREFERER => TRUE,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $loginDetails,
CURLOPT_SSL_VERIFYHOST => FALSE,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_VERBOSE => FALSE
);
try {
$ch = curl_init();
curl_setopt_array($ch,$curlOptions);
$content = curl_exec($ch);
$err = curl_errno($ch);
$errmsg = curl_error($ch);
$response = curl_getinfo($ch);
curl_close($ch);
if ($content === FALSE) {
throw new Exception(curl_error($ch), curl_errno($ch));
} else {
return true;
}
} catch(Exception $e) {
trigger_error(sprintf('Curl failed with error #%d: %s', $e->getCode(), $e->getMessage()), E_USER_ERROR);
}
The Guzzle client is initialized in a global file that creates a container which stores various objects we use throughout the application. I'm including it in case I missed something vital that isn't in Guzzle's documentation.
Guzzle initialization:
$container['client'] = function ($c) {
return new \GuzzleHttp\Client([
'base_uri' => API_URL,
'timeout' => 30.0,
'allow_redirects' => true,
'verify' => false,
'verbose' => true,
[
'headers' => [
'Authorization' => 'Bearer '.$sharedSecret,
]
],
]);
};
Non-working Guzzle Request:
$headers = array(
'Authorization' => 'Bearer '.$sharedSecret,
'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/json',
'Content-Length'=> strlen($loginDetails),
);
try {
$response = $this->client->post('/api/member/SessionManager',
['debug' => true],
['headers' => $headers],
['body' => $loginDetails]
);
if($response) {
$this->handleResponse($response);
}
} catch (GuzzleHttp\Exception\ClientException $e) {
$response->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
}
Whether I remove the headers array in the Guzzle initialization or not, it doesn't matter. The Authorization header is nowhere to be found in the request (confirmed with tcpdump, Wireshark, and receiving API error logging), and Guzzle's debug output shows no indication of my headers, nor my request body being anywhere in the request.
I'm stumped as to why this isn't working, and would very much like to understand. I can go the route of not using Guzzle, but would really prefer to due to brevity. Any input would be greatly appreciated.
In cURL request, the API URL being called is
API_URL.'member/SessionManager'
While in Guzzle request, the API URL being called has extra text "/api/"
(assuming API_URL is defined same in both cases)
new \GuzzleHttp\Client([
'base_uri' => API_URL,
...
$this->client->post('/api/member/SessionManager',
Appreciate that the question is old, but I thought I'd share my experience as I also struggled with this. The equivalent of:
CURLOPT_POSTFIELDS => $loginDetails,
in Guzzle is:
"query" => $loginDetails
In addition, I have found that if the base_uri does not end with a /, Guzzle will misunderstand it.
With all that in mind, your POST request should be as follows:
$response = $this->client->post('api/member/SessionManager', // Removed the first / as it's part of the base_uri now
['debug' => true],
['headers' => $headers],
['query' => $loginDetails] // Replaced "body" with "query"
);
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);