banner-shape-1
banner-shape-1
object-3d-1
object-3d-2
Integrating APIs in WordPress (Custom REST Endpoints)

Integrating APIs in WordPress (Custom REST Endpoints)

Introduction

WordPress is no longer just a blogging platform — it’s a powerful CMS that can easily serve as a headless backend or a data hub for web and mobile apps. One of the best ways to extend its functionality is through custom REST API endpoints, allowing developers to connect external services, share data, and build dynamic integrations.

Whether you want to fetch data from a third-party API, expose your own data for other applications, or automate backend processes — WordPress REST API integration makes it all possible.

  • Understand the WordPress REST API structure
  • Create and register your own custom endpoints
  • Fetch data from external APIs
  • Handle authentication and security
  • Follow best practices for maintainable code

What Is the WordPress REST API?

The WordPress REST API provides a JSON-based interface that lets external apps interact with your site. For example, you can access your posts via:

https://example.com/wp-json/wp/v2/posts

Each endpoint returns data in JSON format, making it easy to integrate with frontend frameworks like React or Vue, or other systems.

WordPress also lets you create your own endpoints, which is useful when you need to:

  • Expose custom data like post meta or custom post types
  • Connect external APIs and process the response in WordPress
  • Implement business logic beyond the default routes

Setting Up a Custom REST Endpoint

Step 1: Create a Custom Plugin

To keep your code organized, create a simple plugin.

File path: /wp-content/plugins/custom-api-integration/custom-api-integration.php

<?php
/**
 * Plugin Name: Custom API Integration
 * Description: Demonstration of creating custom REST API endpoints in WordPress.
 * Version: 1.0
 * Author: Naveed Shahzad
 */

if (!defined('ABSPATH')) exit; // Prevent direct access

// Hook into REST API initialization
add_action('rest_api_init', function () {
    register_rest_route('custom/v1', '/data', [
        'methods' => 'GET',
        'callback' => 'get_custom_api_data',
        'permission_callback' => '__return_true'
    ]);
});

function get_custom_api_data(WP_REST_Request $request) {
    $data = [
        'message' => 'Custom API endpoint working successfully!',
        'timestamp' => current_time('mysql')
    ];

    return new WP_REST_Response($data, 200);
}

Activate the plugin in your WordPress dashboard, then visit:

https://yourdomain.com/wp-json/custom/v1/data

You should see:

{
  "message": "Custom API endpoint working successfully!",
  "timestamp": "2025-10-06 14:35:12"
}

Step 2: Fetching Data from an External API

Now let’s make it more useful. Suppose you want to fetch data from an external API such as JSON Placeholder.

function get_custom_api_data(WP_REST_Request $request) {
    $response = wp_remote_get('https://jsonplaceholder.typicode.com/posts');

    if (is_wp_error($response)) {
        return new WP_REST_Response(['error' => 'Failed to fetch data'], 500);
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body);

    // Return first 5 posts only
    return new WP_REST_Response(array_slice($data, 0, 5), 200);
}

When you call your endpoint, it will fetch and return data from the external API in JSON format.

Step 3: Securing Your Endpoint

Security is crucial when exposing REST endpoints. Here are some best practices:

  • Use Permission Callbacks:  Avoid using __return_true. Instead:
    'permission_callback' => function () {
        return current_user_can('manage_options');
    }
    
  • Verify Nonces for frontend AJAX requests:
    check_ajax_referer('custom_api_nonce', 'security');
  • Restrict Methods: Only allow GET or POST where needed.
  • Sanitize Input: Always validate parameters.
    $limit = intval($request->get_param('limit'));

Step 4: Accepting Parameters in Custom Endpoints

register_rest_route('custom/v1', '/posts/(?P<id>\d+)', [
    'methods' => 'GET',
    'callback' => 'get_single_post',
    'permission_callback' => '__return_true'
]);

function get_single_post($request) {
    $id = $request['id'];
    $post = get_post($id);

    if (!$post) {
        return new WP_REST_Response(['error' => 'Post not found'], 404);
    }

    return new WP_REST_Response([
        'id' => $post->ID,
        'title' => $post->post_title,
        'content' => wp_strip_all_tags($post->post_content)
    ], 200);
}

Now you can access: https://yourdomain.com/wp-json/custom/v1/posts/45 to get that post’s data.

Step 5: Handling POST Requests (Sending Data to WordPress)

register_rest_route('custom/v1', '/submit', [
    'methods' => 'POST',
    'callback' => 'handle_post_submission',
    'permission_callback' => '__return_true'
]);

function handle_post_submission(WP_REST_Request $request) {
    $params = $request->get_json_params();
    $title = sanitize_text_field($params['title'] ?? '');
    $content = sanitize_textarea_field($params['content'] ?? '');

    if (empty($title)) {
        return new WP_REST_Response(['error' => 'Title is required'], 400);
    }

    $post_id = wp_insert_post([
        'post_title' => $title,
        'post_content' => $content,
        'post_status' => 'publish',
        'post_type' => 'post'
    ]);

    return new WP_REST_Response(['success' => true, 'post_id' => $post_id], 200);
}

You can send POST data like this:

{
  "title": "My New Post",
  "content": "This post was created using the REST API!"
}

Step 6: Testing Your API Endpoints

  • Postman
  • cURL
  • Insomnia
  • Your browser (for GET requests)
curl https://yourdomain.com/wp-json/custom/v1/data
curl -X POST https://yourdomain.com/wp-json/custom/v1/submit \
    -H "Content-Type: application/json" \
    -d '{"title": "Hello API", "content": "Created via cURL!"}'

💡 Best Practices for WordPress API Integration

  • Always sanitize and validate user input.
  • Use unique namespaces like myplugin/v1 to prevent conflicts.
  • Cache external API results using set_transient().
  • Return appropriate HTTP response codes.
  • Use authentication for protected routes.
  • Version your API for future updates (v1, v2, etc.).

Real-World Example Use Cases

  • Syncing products or orders between WordPress and Shopify/WooCommerce
  • Fetching live currency rates for dynamic pricing
  • Using WordPress as a headless CMS with React or Vue
  • Integrating CRMs or marketing tools like Mailchimp or Salesforce
  • Automating data workflows between multiple systems

Conclusion

Integrating APIs in WordPress using custom REST endpoints gives you limitless flexibility to connect external services, automate workflows, and extend your website beyond traditional use cases.

Once you understand the structure — registering routes, handling requests, securing them, and managing responses — you can integrate virtually any API with WordPress.

This combination of PHP, WordPress, and REST API development is a powerful skill set for any full stack developer and an excellent way to showcase technical expertise in your portfolio.

Key Takeaways

  • Use register_rest_route() to define endpoints
  • Secure routes using permission callbacks
  • Handle GET and POST methods properly
  • Cache external API results
  • Test with Postman or cURL

Let’s Connect Beyond the Blog