Thursday, 16 February 2017

The WordPress REST API’s Undocumented Validation Options – Shawn Hooper – WordPress Developer & Speaker


The WordPress REST API is still very new. As with many early early technologies, documentation seems to be the last thing to get updated. This is why it can be fun/educational to read through the source code in open source projects. You’ll find things the documentation didn’t teach you! (Or at least not in any documentation I could easily find.) The custom endpoint I was creating required quite a few arguments when called. I wanted to include sanitization and/or validation of these arguments. Setting up a schema for the endpoint made sense. I knew I could perform validation by specifying a ‘validate_callback’ function in the argument definition.
However browsing the source code in WordPress’ core revealed a few bonuses built right into the core, in a function called rest_validate_value_from_schema.
The ‘type’ attribute
By including in a ‘type‘ attribute when defining an argument, the REST API’s validation will automatically check if the value passed into this argument is of the appropriate data type.
register_rest_route( ‘route/v1’, ‘/endpoint/’, array(
‘methods’ => ‘POST’,
‘callback’ => array( $this, ‘endpoint_post_handler’
Source: https://managewp.org/articles/14408/the-wordpress-rest-api-s-undocumented-validation-options-shawn-hooper-wordpress-developer-speaker




source https://williechiu40.wordpress.com/2017/02/17/the-wordpress-rest-apis-undocumented-validation-options-shawn-hooper-wordpress-developer-speaker/

No comments:

Post a Comment