Schema & Validation

Stop bad input at the door with args, type and enum, and avoid the sanitize_callback trap.

4 lessons16 interview questions

Sanitized is not validated. Add absint as a sanitize_callback and post_id=abc quietly becomes 0 โ€” the request passes. In this module you learn what core checks for you, and the one place where it stops.

CourseWordPress REST API Course ยท Module 5 of 9 ยท Stage 2 "Build your own"
Learnargs, required, type, enum, validate_callback, sanitize_callback, rest_validate_request_arg, get_item_schema
HowReal args from 4WP Weather, SEO Helper and FAQ, core behaviour checked in class-wp-rest-request.php, interview questions after every lesson

What runs before your callback

flowchart LR
  I["Request"] --> RQ["required?<br/>400 rest_missing_callback_param"]
  RQ --> T["type / enum<br/>400 rest_invalid_param"]
  T --> S["sanitize_callback"]
  S --> CB["your callback"]
  classDef err fill:#feebeb,stroke:#f93e3e,color:#1e293b
  classDef ok fill:#e8f6f0,stroke:#49cc90,color:#1e293b
  class RQ,T err
  class CB ok

Your args also appear in /wp-json/{namespace}, so validation doubles as documentation.

Before โ†’ after

BeforeAfter Module 5
$request['id'] checked by hand in every callbackargs with required, type, enum
sanitize_callback => absint, abc becomes 0validate_callback => rest_validate_request_arg next to it
API docs in a README nobody updatesargs and schema in the route index
500 on bad input400 with a real core error code

You'll be able to answer

  • What happens when a REST arg has a type and a custom sanitize_callback?
  • What is the difference between validate_callback and sanitize_callback?
  • How does a schema make a WordPress endpoint self-documenting?

Lessons in this module 4 lessons