Marinko Popovic
Marinko Popovic

Reputation: 21

WP REST API | RESTful URL parameters

I am creating a custom route using WP API this way:

 register_rest_route( 'service/v1', 'shopping', array(
        'methods'  => WP_REST_Server::READABLE,
        'callback' => 'my_awesome_function',
        ));

I am writing the following function:

function my_awesome_function($request_data) {
    $parameters = $request_data->get_params();
    if( !isset( $parameters['product'] ) || empty($parameters['product']) ){
        return array( 'error' => 'No product provided' );
    }else{
        $product = $parameters['product'];\

       return array( 'Product' => $product );

    }
}

This works perfectly fine using this structure www.example.com/wp-json/service/v1/shopping?product=perfume

However I want it to work in a RESTful way using the URL: www.example.com/wp-json/service/v1/shopping/perfume

Should I change the way I am registering the route or this is not possible and needs to be done through URL rewrite in .htaccess?

Upvotes: 2

Views: 5575

Answers (1)

felipelavinz
felipelavinz

Reputation: 549

You can use something like:

register_rest_route( 'service/v1', 'shopping/(?P<id>[\d]+)', array(
    'methods'  => WP_REST_Server::READABLE,
    'callback' => 'my_awesome_function',
));

The regex at the end of the path will capture a single or more digits and set it as an "id" parameter which you can then use to get the relevant product

You can use something like: (?P<slug>[a-zA-Z0-9-]+) to capture a "slug" with uppercase/lowercase letters, numbers and/or dashes

Upvotes: 1

Related Questions