Building a Custom REST API in WordPress the Right Way
WordPress is often treated as a traditional CMS, but its REST API makes it possible to use WordPress as the backend for applications, dashboards, mobile clients, automation systems, and external services. The difficult part isn't registering an endpoint. The difficult part is designing the endpoint so that authentication, authorization, validation, error handling, and data access are all handled correctly. A production API needs a contract. It needs to know: Who can access it What data they can access What input is accepted What output is returned What happens when something fails Here's a practical approach. Register a Custom Route A basic WordPress REST API route can be registered with register_rest_route() . add_action ( 'rest_api_init' , function () { register_rest_route ( 'myplugin/v1' , '/posts' , [ 'methods' => WP_REST_Server :: READABLE , 'callback' => 'myplugin_get_posts' , ]); }); This creates an endpoint similar to: /wp-json/myplugin/v1/posts The namespace matters. Using: myplugin/v1 gives the API a version boundary. If the response structure changes later, a new version can be introduced without immediately breaking existing clients. Don't Put Authorization Inside the Callback A common beginner implementation does everything inside the callback: function myplugin_get_posts () { if ( ! current_user_can ( 'manage_options' )) { return new WP_Error ( 'forbidden' , 'Access denied' , [ 'status' => 403 ] ); } // Query data... } This works, but WordPress provides a cleaner place for the permission decision. Use permission_callback . register_rest_route ( 'myplugin/v1' , '/posts' , [ 'methods' => WP_REST_Server :: READABLE , 'callback' => 'myplugin_get_posts' , 'permission_callback' => function () { return current_user_can ( 'manage_options' ); }, ]); Now the endpoint has a clearer separation: Request ↓ Permission check ↓ Callback ↓ Data That separation becomes increasingly valuable as an API grows. Authentication Is Not Authorization These concepts are easy to m