So I finally figured out my problems. One mistake I was making was not structuring $options
properly.
This is WRONG what i did:
$options = array(
'http' => array(
'header' => "Authorization: Bearer $api_key\r\n",
'method' => 'GET',
),
);
I’m not supposed to use http
. This is the CORRECT WAY to do it:
$options = array(
'headers' => array(
'Authorization' => 'Bearer ' . $api_key,
),
'method' => 'GET',
);
You have to use headers
instead of http
when passing in an api key.
Another mistake I made was improperly getting the response from wp_remote_get()
.
This is the WRONG WAY:
// Make the API call
$response = wp_remote_get($url, $options);
if ($response === false) {
// Handle error
return false;
}
// Process the response
$data = json_decode($response, true);
return new WP_REST_Response($data, 200);
}
using wp_remote_get()
like this is correct:
$response = wp_remote_get($url, $options);
However, the way i passed the response into json_decode($response, true)
is incorrect. I had to extract the response body like this:
This is the CORRECT WAY:
// Extract the response body
$body = wp_remote_retrieve_body($response);
// Convert the JSON response to an associative array
$data = json_decode($body, true);
After i did this, I could access the data from the api response. Here’s my correct code in its entirety:
function make_api_call_to_third_party() {
$url="https://api.pledge.to/v1/organizations";
$api_key = '{my api key}';
$options = array(
'headers' => array(
'Authorization' => 'Bearer ' . $api_key,
),
'method' => 'GET',
);
// Make the API call
$response = wp_remote_get($url, $options);
//handle error section
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
// Handle the error, return an error response or log it
return new WP_REST_Response(array('error' => $error_message), 500);
}
// Extract the response body
$body = wp_remote_retrieve_body($response);
// Log the response for debugging
error_log('API response: ' . $body);
// Convert the JSON response to an associative array
$data = json_decode($body, true);
// Check for JSON decoding errors
if (json_last_error() !== JSON_ERROR_NONE) {
// Handle JSON decoding error
return new WP_REST_Response(array('error' => 'Failed to decode JSON response'), 500);
}
//process the response
return new WP_REST_Response($data, 200);
}
//function for permissions callback
function custom_theme_api_permissions(){
return true;
}
I was stuck on this for a really long time. So i hope this helps someone out there. Happy coding everyone 🙂