Back to Blog
Lesson 36 of the WordPress Plugin Development: Foundations (PHP & MVC) course
WordPressJune 25, 20263 min read

REST API Integration: Exposing Data for External Consumption

Learn to extend the WordPress REST API by registering custom endpoints. We'll show you how to securely serve your Knowledge Base data as structured JSON.

WordPressREST APIJSONPlugin DevelopmentMVCAPIphpplugin-development

Previously in this course, we covered handling AJAX requests, which is excellent for internal dashboard communication. Today, we move beyond the admin area to make your plugin data accessible to the outside world via the WordPress REST API.

The WordPress REST API provides a standardized interface for interacting with your site's data. By registering custom endpoints, you transform your Knowledge Base plugin from a simple CMS add-on into a headless data source capable of feeding mobile apps, external frontends, or third-party integrations.

Registering Your Custom API Endpoint

In WordPress, you register API routes using the register_rest_route function, typically hooked into rest_api_init. Think of this as defining a URL pattern and mapping it to a callback function that returns your data.

To maintain our MVC structure, we’ll handle this in an ApiController class. Here is how you define a route to fetch our Knowledge Base articles:

PHP
class ApiController {
    public function register_routes() {
        register_rest_route('kb-plugin/v1', '/articles', [
            'methods'  => 'GET',
            'callback' => [$this, 'get_articles'],
            'permission_callback' => '__return_true', #6A9955">// Public access
        ]);
    }

    public function get_articles($request) {
        $articles = new WP_Query(['post_type' => 'knowledge_article']);
        $data = [];

        if ($articles->have_posts()) {
            foreach ($articles->posts as $post) {
                $data[] = [
                    'id'    => $post->ID,
                    'title' => $post->post_title,
                    'link'  => get_permalink($post->ID),
                ];
            }
        }

        return new WP_REST_Response($data, 200);
    }
}

Defining Endpoint Permissions

The permission_callback is your primary security gate. Never leave this as __return_true for sensitive data. If you want to restrict access to logged-in users with specific capabilities, use current_user_can:

PHP
'permission_callback' => function() {
    return current_user_can('edit_posts');
},

By enforcing these checks, you ensure that your REST API remains secure while still providing the flexibility needed for different user roles. If you need more complex validation later, you might explore custom schema-validated endpoints to ensure incoming requests follow a strict structure.

Returning Formatted JSON Data

The WP_REST_Response object automatically handles the serialization of your array into valid JSON. When you return this object, WordPress sets the correct Content-Type: application/json header, allowing consumers to parse your data effortlessly.

If your data grows, consider how clients consume it. Rather than dumping entire objects, focus on efficient payloads. You can read more about field selection patterns to optimize how much data you send over the wire.

Hands-on Exercise

  1. Create an ApiController class in your plugin’s src/Controllers folder.
  2. Register a new route /kb-plugin/v1/article/(?P<id>\d+) that accepts an ID parameter.
  3. Update the callback method to return a single article’s details using get_post() and WP_REST_Response.
  4. Test your endpoint by visiting yoursite.com/wp-json/kb-plugin/v1/article/123 in your browser.

Common Pitfalls

  • Forgetting rest_api_init: If your endpoint returns a 404, check that your register_rest_route call is inside a function hooked to rest_api_init.
  • Hardcoding URLs: Always use get_permalink() or rest_url() instead of manually constructing strings. This keeps your plugin portable across environments.
  • Ignoring Error States: If a post isn't found, don't return an empty array. Return a WP_Error object with a 404 status code so the client knows exactly what happened.

Recap

Building custom REST API endpoints is the bridge between a static WordPress site and a modern, dynamic web application. By using register_rest_route, implementing strict permission_callback logic, and returning WP_REST_Response objects, you've successfully exposed your plugin's internal data to the world.

Up next: We'll dive into advanced database queries to fetch complex datasets efficiently.

Similar Posts