How to Add Custom Endpoints to WordPress API

Recently I worked on a project where we wanted to use AngularJS on the front end and WordPress as the backend. In order to exchange data between AngularJS and WordPress, we used the WordPress REST API. It was a good experience working with the REST API in WordPress. WordPress provides a very clean and efficient way to start using the REST API. This popular CMS also allows you to build the custom endpoint to send/receive data through it.

In this article, we study how to create a custom endpoint in the WordPress REST API. I am going to build the custom endpoint for the GET and POST request.

Use of WordPress REST API

Everybody knows about the popularity of mobile applications and JavaScript frameworks. While building a mobile application or website using the JavaScript framework you need to interact with the backend for the exchange of data.

One can choose any platform like WordPress, Laravel for backend purposes. The only requirement is you should have API endpoints on your backend platform to interchange data with the frontend. The frontend system gives an API call to the backend. On the backend, we should build a system that receives the API requests and processes it.

Mostly we used two types of requests in API endpoints – GET and POST. While we call API with GET request, API will give data from the database in response or delete the data in the database. In the case of POST requests, we either insert records in the database or check the data against the database. Of course, it’s not a thumb rule. The users can decide how it behaves depends on their requirements.

Authorization Using WordPress REST API

WordPress REST API requires you to follow Basic Auth flow. In the Basic Auth, you have to send a token in the Authorization header while sending an API request. Starting WordPress 5.6, a new feature ‘Application Passwords’ is introduced in the system. This application password(with username) can be used as a token in the Authorization header.

The Application Passwords is available to all users on sites served over SSL/HTTPS. If for some reason you are not using SSL on your website then you make it available using the below filter.

add_filter( 'wp_is_application_passwords_available', '__return_true' );

You will find the option for Application Passwords on the Users->Profile page. Generate the password by simply entering Application Name.

In the screenshot, you notice the spaces in the password. Application passwords can be used with or without the spaces. If included, spaces will just be stripped out before the password is hashed and verified on the WordPress end.

Now, you are ready with the password. Next, to create an Auth token you have to create a Base64 encoded version of your username and application password. Let’s say your username is ‘admin’ and password is ‘Ho9c 9vGs AOBG nXb0 FPpr W5vO’. Use the following statement which gives you a final valid token.

<?php
$username = 'admin';
$application_password = 'Ho9c 9vGs AOBG nXb0 FPpr W5vO';

echo base64_encode($username.':'.$application_password);

The above statement returns a token value as YWRtaW46SG85YyA5dkdzIEFPQkcgblhiMCBGUHByIFc1dk8=. This token you need to send in the Authorization header while calling WordPress REST API.

Login Using WordPress REST API

We are ready with the Basic Auth token value. Now, let’s build a custom endpoint for a login system. In the below code, we write an API endpoint that receives user credentials and checks if the details are correct or not. You need to add this code in your themes functions.php file.

add_action(
    'rest_api_init',
    function () {
        register_rest_route(
            'api',
            'login',
            array(
                'methods'  => 'POST',
                'callback' => 'login',
            )
        );
    }
);

WordPress provides an action ‘rest_api_init’ using which we can build our custom endpoints. Here I am using the register_rest_route function which produces the above API endpoint as YOUR_SITE_URL/wp-json/api/login.

In our code ‘api’ is the namespace, ‘login’ is the route, a method is ‘POST’ and the callback function is ‘login’. The callback method will have an actual logic.

In order to write a logic for login flow, the POST parameters required are email and password which should be sent from the frontend along with the Authorization header. While posting this data, you need to send it in JSON format. For instance, from the VSCode using Rest Client Extension I send the POST request as shown in the screenshot below.

Here we have passed the token created in the previous step as the Authorization header value.

Add the below code for the login() method in the functions.php file.

function login( WP_REST_Request $request ) {
    $arr_request = json_decode( $request->get_body() );

    if ( ! empty( $arr_request->email ) && ! empty( $arr_request->password ) ) {
        // this returns the user ID and other info from the user name.
        $user = get_user_by( 'email', $arr_request->email );

        if ( ! $user ) {
            // if the user name doesn't exist.
            return [
                'status' => 'error',
                'message' => 'Wrong email address.',
            ];
        }

        // check the user's login with their password.
        if ( ! wp_check_password( $arr_request->password, $user->user_pass, $user->ID ) ) {
            // if the password is incorrect for the specified user.
            return [
                'status' => 'error',
                'message' => 'Wrong password.',
            ];
        }

        return [
            'status' => 'success',
            'message' => 'User credentials are correct.',
        ];
    } else {
        return [
            'status' => 'error',
            'message' => 'Email and password are required.',
        ];
    }
}

Note: If you received an error like “No route was found matching the URL and request method”, you need to update your permalink.

Upon receiving the ‘success’ value for the ‘status’ key, you can log the user in the frontend application.

Build an Endpoint for GET Request

We have seen how to build custom endpoints for POST requests. Now, let’s look into the GET request using WordPress REST API. For this, I will write an API that deletes a user. From the frontend, you should pass the id of a user as a GET parameter.

add_action(
    'rest_api_init',
    function () {
        register_rest_route(
            'api',
            'delete_user/(?P<id>\d+)',
            array(
                'methods'  => 'GET',
                'callback' => 'delete_user',
            )
        );
    }
);

This code generates an API endpoint as YOUR_SITE_URL/wp-json/api/delete_user/id. To this endpoint, instead of id you should pass the actual id of a user.

The callback method delete_user will have the following code.

function delete_user( $data ) {
    // delete the user
    require_once(ABSPATH.'wp-admin/includes/user.php' );
    if ( wp_delete_user($data['id']) ) {
        return [
            'status' => 'success',
            'message' => 'User deleted successfully.',
        ];
    }

    return [
        'status' => 'error',
        'message' => 'It seems you passed the wrong user id.',
    ];
}

I hope you understand how to build a custom endpoint in WordPress REST API. Please share your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

1 thought on “How to Add Custom Endpoints to WordPress API

  1. In the companion YouTube video you require the editing of .htaccess by? adding “SetEnvIf Authorization “(.*)” HTTP_AUTHORIZATION=$1″, is this still required or was that for a previous version of WordPress?

Leave a Reply

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