WordPress REST API: Custom Endpoints, Authentication & JSON Services

Merged into core in WordPress 4.7, the WordPress REST API transformed WordPress from a monolithic, server-side PHP publishing platform into an open, universally interoperable Data Provider. By exposing content over standard HTTP requests returning structured JSON (JavaScript Object Notation) payloads, the REST API enables any external software — from a mobile React Native iOS app and a Next.js web application to an IoT device or command-line terminal — to interact with your WordPress database effortlessly.

WordPress REST API and Headless Architecture Flowchart showing JSON data pipeline

Figure 39.1: WordPress REST API & Headless Decoupled Architecture

Exploring Default Core REST Endpoints

Every WordPress website natively exposes public, read-only REST endpoints under the /wp-json/ namespace:

HTTP Method API Endpoint URL Path Data Returned
GET /wp-json/wp/v2/posts Retrieves a paginated JSON array of published blog posts with titles, dates, author IDs, and rendered content.
GET /wp-json/wp/v2/pages Retrieves published static pages.
GET /wp-json/wp/v2/categories Retrieves all taxonomy categories with post counts and slugs.
GET /wp-json/wp/v2/users Retrieves public user profiles (authors who have published content).

How to Register a Custom REST API Route in PHP

When developing custom enterprise applications, developers register custom REST routes using register_rest_route() hooked into the rest_api_init action hook:

// Register Custom Endpoint: GET /wp-json/veewom/v1/latest-courses
add_action('rest_api_init', 'veewom_register_custom_rest_routes');

function veewom_register_custom_rest_routes() {
    register_rest_route('veewom/v1', '/latest-courses', array(
        'methods'             => 'GET', // or WP_REST_Server::READABLE
        'callback'            => 'veewom_get_latest_courses_api',
        'permission_callback' => '__return_true' // Publicly accessible endpoint
    ));
}

function veewom_get_latest_courses_api($request) {
    $args = array(
        'post_type'      => 'course',
        'posts_per_page' => 5,
        'post_status'    => 'publish'
    );
    
    $query = new WP_Query($args);
    $results = array();

    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
            $results[] = array(
                'id'       => get_the_ID(),
                'title'    => get_the_title(),
                'permalink'=> get_the_permalink(),
                'fee'      => get_field('tuition_fee')
            );
        }
        wp_reset_postdata();
    }

    // Return clean JSON response with HTTP 200 status
    return new WP_REST_Response($results, 200);
}

Authentication: Application Passwords vs. JWT

While GET read requests are public, writing or deleting data (POST, PUT, DELETE) requires authentication:

  • Application Passwords (Built-in Core): Since WordPress 5.6, administrators can generate random 24-character Application Passwords under Users > Profile. External scripts submit this password via HTTP Basic Authentication over SSL without sharing the main account password.
  • JWT (JSON Web Tokens): The gold-standard for decoupled single-page apps. The user submits username/password once to /wp-json/jwt-auth/v1/token, receives an encrypted JWT bearer token, and includes it in subsequent HTTP Authorization: Bearer <token> headers.

Crucial Security Note: permission_callback

In modern WordPress REST development, setting 'permission_callback' is mandatory. Omitting this parameter throws a _doing_it_wrong() security notice. For protected administrative endpoints, always pass a capability verification callback: 'permission_callback' => function() { return current_user_can('edit_posts'); }.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is CORS (Cross-Origin Resource Sharing) in the WP REST API?

By default, WordPress allows public GET requests from any origin (`Access-Control-Allow-Origin: *`). For private enterprise backends, you can restrict CORS headers to specific frontend domains using the `rest_pre_serve_request` filter.

Q2. How can I disable public user endpoints to prevent username harvesting?

Attackers often query `/wp-json/wp/v2/users` to harvest valid usernames for brute-force attacks. You can disable this endpoint using security plugins or by returning a `WP_Error` on user routes if the user is unauthenticated.

Q3. Can I filter REST API responses to return only specific fields?

Yes! Append the `_fields` parameter to any endpoint (e.g. `/wp-json/wp/v2/posts?_fields=id,title,slug`). This prevents returning the entire post body, reducing JSON payload weight by up to 90%.

Explore Related WordPress Tutorials & Next Steps

Expand your CMS mastery by studying these tightly integrated WordPress development topics:

Headless WordPress with Next.js

Fetch posts, pages, and products to render high-speed React web apps.

Custom Plugin Development

Register custom REST routes, controllers, and schema validation.

Security Hardening

Authenticate REST requests using Application Passwords and JWT.

100+ Interview Questions & Answers

Common senior developer interview questions on WP REST API and CORS.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!