I'm currently setting up my first WP REST API and am attempting to understand how WP implements JSON Schema for the API endpoints, and the docs are imho really poor and confusing; so I wanted to make sure that I understand things properly:
According to this, you can specify the 'schema' parameter within the $args argument when registering a new rest route, to provide a JSON schema informing about the structure of the response of your endpoint. That schema should be delivered to any client making an
OPTIONS
HTTP request to the according endpoint. That works.You can then specify any combination of the WP JSON Schema parameters for every parameter of your
$args
array when usingregister_rest_route
, to inform about the required format of the request's arguments, for that respective endpoint. When I add for example adescription
key to the argument X of the endpoint Y, and then inspect the generalhttps://example.org/wp-json/
REST schema of the website viaGET
, thatdescription
indeed shows up under the argument X of my API endpoint Y. So that also works.What I totally don't understand is, how can I use the JSON schema I've specified in 2) for validation and subsequent (if validation is passed) sanitization? The docs mention the built-in
rest_validate_value_from_schema
andrest_validate_value_from_schema
functions, but do not really show any examples / explain how you implement your JSON schemas provided for the request data (step 2)) for validation / sanitization.
How is that actually done using WP's built-in JSON schema ?
rest_validate_value_from_schema
andrest_validate_value_from_schema
functions. To these, you can actually indeed provide a WP JSON Schema (as PHP array, as for theschema
parameter when registering a route), and the two callbacks then use that to execute the validation and sanitization as built-in by wordpess. Think I figured it out; will post the resulting code in a while.