Written by 8:51 pm APIs & Integrations Views: 4

WordPress REST API for Beginners: Build Your First Custom Endpoint

Learn how to use the WordPress REST API from scratch. This hands-on tutorial covers default endpoints, authentication with Application Passwords and JWT, building custom endpoints with register_rest_route(), permission callbacks, input validation, error handling, and testing with curl and Postman.

WordPress REST API for Beginners - Build Your First Custom Endpoint tutorial

The WordPress REST API is one of the most powerful features available to WordPress developers. It transforms WordPress from a traditional CMS into a full-fledged application platform, enabling you to interact with your site programmatically using standard HTTP requests. Whether you want to build a headless frontend with React, power a mobile app, or integrate WordPress with third-party services, the REST API is your gateway. This tutorial walks you through everything you need to know to get started, including how to build your first custom endpoint from scratch.

Close-up of a person coding on a laptop, showcasing web development and programming concepts.
Photo by Lukas Blazek on Pexels

What Is the WordPress REST API?

REST stands for Representational State Transfer. In practical terms, the WordPress REST API provides a set of URL endpoints that accept and return JSON data. Instead of loading a full HTML page, you send an HTTP request (GET, POST, PUT, DELETE) to a specific URL, and WordPress responds with structured JSON data. This approach decouples the data layer from the presentation layer, opening up possibilities that go far beyond traditional WordPress themes.

The REST API was merged into WordPress core in version 4.7, released in December 2016. Before that, developers relied on admin-ajax.php for asynchronous requests or the older XML-RPC protocol. Both of those approaches had significant limitations: admin-ajax.php loads the entire WordPress admin stack on every request, and XML-RPC has a history of security vulnerabilities. The REST API replaces both with a modern, standardized, and efficient interface.

Why Should You Care?

  • Headless WordPress, Use WordPress as a backend while building the frontend with React, Vue, Next.js, or any JavaScript framework.
  • Mobile Applications, A native iOS or Android app can fetch posts, submit comments, and manage content through the REST API.
  • Third-Party Integrations, Connect WordPress to CRMs, email marketing platforms, analytics dashboards, or any external service that communicates over HTTP.
  • Custom Admin Interfaces, Build specialized dashboards or editorial tools tailored to your workflow.
  • Automation, Automate content publishing, user management, or site maintenance with scripts or CI/CD pipelines.

Exploring the Default REST API Endpoints

Every WordPress installation exposes a set of default endpoints. You can access them right now by visiting your site’s REST API index. Open your browser or use curl from the terminal:

This returns a JSON array of published posts. The /wp-json/ prefix is the REST API root, wp/v2/ is the namespace and version, and posts is the resource. WordPress ships with endpoints for all major content types:

EndpointDescription
/wp-json/wp/v2/postsBlog posts (CRUD operations)
/wp-json/wp/v2/pagesPages
/wp-json/wp/v2/categoriesPost categories
/wp-json/wp/v2/tagsPost tags
/wp-json/wp/v2/usersUser profiles
/wp-json/wp/v2/mediaMedia attachments
/wp-json/wp/v2/commentsPost comments

You can add query parameters to filter results. For example, to fetch only 5 posts from a specific category:

The REST API also supports discovery. Visit /wp-json/ without any namespace to see every registered route on your site, including those added by plugins. The media endpoint is especially useful if you manage a large number of images; for tips on keeping things performant, check out our article on using the Media Library without slowing down your site. According to the WordPress REST API Reference, the discovery endpoint is the best starting point for understanding what your site exposes.


Authentication Methods

Public endpoints like listing published posts do not require authentication. But any request that creates, updates, or deletes data requires you to prove your identity. WordPress supports several authentication methods for the REST API.

Application Passwords (Recommended for Beginners)

Introduced in WordPress 5.6, Application Passwords are the simplest way to authenticate REST API requests. You generate a unique password for each application or integration, and it is separate from your login password. To create one, go to Users → Profile in the WordPress admin, scroll to the Application Passwords section, enter a name like “My Script”, and click Add New. WordPress generates a 24-character password.

Use it with HTTP Basic Authentication. Here is a curl example that creates a new post:

Application Passwords are sent as Base64-encoded credentials in the Authorization header. Always use HTTPS in production to prevent credentials from being intercepted.

JWT Authentication

JSON Web Tokens (JWT) are a popular choice for single-page applications and mobile apps. WordPress does not include JWT support out of the box, but the official REST API Handbook documents how to implement it. The most common approach uses a plugin like JWT Authentication for WP REST API or the newer Simple JWT Login.

The typical JWT flow works like this: you send your username and password to a token endpoint, receive a JWT in return, and then include that token in the Authorization: Bearer header of subsequent requests. The token has an expiration time, so you need to handle token refresh in your application logic.

Cookie Authentication (for Logged-In Users)

If you are making REST API requests from within the WordPress admin, for example, from a custom Gutenberg block or an admin page script, WordPress automatically uses cookie-based authentication. You need to include the X-WP-Nonce header with a nonce value generated by wp_create_nonce( 'wp_rest' ). This is how the block editor communicates with the REST API internally.


Building Your First Custom Endpoint

The default endpoints cover standard WordPress content types, but real-world projects often need custom endpoints. Maybe you want to expose data from a custom database table, provide a simplified response format, or create an endpoint for a specific business process. The register_rest_route() function is how you do it.

The register_rest_route() Function

This function registers a new route (URL pattern) within a namespace. It must be called inside a callback hooked to rest_api_init. Here is the basic structure:

After adding this code to your plugin file or theme’s functions.php, you can access the endpoint at /wp-json/myplugin/v1/greeting. Let us break down the key parts.

  1. Namespace (myplugin/v1): This groups your routes and prevents conflicts with other plugins. Always include a version number so you can evolve your API without breaking existing consumers.
  2. Route (/greeting): The URL path after the namespace. Routes can include dynamic parameters (covered below).
  3. Methods: The HTTP methods this route accepts. Use WP_REST_Server::READABLE for GET, WP_REST_Server::CREATABLE for POST, or WP_REST_Server::ALLMETHODS for any method.
  4. Callback: The function that processes the request and returns a response.
  5. Permission Callback: A function that determines whether the request is authorized. This is mandatory since WordPress 5.5.

Permission Callbacks: Securing Your Endpoint

The permission callback runs before the main callback. If it returns false, WordPress returns a 401 or 403 error. Never use __return_true for endpoints that modify data or expose sensitive information. Here are practical examples:

For production plugins, use specific WordPress capabilities rather than broad role checks. The REST API Handbook on custom endpoints has a complete guide on permissions.


Handling Request Parameters

Custom endpoints become truly useful when they accept parameters. The REST API supports URL parameters, query string parameters, and request body data. The WP_REST_Request object passed to your callback provides methods to access all of these.

URL Parameters (Route Variables)

Define dynamic segments in your route using regex patterns. This example creates an endpoint to retrieve a specific item by ID:

The regex (?P<id>\d+) captures one or more digits and names the parameter id. WordPress automatically passes it through your validation and sanitization callbacks before your main callback runs.

Sanitization and Validation

Input validation and sanitization are critical for security. WordPress provides the args array for defining parameter rules. Each parameter can have:

  • required: Whether the parameter must be present.
  • default: A fallback value if the parameter is absent.
  • type: Expected data type (string, integer, boolean, array, object).
  • validate_callback: A function that returns true if the value is acceptable, or a WP_Error if not.
  • sanitize_callback: A function that cleans the value before it reaches your callback. Use WordPress functions like sanitize_text_field(), absint(), or sanitize_email().

Here is an example for a POST endpoint that accepts structured data:


Error Handling with WP_Error

Proper error handling separates a robust API from a fragile one. The WordPress REST API uses the WP_Error class to return structured error responses. When your callback returns a WP_Error object, WordPress automatically converts it into an appropriate HTTP error response with the correct status code.

The JSON response looks like this on the client side:

Always use descriptive error codes and messages. API consumers, frontend developers, mobile developers, or integration partners, will use these to handle errors gracefully in their applications.


Testing Your Endpoints

Testing is essential during development. Here are two practical approaches that every developer should be comfortable with.

Testing with curl

The command-line tool curl is the fastest way to test endpoints. Here are common patterns:

Testing with Postman

Postman provides a visual interface for building, sending, and inspecting API requests. It is especially helpful when you are working with complex request bodies or need to save collections of requests for repeated testing. To set up authentication in Postman, go to the Authorization tab, select Basic Auth, and enter your WordPress username and Application Password. Postman also lets you write automated test scripts using JavaScript, which is valuable for CI/CD pipelines.

A useful debugging tip: if an endpoint returns unexpected results, add ?_envelope to the URL. This wraps the response in an envelope that includes the HTTP status code and headers in the JSON body, making it easier to debug without inspecting raw HTTP headers.


Real-World Use Cases

Understanding the API mechanics is important, but seeing real applications is what brings the concepts together. Here are scenarios where custom REST API endpoints provide clear value.

Headless WordPress with Next.js or Gatsby

In a headless architecture, WordPress serves as the content management backend while a JavaScript framework handles the frontend. The REST API is the bridge. Your Next.js application fetches posts from /wp-json/wp/v2/posts, renders them as React components, and benefits from static site generation or server-side rendering for performance. You can even pull in navigation menus via the REST API to keep your headless frontend consistent with your WordPress admin structure. Custom endpoints let you create optimized response payloads that include only the fields your frontend needs, reducing data transfer and improving load times. According to the WordPress REST API Handbook, the API is designed with exactly this kind of decoupled architecture in mind.

Mobile Applications

A custom REST endpoint can aggregate data from multiple WordPress sources into a single response optimized for mobile consumption. Instead of making five separate API calls from a mobile app (posts, categories, user profile, site settings, notifications), you can create one endpoint that bundles everything the home screen needs. This reduces network round trips, which is critical for mobile users on slower connections.

Third-Party Integrations

Custom endpoints work well for integration scenarios. You might build an endpoint that receives webhook payloads from Stripe when a payment completes, creates a WooCommerce order, and sends a confirmation email. Or you could create an endpoint that a CRM system calls to sync customer data with WordPress user profiles. The key advantage over admin-ajax.php is that REST endpoints are stateless, cacheable, and follow HTTP standards that every integration platform already understands.


Best Practices and Security Considerations

Before you deploy your custom endpoints to production, review these essential practices. Security mistakes in APIs can expose your entire site to attackers.

  • Always define a permission callback. Since WordPress 5.5, omitting the permission callback triggers a _doing_it_wrong notice. Never leave it as __return_true for endpoints that modify data.
  • Sanitize all input. Use WordPress sanitization functions (sanitize_text_field(), sanitize_email(), absint(), wp_kses_post()) for every parameter. Never trust client-supplied data.
  • Validate before processing. Use validate_callback in your args array to reject bad data before it reaches your main logic. This is more efficient and cleaner than checking inside the callback.
  • Use HTTPS. Application Passwords and JWT tokens are transmitted in headers. Without TLS encryption, they can be intercepted. Most hosting providers offer free SSL certificates through Let’s Encrypt.
  • Namespace your routes. Always use a unique namespace like yourplugin/v1. This prevents route collisions with other plugins and allows you to version your API independently.
  • Rate limiting. The REST API does not include rate limiting by default. For public-facing endpoints, consider implementing rate limiting with a plugin or at the server level (Nginx, Cloudflare) to prevent abuse.
  • Return appropriate status codes. Use 200 for success, 201 for created, 400 for bad requests, 401 for unauthenticated, 403 for forbidden, 404 for not found, and 500 for server errors. Consistent status codes make your API predictable.

Complete Working Example: A Bookmarks Endpoint

Let us put everything together with a practical example. This plugin creates a bookmarks system where logged-in users can save and retrieve their favorite posts.

This example demonstrates GET, POST, and DELETE methods, parameter validation, permission callbacks, user-specific data, error handling with WP_Error, and appropriate HTTP status codes. You can test it with curl or Postman using the patterns shown earlier in this tutorial.


Where to Go From Here

This tutorial covers the fundamentals, but the WordPress REST API has much more to offer. As your next steps, explore these areas:

  • Schema and response filtering, Define a JSON Schema for your endpoints to enable automatic documentation and validation. Use rest_prepare_{post_type} filters to modify default endpoint responses.
  • Custom post type endpoints, When you register a custom post type with show_in_rest => true, WordPress automatically creates REST API endpoints for it. If you are still getting familiar with the difference between posts, pages, and custom types, our guide on pages vs posts vs custom post types in WordPress explains the fundamentals. You can customize the controller class for advanced behavior.
  • Batch requests, WordPress 5.6 introduced the /wp-json/batch/v1 endpoint, which lets you send multiple API requests in a single HTTP call.
  • Caching, Implement server-side caching with transients or object caching for expensive queries. Set appropriate Cache-Control headers for client-side caching.
  • Official documentation, The WordPress REST API Handbook on developer.wordpress.org is the definitive reference. Bookmark it and refer to it often.

The REST API fundamentally changes what you can build with WordPress. It turns WordPress into a platform that speaks the same language as every modern application. Start with the basics covered here, experiment with custom endpoints in a local development environment, and gradually build toward more complex integrations. Every custom endpoint you create is a building block for the applications your users need.



Frequently Asked Questions About the WordPress REST API

Is the WordPress REST API enabled by default?

Yes. The REST API is enabled by default on all WordPress sites running version 4.7 or later. You can verify it is working by visiting yoursite.com/wp-json/ in a browser, a valid JSON response means the API is active. Some security plugins or server configurations may restrict REST API access for unauthenticated requests. If you need to disable parts of the API, plugins like Disable REST API or custom filters using rest_endpoints can selectively block routes without disabling the entire API.

Can I use the REST API without a plugin?

Absolutely. The register_rest_route() function is part of WordPress core, no plugins required. You can add custom endpoints directly in your theme’s functions.php file for quick testing, or inside a custom plugin for production use. External consumers do not need any plugin on their end, they communicate with your site over standard HTTP just like any other API.

What is the difference between WP_REST_Response and WP_Error?

WP_REST_Response is for successful responses, pass it your data array and a 2xx HTTP status code. WP_Error is for error conditions, provide an error code string, a human-readable message, and optional data including the HTTP status. WordPress automatically converts WP_Error objects into properly formatted JSON error responses with the correct HTTP status. Use WP_Error for any condition where the request cannot be fulfilled: invalid input, insufficient permissions, missing resources, or server failures.

How do I version my custom REST API endpoints?

Include a version number in your namespace, for example myplugin/v1. When you need to make breaking changes, changing response structure, removing fields, requiring new parameters, register a new namespace (myplugin/v2) and keep the old one alive during a deprecation period. This allows existing integrations to keep working while you migrate consumers to the new version. The WordPress core API follows this same pattern with its wp/v2 namespace.

Should I use the REST API or admin-ajax.php for new development?

Always use the REST API for new development. The admin-ajax.php approach loads the entire WordPress admin stack on every request, making it slow and wasteful. The REST API is faster, follows HTTP standards, supports proper authentication, is cacheable, and is where WordPress core development is heading. New features like the Gutenberg block editor, Site Editor, and Full Site Editing are all built on the REST API. Writing new code against admin-ajax.php is technical debt from day one.

How do I handle CORS for my custom endpoints?

Cross-Origin Resource Sharing (CORS) becomes relevant when your frontend and WordPress backend are on different domains. WordPress adds CORS headers automatically for requests that include a valid nonce (cookie-authenticated requests from wp-admin). For external consumers using Application Passwords or JWT, you need to configure CORS headers explicitly. The most reliable approach is to add CORS headers at the server level (via Nginx configuration or an .htaccess rule) rather than in WordPress code. This ensures headers are sent even for requests that WordPress rejects before executing PHP. If you need fine-grained per-endpoint CORS control, use the rest_pre_serve_request filter to add custom Access-Control-Allow-Origin headers based on your endpoint namespace. Avoid the blanket approach of opening all routes to all origins unless your site is a fully public read-only API.

What is the REST API discovery mechanism?

Discovery lets API consumers programmatically find all available endpoints on your site. The root discovery endpoint at /wp-json/ returns a JSON document listing every registered namespace, route, and its supported HTTP methods. Individual route descriptions include schemas for accepted parameters, return values, and authentication requirements. For plugin developers, this means your endpoint documentation is built-in, API clients can introspect your endpoints without reading code. WordPress also adds a Link header to every frontend HTML page pointing to the REST API root, enabling automatic discovery for clients that follow web-standard API detection patterns.


Ready to build? Start by adding the greeting endpoint from this tutorial to a local WordPress installation. Once it responds with JSON, you have a working foundation. From there, swap in your own data, add authentication, and connect it to a frontend framework. The REST API is your bridge from WordPress to everything else.

Visited 4 times, 1 visit(s) today

Last modified: March 21, 2026

Close