Building Custom REST API Endpoints in WordPress

Modern WordPress development often goes beyond traditional server-rendered templates. Whether you are building a decoupled Headless WordPress site, a custom Gutenberg block that fetches dynamic data, or a standalone dashboard application, the WordPress REST API is your primary tool.

While WordPress comes with powerful default endpoints, building custom routes allows you to expose tailored backend data securely.

In this tutorial, we will walk through registering a custom REST API endpoint, defining strict security permissions, and returning JSON responses.

1. Registering a Custom REST Route

To register a custom route, we hook into rest_api_init and use the native register_rest_route() function. You must define a namespace, a route path, and an array of endpoints containing HTTP methods and callback functions.

Add the following code to your custom plugin or theme’s functions.php:

				
					if (!defined('ABSPATH')) {
    exit;
}

add_action('rest_api_init', 'wg_register_custom_rest_routes');

function wg_register_custom_rest_routes() {
    register_rest_route(
        'webgarage/v1',          // Namespace
        '/latest-submissions',    // Route
        [
            'methods'             => 'GET',
            'callback'            => 'wg_get_latest_submissions_endpoint',
            'permission_callback' => 'wg_rest_permission_check',
        ]
    );
}
				
			

2. Setting Up Security and Permission Callbacks

Every custom REST endpoint should include a permission_callback to prevent unauthorized access. You can check user capabilities using current_user_can() or verify nonces/application passwords depending on your app’s architecture.

				
					function wg_rest_permission_check($request) {
    // Restrict access only to users who can manage options (or change tois_user_logged_in() for subscribers)
    if (!current_user_can('manage_options')) {
        return new WP_Error(
            'rest_forbidden',
            __('You do not have permissions to view this resource.', 'webgarage'),
            ['status' => 403]
        );
    }
    
    return true;
}
				
			

3. Writing the Endpoint Callback and Returning Data

The callback function executes when a valid request hits your endpoint. You can query the database, process logic, and return data using standard PHP arrays. WordPress automatically converts return values into JSON.

				
					function wg_get_latest_submissions_endpoint($request) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'wg_submissions';

    // Optional query parameter sanitization (e.g., ?limit=5)
    $limit = $request->get_param('limit') ? absint($request->get_param('limit')) : 5;

    // Fetch data securely
    $results = $wpdb->get_results(
        $wpdb->prepare("SELECT * FROM $table_name ORDER BY time DESC LIMIT %d", $limit)
    );

    if (empty($results)) {
        return new WP_REST_Response([
            'success' => true,
            'message' => 'No submissions found.',
            'data'    => []
        ], 200);
    }

    return new WP_REST_Response([
        'success' => true,
        'data'    => $results
    ], 200);
}
				
			

4. Testing Your Endpoint

Once your code is active, you can test your new endpoint directly in your browser or via JavaScript’s Fetch API:

				
					fetch('/wp-json/webgarage/v1/latest-submissions?limit=3', {
    method: 'GET',
    headers: {
        'X-WP-Nonce': wpApiSettings.nonce // Required if authenticated
    }
})
.then(response => response.json())
.then(data => console.log(data));
				
			

Creating custom REST API endpoints empowers you to extend WordPress beyond standard limits, making it easy to build dynamic interfaces, mobile apps, or headless architectures securely.

Be sure to check out our previous tutorials on WordPress development:
Creating Custom Database Tables in WordPress with dbDelta
Creating Custom Dashboard Widgets in WordPress
How to Create Custom Options Pages in WordPress Admin Without Plugins

Need help with your project? We will be happy to help with your project. Feel free to contact us. Just reach out and we will reply soon.

Comments

No comments yet

Share Your Thoughts

Join the conversation!

Scroll to Top

Share Your Thoughts

Thank you for your comment!

Your email address will not be published. Required fields are marked *

Pro

Thank you for reaching out! We’ll be in touch within 24 hours to discuss your project

Standard

Thank you for reaching out! We’ll be in touch within 24 hours to discuss your project

Basic

Thank you for reaching out! We’ll be in touch within 24 hours to discuss your project