Learn to map REST API callbacks to HTTP GET methods, return structured JSON responses, and format WordPress post data for your custom Knowledge Base plugin.
Previously in this course, we covered the Anatomy of a REST API Endpoint: Mastering register_rest_route and reinforced security with Implementing REST API Permission Callbacks for Secure Plugins. Now that your endpoint is registered and secured, it’s time to make it useful: we need to fetch data from the database and return it to the client.
In the REST API, the GET method is the primary vehicle for data retrieval. When a client requests your endpoint, WordPress triggers the callback function you defined during registration. Our goal today is to ensure that callback successfully queries our "Knowledge Base" custom post type and returns the data in a clean, predictable JSON format.
When you register a route, you specify the methods allowed for that endpoint. To specifically handle GET requests, you map the methods key to WP_REST_Server::READABLE (which is a constant for GET).
The callback function receives a WP_REST_Request object as its first argument. This object contains all the information about the request, including URL parameters, headers, and query strings.
Let's implement a callback that fetches the latest Knowledge Base articles. In your plugin's main entry point or a dedicated API class, define the following:
PHPadd_action( 'rest_api_init', function () { register_rest_route( 'kb-plugin/v1', '/articles', [ 'methods' => WP_REST_Server::READABLE, 'callback' => 'get_knowledge_base_articles', 'permission_callback' => 'my_plugin_permission_check', #6A9955">// As learned previously ] ); } ); function get_knowledge_base_articles( WP_REST_Request $request ) { $args = [ 'post_type' => 'knowledge_base', 'posts_per_page' => 10, 'post_status' => 'publish', ]; $query = new WP_Query( $args ); $posts = $query->get_posts(); if ( empty( $posts ) ) { return new WP_REST_Response( [], 200 ); } $data = []; foreach ( $posts as $post ) { $data[] = [ 'id' => $post->ID, 'title' => get_the_title( $post->ID ), 'excerpt' => get_the_excerpt( $post->ID ), 'link' => get_permalink( $post->ID ), ]; } return new WP_REST_Response( $data, 200 ); }
Notice that we don't echo anything. In the WordPress REST API, you return a WP_REST_Response object (or a WP_Error if something goes wrong). WordPress automatically handles the header serialization, turning your array into a valid JSON response.
The structure of the data you return is entirely up to you, but keep it consistent. If you are building a React dashboard, your frontend will expect the same fields in every response. Avoid returning the raw global $post object, as it contains unnecessary overhead and potentially sensitive system data. Always map the fields to a clean associative array as shown above.
To advance our project, update your get_knowledge_base_articles function to include a category parameter.
$request->get_param('category').tax_query to your $args array to filter results.?category=your-slug to the endpoint URL.WP_Post object directly. It exposes too much internal data and can cause circular reference issues when serialized to JSON. Always sanitize and curate your output.200 OK status code. If your logic fails to find posts, it is not necessarily an error (like a 404 or 500); it is a valid response of "no data found."WP_Error: If a critical failure occurs (e.g., database connection error), return a WP_Error object. WordPress will automatically convert this into a proper error response with the correct HTTP status (e.g., 500).By mapping callbacks to WP_REST_Server::READABLE, we ensure that our Knowledge Base plugin can securely and efficiently expose data. We've learned that returning a WP_REST_Response ensures our data is delivered as clean JSON, and by manually mapping our fields, we keep our API payload lightweight and predictable.
Up next: We will explore Validating and Sanitizing API Arguments, where we'll learn how to ensure that the parameters sent by your frontend are safe before they touch your database.
Learn to extend the WordPress REST API by registering custom endpoints. We'll show you how to securely serve your Knowledge Base data as structured JSON.
Read moreLearn to update existing WordPress resources using REST API PUT and PATCH methods. Master ID-based routing and secure data modification for your plugins.
Handling GET Requests in REST API
Implementing CRUD in the Admin UI
Understanding WordPress Data Store Architecture
Registering a Custom Data Store
Writing Selectors for Data Access
Defining Actions and Reducers
Implementing Resolvers for Data Fetching
Optimizing Performance with Selectors
Handling Complex State Dependencies
Implementing Nonce Verification
Advanced Sanitization Techniques
Input Validation and Error Handling
Protecting Admin Screens
Production Build Pipeline
Debugging React in the WordPress Admin
Building Search and Filter Functionality
Internationalization in React
Managing File Uploads via REST API
Optimizing API Response Times
Working with Date and Time in React
Implementing Drag-and-Drop Sorting
Creating Custom Hooks for API Logic
Integrating with Gutenberg Blocks
Handling Conflict Resolution
Building a Modal Confirmation System
Implementing Activity Logging
Using Webpack Aliases
Unit Testing API Endpoints
Unit Testing React Components
Handling Large Datasets with GraphQL
Implementing Real-time Updates with Web