How to Integrate a Custom API with Your WordPress Site

Jasper T Jan 16, 2025 API Integration
How do I connect my website to another service to get data or send information?
What are the steps to authenticate and interact with a custom REST API in WordPress, including creating endpoints and handling responses?
Andy answered Jan 16, 2025

Integrating External APIs with WordPress

Basic Approach

WordPress offers several methods to integrate external APIs into your site. Here's a structured approach to implement API connections:

  1. WordPress HTTP API
  2. WordPress REST API endpoints
  3. WordPress hooks and filters
  4. Authentication handling
  5. Data caching

Setting Up API Connection

First, let's create a basic API connection using WordPress HTTP API:

Basic GET request to an external API:

function get_external_api_data() {
    $api_url = 'https://api.example.com/endpoint';
    $response = wp_remote_get($api_url);
    
    if (is_wp_error($response)) {
        return false;
    }
    
    return json_decode(wp_remote_retrieve_body($response), true);
}

POST request with authentication headers:

function post_to_external_api($data) {
    $api_url = 'https://api.example.com/endpoint';
    
    $args = array(
        'method' => 'POST',
        'headers' => array(
            'Authorization' => 'Bearer ' . YOUR_API_KEY,
            'Content-Type' => 'application/json'
        ),
        'body' => json_encode($data)
    );
    
    return wp_remote_post($api_url, $args);
}

Creating Custom Endpoints

Register a custom endpoint to receive API data:

add_action('rest_api_init', function() {
    register_rest_route('my-api/v1', '/data', array(
        'methods' => 'GET',
        'callback' => 'handle_api_request',
        'permission_callback' => function() {
            return current_user_can('manage_options');
        }
    ));
});

function handle_api_request($request) {
    $data = get_external_api_data();
    if (!$data) {
        return new WP_Error('api_error', 'Failed to fetch data', array('status' => 500));
    }
    return rest_ensure_response($data);
}

Implementing Caching

Cache API responses to improve performance:

function get_cached_api_data() {
    $cache_key = 'my_api_data';
    $cached_data = get_transient($cache_key);
    
    if (false === $cached_data) {
        $cached_data = get_external_api_data();
        set_transient($cache_key, $cached_data, HOUR_IN_SECONDS);
    }
    
    return $cached_data;
}

Security Best Practices

  1. Always validate and sanitize API responses
  2. Store API keys in wp-config.php
  3. Use WordPress nonces for form submissions
  4. Implement rate limiting
  5. Add error handling

Example of secure API key storage in wp-config.php:

define('MY_API_KEY', 'your-api-key-here');

Error Handling

Robust error handling implementation:

function handle_api_errors($response) {
    if (is_wp_error($response)) {
        error_log('API Error: ' . $response->get_error_message());
        return false;
    }
    
    $status_code = wp_remote_retrieve_response_code($response);
    if ($status_code !== 200) {
        error_log('API Error: Status code ' . $status_code);
        return false;
    }
    
    return true;
}

Helpful Plugins

  1. WP REST API Controller - Manages REST API endpoints through the admin interface
  2. Advanced Custom Fields to REST API - Exposes ACF fields to the REST API
  3. API Shield - Adds security layers to your API endpoints

Common Pitfalls to Avoid

  1. Not handling API timeouts
  2. Ignoring rate limits
  3. Storing sensitive data in plain text
  4. Not implementing proper error handling
  5. Forgetting to validate API responses

Testing Your Integration

Basic API testing function:

function test_api_connection() {
    $response = get_external_api_data();
    
    if (!$response) {
        wp_die('API connection failed');
    }
    
    echo '<pre>';
    print_r($response);
    echo '</pre>';
}

// Add to admin menu for testing
add_action('admin_menu', function() {
    add_management_page('API Test', 'API Test', 'manage_options', 'api-test', 'test_api_connection');
});

Remember to implement proper error handling, caching, and security measures based on your specific needs and the API requirements you're working with.