WordPress Development

Building REST APIs with the WordPress WP-API Plugin

For most of its history WordPress communicated with the outside world through XML-RPC — a protocol that felt dated even when it launched. The WP-API plugin, which merged into WordPress core as of version 4.7 in 2016, changes everything. It exposes your WordPress content as a clean JSON REST API, opening the door to JavaScript-powered frontends, mobile apps, and third-party integrations.

Installing and Accessing the API

Install the WP REST API plugin from the WordPress repository, then visit:

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

You immediately get a JSON array of published posts. Every built-in content type — posts, pages, users, taxonomies, media — has its own endpoint.

Registering a Custom Endpoint

The rest_api_init hook and register_rest_route() make it straightforward to add your own routes:

add_action( 'rest_api_init', function() {
    register_rest_route( 'mytheme/v1', '/featured', [
        'methods'  => 'GET',
        'callback' => function( $request ) {
            $posts = get_posts( [
                'meta_key'   => '_featured',
                'meta_value' => '1',
                'numberposts'=> 5,
            ] );
            return rest_ensure_response( $posts );
        },
    ] );
} );

Authentication

Read-only public endpoints need no authentication. For write operations, the WP-API supports Basic Auth (over HTTPS only, suitable for development), OAuth 1.0a (for third-party clients), and cookie-based auth for JavaScript within the same WordPress installation using the built-in nonce system.

Consuming the API with JavaScript

fetch( 'https://yoursite.com/wp-json/wp/v2/posts?per_page=3' )
    .then( res => res.json() )
    .then( posts => {
        posts.forEach( post => console.log( post.title.rendered ) );
    } );

Custom Post Types in the API

Set 'show_in_rest' => true when registering a CPT to expose it at /wp-json/wp/v2/{post-type}. You can also customise the endpoint namespace and base slug.

The WP-API transforms WordPress from a monolithic blog platform into a headless CMS. This is not the future — it is happening right now, and every WordPress developer should be comfortable with it.

Share this post:
Copied!

Leave a Comment

Your email will not be published.

READY TO BUILD?

Let's Build Something
Amazing Together

Tell us about your project. We'll have a proposal in your inbox within 24 hours.

Free Consultation
NDA Available
Fixed-price Options
Dedicated PM