Mahamudul Hasan Rubel
HomeAboutProjectsSkillsExperienceBlogCoursesPhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • About
  • Projects
  • Skills
  • Experience
  • Blog
  • Courses
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 36 of the WordPress Plugin Development: Foundations (PHP & MVC) course
WordPressWordPressJune 25, 20263 min read

REST API Integration: Exposing Data for External Consumption

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.

WordPressREST APIJSONPlugin DevelopmentMVCAPIphpplugin-development

Previously in this course, we covered handling AJAX requests, which is excellent for internal dashboard communication. Today, we move beyond the admin area to make your plugin data accessible to the outside world via the WordPress REST API.

The WordPress REST API provides a standardized interface for interacting with your site's data. By registering custom endpoints, you transform your Knowledge Base plugin from a simple CMS add-on into a headless data source capable of feeding mobile apps, external frontends, or third-party integrations.

Registering Your Custom API Endpoint

In WordPress, you register API routes using the register_rest_route function, typically hooked into rest_api_init. Think of this as defining a URL pattern and mapping it to a callback function that returns your data.

To maintain our MVC structure, we’ll handle this in an ApiController class. Here is how you define a route to fetch our Knowledge Base articles:

PHP
class ApiController {
    public function register_routes() {
        register_rest_route('kb-plugin/v1', '/articles', [
            'methods'  => 'GET',
            'callback' => [$this, 'get_articles'],
            'permission_callback' => '__return_true', #6A9955">// Public access
        ]);
    }

    public function get_articles($request) {
        $articles = new WP_Query(['post_type' => 'knowledge_article']);
        $data = [];

        if ($articles->have_posts()) {
            foreach ($articles->posts as $post) {
                $data[] = [
                    'id'    => $post->ID,
                    'title' => $post->post_title,
                    'link'  => get_permalink($post->ID),
                ];
            }
        }

        return new WP_REST_Response($data, 200);
    }
}

Defining Endpoint Permissions

The permission_callback is your primary security gate. Never leave this as __return_true for sensitive data. If you want to restrict access to logged-in users with specific capabilities, use current_user_can:

PHP
'permission_callback' => function() {
    return current_user_can('edit_posts');
},

By enforcing these checks, you ensure that your REST API remains secure while still providing the flexibility needed for different user roles. If you need more complex validation later, you might explore custom schema-validated endpoints to ensure incoming requests follow a strict structure.

Returning Formatted JSON Data

The WP_REST_Response object automatically handles the serialization of your array into valid JSON. When you return this object, WordPress sets the correct Content-Type: application/json header, allowing consumers to parse your data effortlessly.

If your data grows, consider how clients consume it. Rather than dumping entire objects, focus on efficient payloads. You can read more about field selection patterns to optimize how much data you send over the wire.

Hands-on Exercise

  1. Create an ApiController class in your plugin’s src/Controllers folder.
  2. Register a new route /kb-plugin/v1/article/(?P<id>\d+) that accepts an ID parameter.
  3. Update the callback method to return a single article’s details using get_post() and WP_REST_Response.
  4. Test your endpoint by visiting yoursite.com/wp-json/kb-plugin/v1/article/123 in your browser.

Common Pitfalls

  • Forgetting rest_api_init: If your endpoint returns a 404, check that your register_rest_route call is inside a function hooked to rest_api_init.
  • Hardcoding URLs: Always use get_permalink() or rest_url() instead of manually constructing strings. This keeps your plugin portable across environments.
  • Ignoring Error States: If a post isn't found, don't return an empty array. Return a WP_Error object with a 404 status code so the client knows exactly what happened.

Recap

Building custom REST API endpoints is the bridge between a static WordPress site and a modern, dynamic web application. By using register_rest_route, implementing strict permission_callback logic, and returning WP_REST_Response objects, you've successfully exposed your plugin's internal data to the world.

Up next: We'll dive into advanced database queries to fetch complex datasets efficiently.

Previous lessonHandling AJAX RequestsNext lesson Advanced Database Queries
Back to Blog

Similar Posts

WordPressWordPressJune 25, 20263 min read

Composer for Dependencies: Managing Libraries in WordPress Plugins

Stop manually including PHP libraries. Learn how to use Composer for dependencies to streamline your WordPress plugin development and automate autoloading.

Read more
WordPressWordPressJune 25, 2026

Part of the course

WordPress Plugin Development: Foundations (PHP & MVC)

beginner · Lesson 36 of 47

  1. 1

    Plugin Anatomy and File Structure

    3 min
  2. 2

    The Plugin Lifecycle Hooks

    4 min
  3. 3

    Designing for MVC in WordPress

    3 min
3 min read

Capability Checks: Securing WordPress Plugins with Authorization

Master WordPress security by implementing capability checks. Learn to use current_user_can to restrict admin features and enforce proper access control.

Read more
WordPressJune 25, 20263 min read

Mastering the WordPress Settings API for Plugin Configuration

Learn to build professional admin pages using the WordPress Settings API. We cover registering settings, creating sections, and adding fields for your plugin.

Read more
4

Defining the Plugin Core Class

4 min
  • 5

    Understanding WordPress Hooks

    4 min
  • 6

    Implementing Custom Action Hooks

    4 min
  • 7

    Managing Hook Priorities

    3 min
  • 8

    Creating Admin Menus

    3 min
  • 9

    The Controller Layer for Admin Pages

    3 min
  • 10

    Registering Custom Post Types

    3 min
  • 11

    Configuring CPT Arguments

    3 min
  • 12

    Introduction to Taxonomies

    3 min
  • 13

    Designing Meta-Boxes

    3 min
  • 14

    Sanitizing User Input

    4 min
  • 15

    Saving Meta Data

    3 min
  • 16

    Database Basics with wpdb

    3 min
  • 17

    Secure CRUD Operations

    3 min
  • 18

    Querying with WP_Query

    3 min
  • 19

    Optimizing Queries

    3 min
  • 20

    The Model Layer for Data

    3 min
  • 21

    Enqueuing Scripts and Styles

    3 min
  • 22

    Plugin Template Hierarchy

    3 min
  • 23

    Creating Frontend Templates

    3 min
  • 24

    Building Shortcodes

    3 min
  • 25

    Advanced Shortcode Logic

    3 min
  • 26

    Introduction to Gutenberg Blocks

    3 min
  • 27

    The Settings API

    3 min
  • 28

    Validating Settings

    3 min
  • 29

    Implementing Nonces

    3 min
  • 30

    Capability Checks

    3 min
  • 31

    Handling Plugin Updates

    3 min
  • 32

    Internationalization (i18n)

    3 min
  • 33

    Debugging WordPress Plugins

    4 min
  • 34

    Unit Testing Foundations

    3 min
  • 35

    Handling AJAX Requests

    3 min
  • 36

    REST API Integration

    3 min
  • 37

    Advanced Database Queries

    3 min
  • 38

    Caching Strategies

    3 min
  • 39

    Plugin Security Best Practices

    4 min
  • 40

    Composer for Dependencies

    3 min
  • 41

    Theme Integration Hooks

    3 min
  • 42

    Managing Assets with Gulp/Webpack

    3 min
  • 43

    Documentation Standards

    3 min
  • 44

    Plugin Deployment Strategy

    Coming soon
  • 45

    Advanced MVC: Dependency Injection

    Coming soon
  • 46

    Handling Large Datasets

    Coming soon
  • 47

    Error Handling and Logging

    Coming soon
  • View full course