I want to use the Instgram api from RapidApi. This is what RapidAPI shows as the PHP snippet:
<?php
$request = new HttpRequest();
$request->setUrl('https://instagram47.p.rapidapi.com/public_user_posts');
$request->setMethod(HTTP_METH_GET);
$request->setQueryData([
'userid' => '1718924098'
]);
$request->setHeaders([
'x-rapidapi-key' => ' ***************** ',
'x-rapidapi-host' => 'instagram47.p.rapidapi.com'
]);
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
This is what my code looks like in functions.php:
function get_instaPosts(){
$request = wp_remote_retrieve_body( wp_remote_get( 'https://instagram47.p.rapidapi.com/user_posts', array(
'headers' => array(
"content-type" => "application/json",
'userid' => '1718924098',
'x-rapidapi-key' => 'INSTA_APIKEY',
'x-rapidapi-host' => 'instagram47.p.rapidapi.com'
),
'body' => array()
)
));
$response_code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
if( 401 === $response_code) {
echo "<pre>";
print_r("Unauthorised access");
echo "</pre>";
}
if( 200 !== $response_code) {
echo "<pre>";
print_r("Error in pinging API");
echo "</pre>";
}
if( 200 === $response_code) {
echo "<pre>";
print_r($body);
echo "</pre>";
}
}
But its consistently printing the "Error in pinging API"
defined in if (200!==...)
statement. Printing the $response gives this in between:
[body] => {"message":"Missing required parameters"}
Finally, since they give you a secret API key, is it a good practice to save the actual key as a variable inside wp-config like this and refer it later with just INSTA_APIKEY to not make it public:
/** API key for RapidApi Insta */
define( 'INSTA_APIKEY', '***************' );
FIX: In functions.php:
function get_instaPosts(){
$userid = ' ** insta userid here ** ';
$first = '2';
$after = ' ** the after code here ** ';
$response = wp_remote_get( "https://instagram40.p.rapidapi.com/account-medias?userid=$userid&first=$first&after=$after", array(
'headers' => array(
'x-rapidapi-key' => ' ** secret key ** ',
'x-rapidapi-host' => 'instagram40.p.rapidapi.com'
)
)
);
$response_code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
$decode = json_decode( $body, true );