Reading list Switch to dark mode

    How to Add Custom REST API Route in WordPress?

    Updated 1 November 2023

    WordPress provides us with the ability to create Custom WordPress REST API Route and endpoints.

    You can use the Rewrites API, as well as the query classes: WP_Query, WP_User, etc) for creating your URL mappings, or custom queries.

    This blog describes – how we can add custom REST API routes in WordPress. The use of API is very common nowadays.

    So, when we work with API we need some custom routes along with default ones so that we can facilitate intended tasks.

    When we add our custom routes, we must not affect the default ones. We should add new routes with default ones, not in place of default routes.

    Searching for an experienced
    Woocommerce Company ?
    Find out More

    Registering a Custom Rest Route

    We can register a custom Rest API route through the function register_rest_route.

    The  register_rest_route function takes three arguments: the namespace, the route we want, and the options.

    This function is added as a callback function to action rest_api_init. Let webkul/v1 be our namespace.

    We will explain this in detail in the namespaces later in the blog. Our registered route will match anything /webkulposts/{id}, where {id} is an integer.

    Example-

    We use the rest_api_init hook which fires when preparing to serve an API request.

    add_action( 'rest_api_init', 'wk_register_custom_routes' );
    

    Now, we register our route in the callback function of the above action using the function register_rest_route –

    function wk_register_custom_routes() {
    	register_rest_route(
    		'webkul/v1',
    		'/webkulposts/{id}',
    		array(
    			array(
    				'methods'  => 'GET',
    				'callback' => 'wk_get_post_callback',
    			),
    			array(
    				'methods'  => 'PUT',
    				'callback' => 'wk_put_post_callback',
    			),
    			array(
    				'methods'  => 'DELETE,
    				'callback' => 'wk_delete_post_callback',
    			),
    		)
    	);
    }
    
    public funcion wk_put_post_callback($request)
    {
      // Your code 
    }
    
    public funcion wk_delete_post_callback($request )
    {
      // Your code 
    }

    Here we have registered the three endpoints for the route.

    The “route” refers to the URL, whereas the “endpoint” refers to the function behind it that corresponds to a method.

    Endpoints are nothing but the functions that can be accessed via the APIs. Endpoints take some number of parameters and return the requested data.

    The URL “name” you use to access endpoints, is called a route. A route can have multiple endpoints associated with it, which is used depending on the HTTP verb.

    For example, with the URL `http://webkul.com/wp-json/webkul/v1/webkulposts/23`:

    • The “route” is webkul/v1/webkulposts/23
    • This route has 3 endpoints:
      • GET triggers a wk_get_post_callback  method, returning the post data to the client.
      • PUT triggers an wk_update_post_callback method, taking the data to update, and returning the updated post data.
      • DELETE triggers a wk_delete_post_callback method, returning the now-deleted post data to the client.

    There may be any number of endpoints for each registered route, and for each endpoint, you can define the allowed HTTP methods.

    For each endpoint, you need to define a callback function for responding to the request and a permissions callback for creating custom permissions.

    You can also define allowed fields in the request and for each field specify a default value, a sanitization callback, a validation callback, and whether the field is required.

    Components of Registered Route

    Namespaces

    Namespaces serve as the initial component of the endpoint URL and are crucial for preventing conflicts between custom routes.

    By employing namespaces, conflicts can be avoided when two plugins attempt to add a route with the same name but offer distinct functionalities.

    In general, for namespaces, you should adopt the pattern of plugin_name/v1.

    Here the plugin_name typically corresponds to your WooCommerce plugin or theme slug, while v1 denotes the initial version of the API.

    In the route registered in the previous section – webkul/v1 is our namespace.

    Arguments

    In the key args for each endpoint in WordPress, the arguments are defined as a map.

    The map uses the argument name as the key, with the value being a map of options for that argument.

    This options map can include keys such as default, required, sanitize_callback, and validate_callback.

    The default key is used to set a default value for the argument if none is supplied.

    If the argument is not provided and no default value is set, the argument will be empty.

    The required key, when set to true, ensures that the argument is mandatory. If no value is passed for a required argument, an error will be returned.

    However, if a default value is set, the argument will always have a value and the required setting will have no effect.

    The validate_callback key allows you to specify a function that will receive the value of the argument.

    This function should return true if the value is considered valid and false otherwise. It provides a way to validate the input data before further processing.

    The sanitize_callback key allows you to specify a function that will sanitize the value of the argument before passing it to the main callback.

    Sanitization helps to ensure that the input is safe and conforms to the expected format or type.

    By utilising the sanitize_callback and validate_callback options,

    the main callback function can focus solely on processing the request and preparing the data to be returned, using the WP_REST_Response class.

    These callbacks provide a reliable way to validate and sanitize the input, allowing you to work with trustworthy and secure data during the processing phase.

    Let’s add an argument to our previously registered route which checks if the value supplied for id is numeric or not.

    function wk_register_custom_routes() {
    	register_rest_route(
    		'webkul/v1',
    		'/webkulposts/{id}',
    		array(
    			array(
    				'methods'  => 'GET',
    				'callback' => 'wk_get_post_callback',
    				'args'     => array(
    					'id' => array(
    						'validate_callback' =>     function( $param, $request, $key ) {
    							return is_numeric( $param );
    						},
    					),
    				),
    			),
    			array(
    				'methods'  => 'PUT',
    				'callback' => 'wk_put_post_callback',
    			),
    			array(
    				'methods'  => 'DELETE',
    				'callback' => 'wk_delete_post_callback',
    			),
    		)
    	);
    }

    Permission Callback

    When working with endpoints in WordPress, it is important to register a permissions callback.

    This function will check if the user has the necessary permissions to perform the desired action (such as reading or updating) before the actual callback is executed.

    To register the permissions callback, you can use the permission_callback option alongside the callback option within the endpoint configuration.

    This callback should return either a boolean value or an instance of WP_Error. If the function returns true, the response will be processed.

    A default error message will be returned if it returns false, and the request will not proceed with further processing.

    In the case of an WP_Error instance, that specific error will be returned to the client.

    It’s important to note that the permissions callback is executed after remote authentication, which sets the current user.

    This means you can utilize current_user_can the function to check if the authenticated user possesses the necessary capability for the action.

    Once you have registered a permission_callback , it becomes necessary to authenticate your requests.

    It can by done by including a nonce parameter or using other authentication methods.

    Failure to authenticate your requests will result in a rest_forbidden error. For more detailed authentication information, refer to the relevant documentation.

    Let’s add a permission callback to our previously registered route.

     register_rest_route( '<span style="background-color: initial;font-family: inherit;font-size: inherit;color: initial">webkul/v1', '</span><span style="font-family: inherit;font-size: inherit;color: initial">/webkulposts/{id}</span>', array(
           'methods'  => 'GET',
           'callback' => 'wk_get_post_callback',
            'args' => array(
            'id' => array(
            'validate_callback' => function($param, $request, $key) {
                    return is_numeric( $param );
                    }
              ),
             'permission_callback' => function () {
                    return current_user_can( 'edit_others_posts' );
             }
           ),
        }
       )  );

    In case you intend to keep your REST API endpoint public, you can use  __return_true as the permission callback.

    Return Value

    Once the callback function executes, and then it sends the resulting value back to the client after undergoing JSON conversion.

    This enables the ability to return a wide range of data types.

    In the aforementioned example, we return either a string or null, and the API automatically handles the conversion to JSON.

    Similar to any other WordPress function, it is also possible to return a WP_Error instance.

    For more info – Adding Custom Endpoints

    Support

    That’s All with this blog. Still have any issues? Feel free to contact us at [email protected] Thanks for Your Time! Have a Good Day!

    . . .

    Leave a Comment

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


    1 comments

  • Julius Swetnam
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home