You’re already providing a schema, the parameters in args
are their own schemas, but WordPress does not enforce this schema or perform sanitisation/validation by default.
You can make WordPress enforce it though by setting the validation and sanitisation callbacks to the following:
'sanitize_callback' => 'rest_sanitize_request_arg',
'validate_callback' => 'rest_validate_request_arg',
rest_validate_request_arg
will look up the parameter in the args and use that as the schema and pass it to rest_validate_value_from_schema
for validation. The format of each parameter in the args
section is also the format of the schema for that input because it is a schema.
For example, this is how WordPress defines validates and enforces the per_page
parameter in the args section of collection endpoints:
'per_page' => array(
'description' => __( 'Maximum number of items to be returned in result set.' ),
'type' => 'integer',
'default' => 10,
'minimum' => 1,
'maximum' => 100,
'sanitize_callback' => 'absint',
'validate_callback' => 'rest_validate_request_arg',
),
And here is how it does it internally:
function rest_validate_request_arg( $value, $request, $param ) {
$attributes = $request->get_attributes();
if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
return true;
}
$args = $attributes['args'][ $param ];
return rest_validate_value_from_schema( $value, $args, $param );
}
There is also a rest_sanitize_request_arg
for sanitisation, but this is used in fewer locations in core itself.
- https://developer.wordpress.org/reference/functions/rest_sanitize_request_arg/
- https://developer.wordpress.org/reference/functions/rest_validate_request_arg/
- https://github.com/WordPress/WordPress/blob/c7d3e267b8a7aebc28b23efa74b2971602852315/wp-includes/rest-api/endpoints/class-wp-rest-controller.php#L348