London Web Design Logo Black Cropped
Book a Call

WordPress REST API Integration | Headless WordPress

October 19, 2025

WordPress REST API Integration

WordPress REST API enables accessing WordPress data through HTTP requests returning JSON responses. REST API powers headless WordPress architecture, mobile applications, and JavaScript-powered interfaces. Professional developers leverage REST API creating modern applications consuming WordPress content whilst maintaining editorial workflows and content management capabilities.

What Is WordPress REST API?

WordPress REST API provides programmatic access to WordPress data through RESTful HTTP endpoints. API returns JSON-formatted data enabling external applications consuming WordPress content.

REST (Representational State Transfer) uses standard HTTP methods: GET retrieves data, POST creates data, PUT/PATCH updates data, DELETE removes data.

WordPress REST API ships with core since WordPress 4.7. No plugins required accessing default endpoints.

API exposes posts, pages, users, comments, taxonomies, and settings through standardised endpoints. Custom endpoints extend API for proprietary data.

REST API enables decoupling content management from presentation. WordPress manages content; separate applications handle display.

Understanding REST API opens modern development approaches beyond traditional WordPress development patterns.

WordPress REST API Basics

REST API follows predictable URL patterns accessing WordPress data. Understanding patterns enables intuitive API usage.

Base URL Structure:

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

wp-json - REST API base wp/v2 - WordPress core API namespace and version

Common Endpoints:

GET /wp-json/wp/v2/posts          - Retrieve posts
GET /wp-json/wp/v2/posts/123      - Retrieve specific post
GET /wp-json/wp/v2/pages          - Retrieve pages
GET /wp-json/wp/v2/users          - Retrieve users
GET /wp-json/wp/v2/categories     - Retrieve categories
GET /wp-json/wp/v2/tags           - Retrieve tags
GET /wp-json/wp/v2/comments       - Retrieve comments

Query Parameters:

/wp-json/wp/v2/posts?per_page=10              - Limit results
/wp-json/wp/v2/posts?page=2                   - Pagination
/wp-json/wp/v2/posts?categories=5             - Filter by category
/wp-json/wp/v2/posts?orderby=date&order=desc  - Sorting
/wp-json/wp/v2/posts?search=query             - Search

Response Format:

{
  "id": 123,
  "date": "2024-01-15T10:30:00",
  "title": {
    "rendered": "Post Title"
  },
  "content": {
    "rendered": "<p>Post content...</p>"
  },
  "excerpt": {
    "rendered": "<p>Post excerpt...</p>"
  },
  "author": 1,
  "featured_media": 456
}

REST API returns structured, predictable data enabling reliable application development.

Retrieving WordPress Data via REST API

Fetch WordPress content through standard HTTP requests. Modern JavaScript, mobile apps, or server-side applications consume API easily.

JavaScript Fetch Example:

// Retrieve recent posts
fetch('https://example.com/wp-json/wp/v2/posts?per_page=10')
  .then(response => response.json())
  .then(posts => {
    posts.forEach(post => {
      console.log(post.title.rendered);
    });
  })
  .catch(error => console.error('Error:', error));

// Retrieve specific post
fetch('https://example.com/wp-json/wp/v2/posts/123')
  .then(response => response.json())
  .then(post => {
    document.getElementById('title').innerHTML = post.title.rendered;
    document.getElementById('content').innerHTML = post.content.rendered;
  });

React Example:

import React, { useState, useEffect } from 'react';

function Posts() {
  const [posts, setPosts] = useState([]);
  
  useEffect(() => {
    fetch('https://example.com/wp-json/wp/v2/posts')
      .then(response => response.json())
      .then(data => setPosts(data));
  }, []);
  
  return (
    <div>
      {posts.map(post => (
        <article key={post.id}>
          <h2>{post.title.rendered}</h2>
          <div dangerouslySetInnerHTML={{__html: post.content.rendered}} />
        </article>
      ))}
    </div>
  );
}

PHP cURL Example:

$response = wp_remote_get('https://example.com/wp-json/wp/v2/posts');
$posts = json_decode(wp_remote_retrieve_body($response));

foreach ($posts as $post) {
    echo $post->title->rendered;
}

REST API enables platform-agnostic data access. Any HTTP-capable language consumes WordPress data.

Creating Custom REST API Endpoints

Custom endpoints expose proprietary data or functionality beyond default WordPress endpoints. Professional development creates custom endpoints matching specific application requirements.

Register Custom Endpoint:

function myplugin_register_routes() {
    register_rest_route('myplugin/v1', '/data', array(
        'methods' => 'GET',
        'callback' => 'myplugin_get_data',
        'permission_callback' => '__return_true', // Public endpoint
    ));
    
    register_rest_route('myplugin/v1', '/data/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'myplugin_get_single_data',
        'args' => array(
            'id' => array(
                'validate_callback' => function($param) {
                    return is_numeric($param);
                }
            )
        ),
        'permission_callback' => '__return_true',
    ));
}
add_action('rest_api_init', 'myplugin_register_routes');

Endpoint Callback:

function myplugin_get_data($request) {
    global $wpdb;
    
    $results = $wpdb->get_results(
        "SELECT * FROM {$wpdb->prefix}custom_table"
    );
    
    return rest_ensure_response($results);
}

function myplugin_get_single_data($request) {
    global $wpdb;
    $id = $request['id'];
    
    $result = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}custom_table WHERE id = %d",
        $id
    ));
    
    if (empty($result)) {
        return new WP_Error('no_data', 'No data found', array('status' => 404));
    }
    
    return rest_ensure_response($result);
}

POST Endpoint for Creating Data:

register_rest_route('myplugin/v1', '/data', array(
    'methods' => 'POST',
    'callback' => 'myplugin_create_data',
    'permission_callback' => function() {
        return current_user_can('edit_posts');
    },
    'args' => array(
        'title' => array(
            'required' => true,
            'validate_callback' => function($param) {
                return is_string($param);
            },
            'sanitize_callback' => 'sanitize_text_field',
        ),
    ),
));

function myplugin_create_data($request) {
    global $wpdb;
    
    $title = $request->get_param('title');
    
    $wpdb->insert(
        $wpdb->prefix . 'custom_table',
        array('title' => $title),
        array('%s')
    );
    
    return rest_ensure_response(array(
        'id' => $wpdb->insert_id,
        'title' => $title
    ));
}

Custom endpoints enable exposing any WordPress data through consistent REST API patterns.

REST API Authentication

Authentication secures REST API preventing unauthorised access to protected data or functionality. Multiple authentication methods suit different use cases.

Authentication Methods:

Application Passwords (Recommended):

Generate application-specific passwords through WordPress user profiles. Use with Basic Authentication:

fetch('https://example.com/wp-json/wp/v2/posts', {
  method: 'POST',
  headers: {
    'Authorization': 'Basic ' + btoa('username:application_password'),
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'New Post',
    content: 'Post content',
    status: 'publish'
  })
})

JWT (JSON Web Tokens):

Popular for Single Page Applications requiring token-based auth:

// Requires JWT Authentication plugin
// Generate token
$response = wp_remote_post('https://example.com/wp-json/jwt-auth/v1/token', array(
    'body' => array(
        'username' => 'user',
        'password' => 'pass'
    )
));

$token = json_decode(wp_remote_retrieve_body($response))->token;

// Use token
$response = wp_remote_post('https://example.com/wp-json/wp/v2/posts', array(
    'headers' => array(
        'Authorization' => 'Bearer ' . $token
    ),
    'body' => $post_data
));

Cookie Authentication:

Automatic for logged-in users making requests from same domain. Requires nonce for POST/PUT/DELETE:

// Get nonce from localized script or meta tag
const nonce = wpApiSettings.nonce;

fetch('https://example.com/wp-json/wp/v2/posts', {
  method: 'POST',
  headers: {
    'X-WP-Nonce': nonce,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(postData)
})

OAuth:

Enterprise authentication for third-party applications. Requires OAuth plugin and configuration.

Authentication selection depends on use case: application passwords for external applications, cookies for same-domain requests, JWT for SPAs, OAuth for third-party integrations.

Implement authentication carefully. Exposed REST API without authentication creates security vulnerabilities.

Combine REST API security with comprehensive WordPress security strategies.

Headless WordPress Architecture

Headless WordPress decouples content management from presentation. WordPress serves as content API; separate frontend applications handle display.

Headless Architecture Benefits:

Performance: Static frontends or server-side rendered applications outperform traditional WordPress themes.

Flexibility: Use modern JavaScript frameworks (React, Vue, Next.js) for frontends unconstrained by WordPress theming limitations.

Omnichannel: Single content source serves websites, mobile apps, and other platforms simultaneously.

Security: Reduced attack surface hiding WordPress admin from public internet.

Developer Experience: Modern development workflows with hot reloading, component libraries, and advanced tooling.

Headless Setup:

// Next.js example
export async function getStaticProps() {
  const res = await fetch('https://example.com/wp-json/wp/v2/posts');
  const posts = await res.json();
  
  return {
    props: { posts },
    revalidate: 60 // Regenerate every 60 seconds
  };
}

export default function Home({ posts }) {
  return (
    <div>
      {posts.map(post => (
        <article key={post.id}>
          <h2>{post.title.rendered}</h2>
          <div dangerouslySetInnerHTML={{__html: post.excerpt.rendered}} />
        </article>
      ))}
    </div>
  );
}

Considerations:

Headless increases complexity requiring frontend development expertise. WordPress plugins affecting frontend display won't work. SEO requires server-side rendering or static generation.

Evaluate headless carefully. Traditional WordPress suits many projects; headless benefits justify added complexity only for specific requirements.

Explore headless WordPress architecture for comprehensive implementation guidance.

REST API Performance Optimisation

REST API calls introduce latency. Optimisation strategies minimise performance impacts ensuring responsive applications.

Caching Strategies:

// Cache REST API responses
function cache_rest_response($result, $server, $request) {
    if ($request->get_method() === 'GET') {
        $key = 'rest_cache_' . md5($request->get_route());
        set_transient($key, $result, HOUR_IN_SECONDS);
    }
    return $result;
}
add_filter('rest_pre_dispatch', 'cache_rest_response', 10, 3);

Reduce Payload Size:

// Remove unnecessary fields
function customize_rest_response($response, $post, $request) {
    $data = $response->get_data();
    
    // Remove fields
    unset($data['guid']);
    unset($data['ping_status']);
    unset($data['comment_status']);
    
    $response->set_data($data);
    return $response;
}
add_filter('rest_prepare_post', 'customize_rest_response', 10, 3);

Pagination:

Always paginate large datasets:

/wp-json/wp/v2/posts?per_page=20&page=1

Field Selection:

Request only needed fields:

/wp-json/wp/v2/posts?_fields=id,title,excerpt

Batch Requests:

Combine multiple requests:

Promise.all([
  fetch('/wp-json/wp/v2/posts'),
  fetch('/wp-json/wp/v2/pages'),
  fetch('/wp-json/wp/v2/categories')
]).then(responses => Promise.all(responses.map(r => r.json())))
  .then(([posts, pages, categories]) => {
    // Process all data
  });

Performance optimisation ensures REST API responsiveness maintaining excellent user experiences.

Integrate API optimisation with broader WordPress speed strategies.

REST API Error Handling

Robust error handling prevents application crashes when API requests fail. Professional applications handle errors gracefully.

JavaScript Error Handling:

async function fetchPosts() {
  try {
    const response = await fetch('/wp-json/wp/v2/posts');
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const posts = await response.json();
    return posts;
  } catch (error) {
    console.error('Failed to fetch posts:', error);
    // Show user-friendly error message
    return [];
  }
}

PHP Error Responses:

function myplugin_endpoint($request) {
    $id = $request['id'];
    
    // Validate
    if (!is_numeric($id)) {
        return new WP_Error(
            'invalid_id',
            'Invalid ID provided',
            array('status' => 400)
        );
    }
    
    // Check existence
    $data = get_custom_data($id);
    if (!$data) {
        return new WP_Error(
            'not_found',
            'Data not found',
            array('status' => 404)
        );
    }
    
    return rest_ensure_response($data);
}

Common HTTP Status Codes:

  • 200 OK - Successful GET/PUT/PATCH
  • 201 Created - Successful POST
  • 204 No Content - Successful DELETE
  • 400 Bad Request - Invalid request data
  • 401 Unauthorised - Authentication required
  • 403 Forbidden - Insufficient permissions
  • 404 Not Found - Resource doesn't exist
  • 500 Internal Server Error - Server error

Proper error handling improves debugging and user experience.

REST API vs WP_Query

Understanding when to use REST API versus traditional WP_Query clarifies architectural decisions.

Use REST API When:

  • Building headless WordPress applications
  • Developing mobile applications
  • Creating JavaScript-heavy single-page applications
  • Needing platform-independent data access
  • Building external integrations
  • Requiring RESTful architecture

Use WP_Query When:

  • Building traditional WordPress themes
  • Server-side rendering within WordPress
  • Maximum performance (avoiding HTTP overhead)
  • Complex WordPress-specific queries
  • Leveraging WordPress template hierarchy

Comparison:

REST APIWP_Query
HTTP requestsDirect database
JSON responsesPHP objects
Platform-agnosticWordPress-specific
Network latencyImmediate
Caching complexObject caching simple
Modern architectureTraditional WordPress

Choose appropriate data access method based on project architecture and requirements.

Frequently Asked Questions

Is WordPress REST API secure?

WordPress REST API includes security measures but requires proper implementation. Authentication required for protected endpoints. Default public endpoints (posts, pages) expose publicly-visible content safely. Implement authentication for creating/modifying content. Use HTTPS preventing data interception. Validate and sanitise all inputs. Check permissions in custom endpoints. Properly configured REST API proves secure. Combine API security with comprehensive WordPress security practices.

Can I disable WordPress REST API?

Yes, disable REST API through plugins or code if unnecessary. However, REST API powers WordPress block editor; disabling breaks Gutenberg. Selectively disable endpoints rather than entire API. Most sites benefit leaving API enabled. Disable only when specific security requirements justify limitations. Evaluate whether disabling provides real security benefits versus convenience loss.

How do I add custom fields to REST API responses?

Register custom fields using register_rest_field():

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', $value);
    },
    'schema' => array(
        'type' => 'string',
        'context' => array('view', 'edit')
    )
));

Custom fields extend API responses including any WordPress data in JSON output.

What's difference between REST API and GraphQL?

REST API uses multiple endpoints returning fixed data structures. GraphQL uses single endpoint with flexible queries requesting exact needed data. REST requires multiple requests for related data; GraphQL fetches everything in one request. REST simpler implementing; GraphQL more powerful for complex data relationships. WordPress REST API ships with core; GraphQL requires plugins. Choose REST for simplicity; GraphQL for complex applications needing precise data control.

Can REST API replace traditional WordPress themes?

REST API enables headless WordPress replacing traditional themes with modern frontends. However, traditional themes remain simpler for standard websites. Headless architecture adds complexity requiring JavaScript framework expertise. Choose headless for performance-critical applications, complex frontends, or omnichannel content. Traditional themes suit most business websites requiring content management without architectural complexity. Evaluate requirements before committing to headless architecture.

How do I handle WordPress REST API rate limiting?

WordPress core doesn't include REST API rate limiting by default. Implement rate limiting through plugins or server-level (Nginx, Apache) configurations. Popular rate limiting plugins include WP REST API Controller. Server-level rate limiting provides more robust protection. Implement caching reducing API request frequency. Client-side throttling prevents excessive requests. Rate limiting protects against abuse and performance issues from excessive API usage.

Does using REST API affect WordPress SEO?

Traditional WordPress themes render SEO-friendly HTML server-side. Headless WordPress requires careful SEO implementation through server-side rendering (SSR) or static site generation (SSG). Client-side rendered SPAs harm SEO without SSR/SSG. Implement proper meta tags, structured data, and sitemaps in headless applications. Next.js, Gatsby, and Nuxt provide SEO-friendly static generation. REST API itself doesn't harm SEO; implementation approach determines SEO effectiveness. Combine REST API with proper WordPress SEO practices.


Related WordPress Development Topics:


Written by the WordPress Development Team at London Web Design, building REST API integrations for London businesses since 2015.

London Web Design Logo Black Cropped
London Web Design offers award-winning website design services tailored to your unique business goals. With over a decade of design experience, our team of friendly web designers works closely with you to create attractive, bespoke designs that not only look stunning but also drive results.
Contact
London Office
Directions
[email protected]
+44 7305 523 333
© London Wesbite Design 2025
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram