register_rest_route( string $route_namespace, string $route, array $args = array(), bool $override = false ): bool

Registers a REST API route.

Description

Note: Do not use before the ‘rest_api_init’ hook.

Parameters

$route_namespacestringrequired
The first URL segment after core prefix. Should be unique to your package/plugin.
$routestringrequired
The base URL for route you are adding.
$argsarrayoptional
Either an array of options for the endpoint, or an array of arrays for multiple methods.

Default:array()

$overridebooloptional
If the route already exists, should we override it? True overrides, false merges (with newer overriding if duplicate keys exist).

Default:false

Return

bool True on success, false on error.

Source

function register_rest_route( $route_namespace, $route, $args = array(), $override = false ) {
	if ( empty( $route_namespace ) ) {
		/*
		 * Non-namespaced routes are not allowed, with the exception of the main
		 * and namespace indexes. If you really need to register a
		 * non-namespaced route, call `WP_REST_Server::register_route` directly.
		 */
		_doing_it_wrong( 'register_rest_route', __( 'Routes must be namespaced with plugin or theme name and version.' ), '4.4.0' );
		return false;
	} elseif ( empty( $route ) ) {
		_doing_it_wrong( 'register_rest_route', __( 'Route must be specified.' ), '4.4.0' );
		return false;
	}

	$clean_namespace = trim( $route_namespace, '/' );

	if ( $clean_namespace !== $route_namespace ) {
		_doing_it_wrong( __FUNCTION__, __( 'Namespace must not start or end with a slash.' ), '5.4.2' );
	}

	if ( ! did_action( 'rest_api_init' ) ) {
		_doing_it_wrong(
			'register_rest_route',
			sprintf(
				/* translators: %s: rest_api_init */
				__( 'REST API routes must be registered on the %s action.' ),
				'<code>rest_api_init</code>'
			),
			'5.1.0'
		);
	}

	if ( isset( $args['args'] ) ) {
		$common_args = $args['args'];
		unset( $args['args'] );
	} else {
		$common_args = array();
	}

	if ( isset( $args['callback'] ) ) {
		// Upgrade a single set to multiple.
		$args = array( $args );
	}

	$defaults = array(
		'methods'  => 'GET',
		'callback' => null,
		'args'     => array(),
	);

	foreach ( $args as $key => &$arg_group ) {
		if ( ! is_numeric( $key ) ) {
			// Route option, skip here.
			continue;
		}

		$arg_group         = array_merge( $defaults, $arg_group );
		$arg_group['args'] = array_merge( $common_args, $arg_group['args'] );

		if ( ! isset( $arg_group['permission_callback'] ) ) {
			_doing_it_wrong(
				__FUNCTION__,
				sprintf(
					/* translators: 1: The REST API route being registered, 2: The argument name, 3: The suggested function name. */
					__( 'The REST API route definition for %1$s is missing the required %2$s argument. For REST API routes that are intended to be public, use %3$s as the permission callback.' ),
					'<code>' . $clean_namespace . '/' . trim( $route, '/' ) . '</code>',
					'<code>permission_callback</code>',
					'<code>__return_true</code>'
				),
				'5.5.0'
			);
		}

		foreach ( $arg_group['args'] as $arg ) {
			if ( ! is_array( $arg ) ) {
				_doing_it_wrong(
					__FUNCTION__,
					sprintf(
						/* translators: 1: $args, 2: The REST API route being registered. */
						__( 'REST API %1$s should be an array of arrays. Non-array value detected for %2$s.' ),
						'<code>$args</code>',
						'<code>' . $clean_namespace . '/' . trim( $route, '/' ) . '</code>'
					),
					'6.1.0'
				);
				break; // Leave the foreach loop once a non-array argument was found.
			}
		}
	}

	$full_route = '/' . $clean_namespace . '/' . trim( $route, '/' );
	rest_get_server()->register_route( $clean_namespace, $full_route, $args, $override );
	return true;
}

Changelog

VersionDescription
5.5.0Added a _doing_it_wrong() notice when the required permission_callback argument is not set.
5.1.0Added a _doing_it_wrong() notice when not called on or after the rest_api_init hook.
4.4.0Introduced.

User Contributed Notes

  1. Skip to note 9 content

    Since WP 5.5.0 there is a notice if your registration of REST API route is not including the `permission_callback`. You may get some notice in debug.log like the following one:

    PHP Notice: register_rest_route was called incorrectly. The REST API route definition for /foo is missing the required permission_callback argument. For REST API routes that are intended to be public, use __return_true as the permission callback.

    To solve this problem you will need to add the `permission_callback` in arguments like the example from the “Routes and Endpoints Handbook”: https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/#permissions-callback

  2. Skip to note 10 content

    Args is a named array that usually includes the keys ‘methods’ and ‘callback’.

    ‘method’ defines which HTTP methods are to be processed by the function defined by ‘callback’.

    ‘method’ can be a string of comma-separated HTTP methods or an array of strings of HTTP methods.

    A common practice is to use the WP_REST_Server constants to set the ‘method’.

    WP_REST_Server::READABLE = ‘GET’

    WP_REST_Server::EDITABLE = ‘POST, PUT, PATCH’

    WP_REST_Server::DELETABLE = ‘DELETE’

    WP_REST_Server::ALLMETHODS = ‘GET, POST, PUT, PATCH, DELETE’

    Example


    // Get a list of locations.
    // Method GET via wp-json/store-locator-plus//locations/
    //
    // Calls the get_locations method of the current class when the route is matched.
    //
    register_rest_route( 'my-plugin-slug/v2' , '/locations/', array(
    'methods' => 'GET',
    'callback' => array(
    $this,
    'get_locations'
    )
    ) );

  3. Skip to note 11 content
    //The Following registers an api route with multiple parameters. 
    add_action( 'rest_api_init', 'add_custom_users_api');
    
    
    function add_custom_users_api(){ register_rest_route( 'mmw/v1', '/users/market=(?P<market>[a-zA-Z0-9-]+)/lat=(?P<lat>[a-z0-9 .\-]+)/long=(?P<long>[a-z0-9 .\-]+)', array( 'methods' => 'GET', 'callback' => 'get_custom_users_data', )); }

    Make sure that your regex expressions are fine. If the data does not match then the URL will return a 404.
    Some examples are:

    (?P[a-zA-Z0-9-]+) for slug (you can change slug for your custom name)
    (?P\d+) for id
    (?P[a-z0-9 .\-]+) for longitude or latitude

    //Customize the callback to your liking
    function get_custom_users_data($data){
        //get users by market
        $users = mmw_get_custom_users();
        foreach ($users as $key => $user) {
            $market = $user['Market'];
            $long = $user['long'];
            $lat = $user['lat'];
    
            if( intval($market) === intval(trim($data['market'])) ){
                $result[] = array(
                    'user_login' => $user->user_login,
                    'avatar_url' => get_avatar_url($user->ID),
                    'lat' => $lat,
                    'long' => $long
                );
            }
        }
        return $result;
    }

    Edited to remove an extra ) in one of the regexes. – DevHub Team

  4. Skip to note 12 content

    In case you are a friend of type hinting and are wondering what is being passed to your callback method, it’s a WP_REST_Request object. It might help you with autocompletion and discovering other methods provided.

    public function wpdocs_get_lineitems( WP_REST_Request $data ) {
    	$params = $data->get_url_params();
    	// etc.
    }
  5. Skip to note 13 content

    Args , the named array cited above, can also contain an optional ‘args’ array of its own.

    The second args array contains the default arguments, required arguments, validation callback, and sanitization callback that are in place for each argument passed in with the REST request. The key name of this array is the name of the parameter being passed.

    See http://v2.wp-api.org/extending/adding/ under the “Arguments” section for more information and examples.

    Example

    <?php
    add_action( 'rest_api_init', function () {
    register_rest_route( 'myplugin/v1', '/author/(?P\d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
    'args' => array(
    'id' => array(
    'validate_callback' => function($param, $request, $key) {
    return is_numeric( $param );
    }
    ),
    ),
    ) );
    } );

  6. Skip to note 14 content

    1. You can not use / (slash) at the beginning or end of the namespace, for example: plugin_name/api/.
    2. permission_callback is required argument of register_rest_route.

    function plugin_name_create_route() {
            add_action( 'rest_api_init', function() {
                register_rest_route( 'plugin_name/api', '/token/', array(
                    'methods' => 'POST',
                    'callback' =>  'plugin_name_route_api',
                    ‘permission_callback' => function() { return ''; }
                ) );
            } );
     }

    1. Callback takes the request object as a parameter.
    2. You can set the response headers with WP_Error class.

    function plugin_name_route_api( \WP_REST_Request $req ) {
    	$token = get_option('bearer_token');
    	$headers = $req->get_headers();
    	$auth_token = $headers['authorization'][0];
    
    	if ( $token != $auth_token ) {
    		return new WP_Error( '401', esc_html__( 'Not Authorized', 'text_domain' ), array( 'status' => 401 ) );
    	}
    
    	return json_encode(["message" => "Authorized"]);
    }
  7. Skip to note 15 content

    for the non-namespaced routing, call WP_REST_Server::register_route directly.
    Example

    add_action( 'rest_api_init', function ( $server ) {
    	$server->register_route( 'foo', '/foo', array(
    		'methods'  => 'GET',
    		'callback' => function () {
    			return 'baz';
    		},
    	) );
    } );

    will register foo endpoint without namespace. You can access http://example.com/wp-json/foo
    As a reminder, please ensure before registering non-namespaced routes. They can be useful for backward compatibility only.

You must log in before being able to contribute a note or feedback.