WordPress REST API Tutorial: Query Posts, Authenticate Requests, and Build Safe Integrations
REST APIheadless WordPressauthenticationJavaScriptcustom endpointsintegrations

WordPress REST API Tutorial: Query Posts, Authenticate Requests, and Build Safe Integrations

CCode Craft Studio
2026-11-19
7 min read

A practical WordPress REST API checklist for querying posts, authenticating requests, exposing custom content, and building safer integrations.

This WordPress REST API tutorial gives you a repeatable workflow for retrieving posts, testing requests, authenticating private operations, exposing custom content, and building integrations that fail safely. Use it when connecting WordPress to JavaScript, a mobile interface, a reporting tool, or another application.

Overview

The WordPress REST API exposes site data through predictable HTTP endpoints. A typical request uses the site URL, the /wp-json/ namespace, a resource such as wp/v2, and an object type such as posts or pages.

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

Start with discovery rather than guessing. Open https://example.com/wp-json/ in a browser or request it with a command-line tool. The response describes available namespaces and routes. Then inspect a specific route:

curl -i "https://example.com/wp-json/wp/v2/posts?per_page=5"

For public content, no authentication may be needed. Private records, editorial actions, user data, and write operations require authentication and permission checks. Treat the API as an application boundary: validate inputs, request only the fields you need, and avoid exposing capabilities that the consuming application does not require.

Core request concepts

  • Route: The path that identifies a resource, such as /wp/v2/posts.
  • Query parameters: Options such as search, after, categories, orderby, and per_page.
  • Response headers: Headers such as X-WP-Total and X-WP-TotalPages help a client handle pagination.
  • Embedded data: Adding _embed can include related data, such as featured media, in the response.
  • Status codes: A successful response is not the same as a valid business result. Check both the HTTP status and the returned JSON.

Checklist by scenario

Scenario 1: Retrieve and display posts

  1. Confirm the site URL and REST route.
  2. Choose a narrow query instead of downloading every field and record.
  3. Set a reasonable per_page value and implement pagination.
  4. Decide how the frontend will handle empty results, deleted posts, and failed requests.
  5. Escape or safely render returned content according to the destination framework.

For example, this request retrieves published posts from a category and asks WordPress to include related data:

GET /wp-json/wp/v2/posts?categories=12&per_page=10&page=1&_embed

A JavaScript client should treat the response as untrusted input and handle network errors separately from API errors:

async function getPosts(page = 1) {
  const url = new URL('/wp-json/wp/v2/posts', window.location.origin);
  url.searchParams.set('page', page);
  url.searchParams.set('per_page', '10');
  url.searchParams.set('_embed', '1');

  const response = await fetch(url);
  const body = await response.json();

  if (!response.ok) {
    throw new Error(body.message || 'The WordPress request failed.');
  }

  return {
    posts: body,
    totalPages: Number(response.headers.get('X-WP-TotalPages') || 1)
  };
}

Scenario 2: Choose authentication

Use the least powerful authentication method that satisfies the integration. Public endpoints are preferable when the data is intentionally public. Do not place long-lived credentials in browser JavaScript, public repositories, or client-side configuration.

MethodSuitable useImportant checks
Public endpointReading content that is meant to be publicConfirm that drafts, private fields, and user data are not exposed
Cookie authenticationRequests made inside an authenticated WordPress session, such as editor-facing interfacesUse a nonce and verify the current user’s capabilities
Application PasswordsServer-to-server or command-line requests tied to a WordPress userUse HTTPS, limit the account’s privileges, and revoke credentials when no longer needed
OAuth-style integrationSystems that need delegated authorization across applicationsUse a maintained implementation, narrow scopes where available, and protect tokens

For a command-line test using an application password, keep credentials out of shell history where practical:

curl --user "username:application-password" \
  -H "Content-Type: application/json" \
  "https://example.com/wp-json/wp/v2/users/me"

The exact authentication design depends on where the request originates and what it must do. A browser-based public frontend and a private deployment service should not share the same credential strategy.

Scenario 3: Expose a custom post type

A custom post type must be registered for REST access before its records appear at a REST route. In PHP, the registration commonly includes show_in_rest and a rest_base:

register_post_type('case_study', [
  'public' => true,
  'show_in_rest' => true,
  'rest_base' => 'case-studies',
  'supports' => ['title', 'editor', 'thumbnail']
]);

The resulting route is typically:

GET /wp-json/wp/v2/case-studies

Register content models in a maintainable plugin rather than scattering them across a theme. See the WordPress custom post types and taxonomies guide for planning the content structure before exposing it to an application.

Scenario 4: Add custom fields

Custom fields are not automatically available in every REST response. If a field is registered with register_post_meta(), set show_in_rest deliberately and define its type and authorization behavior. A simplified example looks like this:

register_post_meta('post', 'subtitle', [
  'type' => 'string',
  'single' => true,
  'show_in_rest' => true,
  'sanitize_callback' => 'sanitize_text_field',
  'auth_callback' => function () {
    return current_user_can('edit_posts');
  }
]);

Do not expose sensitive operational values merely because a frontend needs one display field. Define a small, intentional response shape whenever possible.

Scenario 5: Build a custom REST route

Use register_rest_route() on the rest_api_init action. Every route should define a namespace, methods, a callback, and a permission_callback. The permission callback is not optional design work; it is the boundary that decides who may use the route.

add_action('rest_api_init', function () {
  register_rest_route('studio/v1', '/summary', [
    'methods' => WP_REST_Server::READABLE,
    'callback' => function (WP_REST_Request $request) {
      $posts = get_posts([
        'post_type' => 'post',
        'post_status' => 'publish',
        'numberposts' => 5
      ]);

      return new WP_REST_Response([
        'count' => count($posts),
        'items' => array_map(function ($post) {
          return [
            'id' => $post->ID,
            'title' => get_the_title($post),
            'url' => get_permalink($post)
          ];
        }, $posts)
      ], 200);
    },
    'permission_callback' => '__return_true'
  ]);
});

This example is intentionally public because it returns limited information about published posts. A private route should replace __return_true with a capability check, such as current_user_can('manage_options'), and should validate every request parameter.

What to double-check

  • Pagination: Never assume page one is the complete dataset. Stop when the requested page exceeds the total pages or when the response is empty.
  • Filtering: Validate dates, IDs, order values, and search terms. Do not pass arbitrary request values into database queries or unrestricted callbacks.
  • Permissions: A logged-in user is not automatically authorized for every action. Check the capability relevant to the operation.
  • Nonces: Cookie-authenticated requests from WordPress interfaces generally need the appropriate REST nonce. A nonce helps with request origin; it does not replace capability checks.
  • Response size: Use _fields when a client needs only selected properties, and use _embed only when the related data is useful.
  • Caching: Cache public, read-only responses where appropriate, but define how content changes invalidate or refresh the cache. Never cache private responses in a shared public cache.
  • Error handling: Log enough context to diagnose a failure without recording passwords, tokens, or private content. Return useful error codes and messages without revealing internals.
  • Compatibility: Test the integration with the WordPress core, PHP version, plugins, theme, and custom fields used by the site. A route can change behavior when its registration or data model changes.

For a broader deployment workflow, pair this checklist with the WordPress update testing checklist and the WordPress code review checklist.

Common mistakes

  1. Putting credentials in frontend code. Anything delivered to a browser can be inspected. Put privileged requests behind a server-side boundary.
  2. Using an overly broad user account. Create an integration identity with only the capabilities it needs, then document ownership and revocation steps.
  3. Confusing 401 and 403 errors. A 401 commonly indicates missing or invalid authentication, while a 403 usually indicates that the authenticated request lacks permission. Inspect the response body and server configuration before changing code.
  4. Forgetting content visibility. A custom post type may exist in the database but still be absent from the API if it is not registered with REST support or if its status is not publicly queryable.
  5. Trusting returned HTML. Render content through the receiving framework’s safe mechanisms. Do not insert API output into the page as raw HTML without understanding the sanitization model.
  6. Registering routes without a namespace. Namespaces reduce collisions and make versioning clearer. A route such as studio/v1 gives you room to introduce a later response format.
  7. Testing only successful requests. Test missing parameters, invalid IDs, expired credentials, insufficient permissions, empty results, rate limits, and unavailable upstream services.

If an integration modifies content, review the related hooks and filters before adding workarounds. The WordPress hooks and filters guide can help identify safer extension points.

When to revisit

Revisit this WordPress REST API checklist whenever the site’s content model, authentication design, frontend, or deployment workflow changes. It is especially useful before a seasonal planning cycle, a major campaign, a headless frontend release, a new custom post type, or a migration between hosting environments.

Before deployment, run this short review:

  • Open the discovery document and confirm that expected namespaces and routes exist.
  • Test a public read request, a valid authenticated request, and an unauthorized request.
  • Verify pagination, empty states, field visibility, and error messages.
  • Review logs and cache behavior without exposing credentials or private data.
  • Record the route version, required capabilities, expected response shape, and rollback plan.

Repeat the review after core, PHP, plugin, theme, or custom-code changes. If the integration is business-critical, keep representative requests in an automated test collection so a workflow or tool change produces an early warning rather than a production surprise. For scheduled synchronization tasks, also consult the WordPress Cron jobs guide and document what happens when a request is retried.

Related Topics

#REST API#headless WordPress#authentication#JavaScript#custom endpoints#integrations
C

Code Craft Studio

WordPress Development Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.