Here’s our complete guide to WordPress REST API, covering everything from basics to advanced usage for developers. We’ve structured it step by step with practical examples, security, and optimization tips.
1. Introduction to WordPress REST API
The WordPress REST API allows you to interact with your WordPress site programmatically over HTTP using JSON. It lets you read, create, update, and delete content via endpoints.
Key benefits:
- Decoupled WordPress (headless CMS)
- Mobile app integration
- External site or service integration
- Custom dashboards and interfaces
Default REST API base URL:
https://example.com/wp-json/
Example core endpoints:
/wp-json/wp/v2/posts→ retrieve posts/wp-json/wp/v2/pages→ retrieve pages/wp-json/wp/v2/categories→ retrieve categories/wp-json/wp/v2/users→ retrieve users (requires auth)
2. Accessing the REST API
2.1 Reading Data (GET Requests)
Example: Fetch latest 5 posts
GET https://example.com/wp-json/wp/v2/posts?per_page=5
Using JavaScript (fetch API):
fetch('https://example.com/wp-json/wp/v2/posts?per_page=5')
.then(response => response.json())
.then(data => console.log(data));
2.2 Query Parameters
Common filters:
per_page=5→ number of itemspage=2→ paginationsearch=keyword→ search contentcategories=3→ filter by category IDauthor=1→ filter by author IDorderby=date→ order by dateorder=desc→ descending order
3. Creating Data (POST Requests)
To create posts, you need authentication. WordPress supports:
- Basic Authentication (for development)
- JWT Authentication
- OAuth 1.0a / Application Passwords (recommended for production)
Example: Using Basic Auth (dev only)
POST https://example.com/wp-json/wp/v2/posts
Authorization: Basic base64_encode(username:password)
Content-Type: application/json
{
"title": "My REST API Post",
"content": "Content from REST API",
"status": "publish"
}
PHP Example (cURL)
$ch = curl_init('https://example.com/wp-json/wp/v2/posts');
$data = [
'title' => 'My API Post',
'content' => 'Hello via REST API',
'status' => 'publish'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Basic ' . base64_encode('username:password'),
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
print_r(json_decode($response, true));
4. Updating Data (PUT/PATCH Requests)
PUT https://example.com/wp-json/wp/v2/posts/123
Authorization: Basic base64_encode(username:password)
Content-Type: application/json
{
"title": "Updated Post Title"
}
PUTreplaces the resource entirely.PATCHupdates only specified fields.
5. Deleting Data (DELETE Requests)
DELETE https://example.com/wp-json/wp/v2/posts/123?force=true
Authorization: Basic base64_encode(username:password)
force=truepermanently deletes (otherwise goes to trash).
6. Authentication Methods
6.1 Application Passwords (Recommended)
- Introduced in WP 5.6+
- Generate from user profile
- Use Basic Auth with generated password:
Authorization: Basic base64_encode(username:application_password)
6.2 JWT Authentication
- Requires plugin (e.g., JWT Authentication for WP REST API)
- Secure for headless setups and mobile apps
6.3 OAuth 1.0a
- More complex, good for third-party integrations
7. Custom REST API Endpoints
You can add your own endpoints using register_rest_route.
Example: Simple endpoint
add_action('rest_api_init', function () {
register_rest_route('myplugin/v1', '/hello', [
'methods' => 'GET',
'callback' => function ($data) {
return ['message' => 'Hello from custom endpoint!'];
}
]);
});
Access:
https://example.com/wp-json/myplugin/v1/hello
Example: Endpoint with Parameters
add_action('rest_api_init', function () {
register_rest_route('myplugin/v1', '/multiply/(?P<num1>\d+)/(?P<num2>\d+)', [
'methods' => 'GET',
'callback' => function ($data) {
return $data['num1'] * $data['num2'];
}
]);
});
- Access:
/wp-json/myplugin/v1/multiply/5/10→ returns50
8. Custom Post Types & Meta
REST API supports custom post types with 'show_in_rest' => true.
register_post_type('book', [
'label' => 'Books',
'public' => true,
'show_in_rest' => true, // Important
'supports' => ['title', 'editor', 'custom-fields'],
]);
Access custom fields
- Use
register_metawith'show_in_rest' => true
register_post_meta('book', 'isbn', [
'type' => 'string',
'single' => true,
'show_in_rest' => true,
]);
9. Permissions & Security
- GET requests are public by default.
- POST/PUT/DELETE require authentication.
- Use
permission_callbackfor custom endpoints:
register_rest_route('myplugin/v1', '/secure', [
'methods' => 'GET',
'callback' => 'secure_callback',
'permission_callback' => function () {
return current_user_can('edit_posts');
}
]);
10. Pagination, Sorting & Filtering
REST API supports:
per_page→ items per page (max 100)page→ current pageorderby→ e.g.,date,titleorder→asc/desc
Example: Get 10 latest posts from category 3
GET /wp-json/wp/v2/posts?categories=3&per_page=10&orderby=date&order=desc
11. Advanced Usage
11.1 Embed Related Data
- Add
_embed=trueto get related data (author, featured image, etc.)
GET /wp-json/wp/v2/posts?_embed
11.2 Batch Requests
- Use WP REST API batch plugin or custom endpoints to handle multiple requests in one call.
11.3 Headless WordPress
- Use REST API with frameworks like React, Vue, Angular for SPA/SSR.
- Example:
fetch('https://example.com/wp-json/wp/v2/posts')
.then(res => res.json())
.then(posts => render(posts));
12. Error Handling
REST API returns standard HTTP status codes:
200→ OK201→ Created401→ Unauthorized403→ Forbidden404→ Not Found500→ Server Error
Example: Check response
fetch('/wp-json/wp/v2/posts')
.then(res => {
if (!res.ok) throw new Error('API Error');
return res.json();
})
.then(data => console.log(data))
.catch(err => console.error(err));
13. Tools & Plugins
- Postman → test API endpoints
- WP REST API Controller → customize REST API visibility
- JWT Authentication → secure token-based auth
- Custom endpoints plugin → manage routes without coding
14. Best Practices
- Use authentication for any data-changing operations
- Validate and sanitize input in custom endpoints
- Use
_embedwisely to reduce requests - Cache responses if high traffic (use transient API or external caching)
- Limit
per_pageto avoid heavy queries
15. Useful References
Build Next-Generation Apps with NeedleCode
The WordPress REST API is the gateway to modern, decoupled web experiences. Whether you’re building a mobile app or a headless React frontend, NeedleCode provides the technical expertise to make it happen.
Our Specialized Services:
- Headless WordPress Development (Next.js/React)
- Custom REST API Extension & Optimization
- Secure Third-Party API Integrations
Let’s modernize your WordPress stack: Request a Consultation
Bridging the gap between legacy content and modern interfaces.