Wp REST API

Wp REST API

Use when building, extending, or debugging WordPress REST API endpoints/routes: register_rest_route, WP_REST_Controller/controller classes,

Category: design Source: WordPress/agent-skills

What Is This?

The WordPress REST API is a built-in interface that allows external applications and internal WordPress features to communicate with your site using standard HTTP requests. It exposes WordPress data such as posts, pages, users, taxonomies, and custom content through structured JSON endpoints. Developers can read, create, update, and delete data without loading the full WordPress stack in a browser.

The REST API was introduced in WordPress 4.7 and has since become the foundation for the block editor, mobile apps, and countless third-party integrations. It follows REST conventions, meaning resources are accessed via predictable URLs and standard HTTP methods like GET, POST, PUT, PATCH, and DELETE.

Why Use It?

The WordPress REST API solves a fundamental problem: how to make WordPress data accessible to decoupled front ends, mobile applications, and external services without relying on PHP templates or admin-ajax.php hacks.

There are several strong reasons to use it. First, it provides a clean, standardized contract between your WordPress backend and any consuming client. Whether you are building a React front end, a mobile app, or a third-party integration, the API gives you a consistent way to exchange data.

Second, it supports custom endpoints, meaning you are not limited to the default routes WordPress provides. You can register your own routes to expose business logic, aggregate data from multiple sources, or return exactly the shape of data your application needs.

Third, it includes built-in support for authentication, permission callbacks, argument validation, and schema definition. This means you can enforce security and data integrity at the API layer rather than scattering those checks throughout your codebase.

How to Use It?

The primary function for registering custom endpoints is register_rest_route. You call it inside the rest_api_init action hook.

add_action( 'rest_api_init', function () {
    register_rest_route( 'myplugin/v1', '/items/(?P<id>\d+)', array(
        'methods'             => 'GET',
        'callback'            => 'myplugin_get_item',
        'permission_callback' => 'myplugin_permissions_check',
        'args'                => array(
            'id' => array(
                'validate_callback' => function( $param ) {
                    return is_numeric( $param );
                },
            ),
        ),
    ) );
} );

For more complex APIs, extending WP_REST_Controller is the recommended approach. This base class provides a consistent structure for CRUD operations and includes helper methods for building responses, checking permissions, and validating schemas.

class MyPlugin_REST_Controller extends WP_REST_Controller {

    public function register_routes() {
        register_rest_route( $this->namespace, '/' . $this->rest_base, array(
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_items' ),
                'permission_callback' => array( $this, 'get_items_permissions_check' ),
            ),
        ) );
    }

    public function get_items_permissions_check( $request ) {
        return current_user_can( 'read' );
    }

    public function get_items( $request ) {
        return rest_ensure_response( array( 'data' => 'your data here' ) );
    }
}

You can also extend existing endpoints by adding custom fields using register_rest_field, which lets you attach additional data to default resources like posts or users without replacing the entire endpoint.

register_rest_field( 'post', 'custom_field', array(
    'get_callback'    => function( $post ) {
        return get_post_meta( $post['id'], 'custom_field', true );
    },
    'update_callback' => function( $value, $post ) {
        update_post_meta( $post->ID, 'custom_field', sanitize_text_field( $value ) );
    },
    'schema'          => array( 'type' => 'string' ),
) );

When to Use It?

Use the WordPress REST API when you are building a headless WordPress site where the front end is powered by JavaScript frameworks like React, Vue, or Next.js. It is also the right tool when you need to expose WordPress data to a mobile application or a third-party service.

Use it when you need to create internal tooling that reads or writes WordPress data programmatically, or when you want to replace legacy admin-ajax.php endpoints with something more structured and maintainable.

It is also appropriate when you need to debug existing API behavior, inspect what data is being returned, or extend default endpoints with additional fields.

Important Notes

Always define a permission_callback for every route. Omitting it or setting it to __return_true without intention can expose sensitive data or allow unauthorized writes.

Namespace your routes using a plugin slug and version number, such as myplugin/v1, to avoid conflicts with WordPress core routes or other plugins.

Use rest_ensure_response to wrap your return values. This guarantees a proper WP_REST_Response object is returned even if you pass a plain array or a WP_Error.

Validate and sanitize all incoming arguments using the args array in your route definition. Define schemas explicitly to improve both security and discoverability of your API.