Reputation: 21
I am trying to fetch data from this API:
https://rapidapi.com/apilayernet/api/rest-countries-v1?
endpoint=53aa5a08e4b0a705fcc323a6
I managed to use wp_remote_get() to make the request but I keep getting no result showing up apart from an error:
The site is experiencing technical difficulties.
I just point out thatI have used Composer to set up the Composer.json file in my XAMPP proper folder in which I have included the request:
{
"require-dev": {
"mashape/unirest-php": "3.*"
}
}
In my code I am including the parameter for the API key as below but for some reason is not working:
$request = wp_remote_get( 'https://restcountries-v1.p.rapidapi.com/all',
array(
"X-RapidAPI-Host" => "restcountries-v1.p.rapidapi.com",
"X-RapidAPI-Key" => "7fc872eb0bmsh1baf0c288235a1ep114aecjsn18f888f020c0"
) );
if( is_wp_error( $request ) ) {
return false; // Bail early
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
echo $data;
Upvotes: 0
Views: 1403
Reputation: 655
This is the method I use on all of my gets from Wordpress
$url = 'https://restcountries-v1.p.rapidapi.com/all'; //define url
$response = wp_remote_get($url, array(
'headers'=> array('X-RapidAPI-Host' => 'restcountries-v1.p.rapidapi.com', //set header
'X-RapidAPI-Key' => '<apikey>'//set api key
),
'method' => 'GET',//set method
));
$decode = json_decode($response);// decode response
echo "<pre>"; print_r($decode); die('dead');// display response on page wiothout any other information.
Upvotes: 0
Reputation: 3128
The wp_remote_get
accepts an array of options as the second argument, but you passed the headers directly.
They should be inside a nested headers
array inside the options.
Method Documentation: https://codex.wordpress.org/Function_Reference/wp_remote_get
$request = wp_remote_get('https://restcountries-v1.p.rapidapi.com/all', [
'headers' => [
'X-RapidAPI-Host' => 'restcountries-v1.p.rapidapi.com',
'X-RapidAPI-Key' => '<apikey>',
],
]);
if (is_wp_error($request)) {
return false; // Bail early
}
$body = wp_remote_retrieve_body($request);
$data = json_decode($body);
echo $data;
Upvotes: 0