WordPress wp_remote_get API call failing with RapidAPI integration

Issue with External API Integration

I’m working on connecting my WordPress website to a third-party API service through RapidAPI. The specific endpoint I’m trying to access is:

https://rapidapi.com/weatherapi/api/current-weather-data

When I attempt to retrieve data using WordPress’s built-in HTTP functions, the page crashes and displays a generic error message:

Website temporarily unavailable due to technical issues.

I’ve set up Composer in my local development environment with the following configuration:

{
    "require-dev": {
        "guzzlehttp/guzzle": "^7.0"
    }
}

Here’s the PHP code I’m using to make the API call:

$response = wp_remote_get( 'https://weatherapi-com.p.rapidapi.com/current.json?q=London', 
array(
    'headers' => array(
        "X-RapidAPI-Host" => "weatherapi-com.p.rapidapi.com",
        "X-RapidAPI-Key" => "abc123def456ghi789jkl012mno345pqr678stu901vwx234yz"
    )
));

if( is_wp_error( $response ) ) {
    return false;
}

$content = wp_remote_retrieve_body( $response );
$results = json_decode( $content );
print_r( $results );

The headers seem correct but something is preventing the request from completing successfully. Has anyone encountered similar problems when integrating RapidAPI services with WordPress?

The Problem: Your WordPress website crashes when attempting to retrieve data from a RapidAPI weather endpoint using wp_remote_get. The error message is generic (“Website temporarily unavailable due to technical issues”), providing little diagnostic information. This suggests a problem with how your WordPress site handles external API calls, not necessarily an issue with your API key or the RapidAPI service itself.

:thinking: Understanding the “Why” (The Root Cause): WordPress’s built-in HTTP functions (wp_remote_get) can be unreliable for complex or resource-intensive external API interactions. Directly calling the API from within WordPress might exceed PHP execution limits, cause conflicts with other plugins or server configurations, or be restricted by your hosting provider’s outbound connection policies. The generic error message is a common symptom of these underlying issues, making debugging difficult.

:gear: Step-by-Step Guide:

  1. Decouple API Calls from WordPress: The most effective solution is to move the RapidAPI interaction completely outside of your WordPress environment. This avoids potential conflicts and limitations within WordPress’s execution context. Create a separate, dedicated service (e.g., a small Node.js or Python script, a serverless function) to handle the API request.

  2. Create a Separate API Call Service (Example using Node.js): This example shows a basic Node.js script:

const axios = require('axios');

const apiKey = process.env.RAPIDAPI_KEY; // Retrieve from environment variables
const apiUrl = 'https://weatherapi-com.p.rapidapi.com/current.json?q=London';

axios.get(apiUrl, {
    headers: {
        'X-RapidAPI-Host': 'weatherapi-com.p.rapidapi.com',
        'X-RapidAPI-Key': apiKey
    }
})
.then(response => {
    //Process the response (e.g., save to a database, send to a webhook)
    console.log(response.data);
})
.catch(error => {
    console.error('Error fetching weather data:', error);
    //Implement robust error handling (e.g., retry logic)
});
  1. Store and Serve Data via WordPress: After fetching data using your separate service, store the results in your WordPress database (e.g., using a custom plugin or a simple database table). Create a custom WordPress endpoint to retrieve the data and display it on your website. This approach ensures your frontend remains unaffected by potential issues with external API requests.

  2. Deploy and Schedule (Optional): Deploy your Node.js script (or equivalent for other languages). Consider scheduling it using a task scheduler (e.g., cron on Linux, Windows Task Scheduler) to periodically fetch updated weather data. This avoids real-time API calls on every page load, improving performance and reliability.

:mag: Common Pitfalls & What to Check Next:

  • Error Handling: Implement comprehensive error handling in your external API service. This should include logging, retry mechanisms, and fallback strategies in case of network issues or API errors.
  • Data Storage: Choose an appropriate data storage solution within WordPress. Consider using a transient API for short-term caching or a custom database table for more persistent storage.
  • Security: Never hardcode your RAPIDAPI_KEY directly in your code. Always use environment variables for secure key management.
  • Rate Limits: Be aware of RapidAPI’s rate limits and adjust your fetching frequency accordingly.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

check ur error logs first - that generic message usually hides the real issue. also, try adding timeout args to wp_remote_get since rapidapi can be slow sometimes. had a similar prob and it was just hitting the php memory limit.

Had this same problem last month with a different RapidAPI endpoint. It’s likely an SSL issue with your hosting. Try adding ‘sslverify’ => false to your wp_remote_get arguments - just temporarily to test if that fixes the crash. Also check if your host allows outbound HTTPS on port 443. Some shared hosts block this by default. Wrap your API call in try-catch and turn on WP_DEBUG in wp-config.php to get actual error details instead of that useless generic message.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.