Friday, July 1, 2022
HomeWordPress Developmentphp - Validate and Sanitize WP REST API Request utilizing WP JSON...

php – Validate and Sanitize WP REST API Request utilizing WP JSON Schema?


The REST API schema is meant to offer info to purchasers concerning the form and construction of what they are going to obtain in a REST response, and the WordPress REST API capabilities are structured round this.

Usually, this schema will cowl all fields, and it is assumed that when you make a request to a REST endpoint, it would take the identical type as what the REST API gave you, afterall if you’re sending a POST request then you’re creating or updating an merchandise that follows the identical schema {that a} GET request would provide you with when requesting knowledge.

On this context, your query is unnecessary and isn’t a RESTful API.

For those who wished to offer customized parameters for requests, you are able to do so through register_rest_route, the canonical technique is to do that when calling register_rest_route with an args parameter as demonstrated within the REST API handbook:

<?php
add_action( 'rest_api_init', operate () {
  register_rest_route( 'myplugin/v1', '/creator/(?P<id>d+)', array(
    'strategies' => 'GET',
    'callback' => 'my_awesome_func',
    'args' => array(
      'id' => array(
        'validate_callback' => operate($param, $request, $key) {
          return is_numeric( $param );
        }
      ),
    ),
  ) );
} );

WordPress will try to validate this for you, and that is the closest factor you will discover to an “enter schema”. Afterall, arguments/inputs come from POST variables or GET variables, not JSON blobs, and a JSON blob itself could be an argument. So it would make sense to use a JSON schema to a particular argument when you wished to put in writing the code for that.

What About rest_validate_value_from_schema?

For those who made a request to an endpoint to fetch merchandise from my plugin, and I declare merchandise are integers, however my code returns "banana" then that is not legitimate, so that is WordPress’ mechanism for checking that.

These capabilities weren’t written for validating the request on the way in which in, they’re for validating the response on the way in which out.

You could possibly attempt to use this to validate issues on the way in which in, however this is able to be separate from what the REST API already does, and inferior to offering an args parameter.

You would wish to:

  • write out the schema for enter ( it could not be auto-discoverable by shopper libraries )
  • name this operate in your REST endpoints implementation with that schema
  • implement code to deal with the results of this
  • output error responses for every validation failure ( the REST API would have executed this for you when you had used args )
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments