Build a custom REST endpoint which greets a name
Description: Create the endpoint GET /wp-json/tc/v1/greet?name=Riya, which returns {"greeting":"Hello, Riya!"}. If the name has more than 20 characters, the endpoint must return an error with the status 400.
Hint:
- Use
register_rest_route()with avalidate_callbackfor thenameargument. - A route needs a
permission_callback.
Solution
<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'tc/v1', '/greet', array(
'methods' => 'GET',
'permission_callback' => '__return_true',
'args' => array(
'name' => array(
'required' => true,
'validate_callback' => function ( $value ) {
return is_string( $value ) && strlen( $value ) <= 20;
},
'sanitize_callback' => 'sanitize_text_field',
),
),
'callback' => function ( WP_REST_Request $request ) {
return array( 'greeting' => 'Hello, ' . $request['name'] . '!' );
},
) );
} );
Terminal output
$ curl -s "http://example.com/wp-json/tc/v1/greet?name=Riya"
{"greeting":"Hello, Riya!"}
$ curl -s "http://example.com/wp-json/tc/v1/greet?name=ThisNameIsMuchTooLongForUs" | jq -c '{code, status: .data.status}'
{"code":"rest_invalid_param","status":400}
$ curl -s "http://example.com/wp-json/tc/v1/greet" | jq -c '{code, message}'
{"code":"rest_missing_callback_param","message":"Missing parameter(s): name"}
How it works
- The route is on the
rest_api_inithook. WordPress checks the arguments before the callback runs. - A failed
validate_callbackgivesrest_invalid_paramwith the status 400, and a missing required argument gives an error too.
Read Custom REST Endpoint.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |