{"id":16003030,"url":"https://github.com/iron-bound-designs/wp-rest-api-schema-validator","last_synced_at":"2025-03-17T15:32:39.280Z","repository":{"id":48430364,"uuid":"91221968","full_name":"iron-bound-designs/wp-rest-api-schema-validator","owner":"iron-bound-designs","description":"Validate WP REST API requests using a complete JSON Schema validator.","archived":false,"fork":false,"pushed_at":"2021-07-26T19:09:51.000Z","size":49,"stargazers_count":12,"open_issues_count":2,"forks_count":2,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-10-09T02:15:35.679Z","etag":null,"topics":["json-schema","wordpress","wp-rest-api"],"latest_commit_sha":null,"homepage":"https://timothybjacobs.com/2017/05/17/json-schema-and-the-wp-rest-api/","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/iron-bound-designs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-05-14T05:22:44.000Z","updated_at":"2024-07-23T21:08:25.000Z","dependencies_parsed_at":"2022-08-21T10:00:12.343Z","dependency_job_id":null,"html_url":"https://github.com/iron-bound-designs/wp-rest-api-schema-validator","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iron-bound-designs%2Fwp-rest-api-schema-validator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iron-bound-designs%2Fwp-rest-api-schema-validator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iron-bound-designs%2Fwp-rest-api-schema-validator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iron-bound-designs%2Fwp-rest-api-schema-validator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/iron-bound-designs","download_url":"https://codeload.github.com/iron-bound-designs/wp-rest-api-schema-validator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":221696284,"owners_count":16865394,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["json-schema","wordpress","wp-rest-api"],"created_at":"2024-10-08T10:05:53.105Z","updated_at":"2024-10-27T15:14:51.741Z","avatar_url":"https://github.com/iron-bound-designs.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# WP REST API Schema Validator\nValidate WP REST API requests using a complete JSON Schema validator.\n\nWordPress ships with a validator, `rest_validate_request_arg()`, that supports a limited subset of the JSON Schema spec. This library allows the full JSON Schema spec to be used when writing endpoint schemas with minimal configuration. \n\nThis library relies upon the [justinrainbow/json-schema](https://github.com/justinrainbow/json-schema) package to do the actual schema validation. This simply bridges the gap between the two.\n\n## Requirements\n- PHP 5.3+\n- WordPress 4.5+\n\n## Installation\n`composer require ironbound/wp-rest-api-schema-validator`\n\n## Usage\nInitialize a `Middleware` instance with your REST route `namespace` and an array of localized strings. This middleware should be initialized before the `rest_api_init` hook is fired. For example, `plugins_loaded`.\n\nAdditionally, schemas must be created with a `title` attribute on the top level. This title should be unique within the versioned namespace.\n\n```php\n$middleware = new \\IronBound\\WP_REST_API\\SchemaValidator\\Middleware( 'namespace/v1', [\n  'methodParamDescription' =\u003e __( 'HTTP method to get the schema for. If not provided, will use the base schema.', 'text-domain' ),\n  'schemaNotFound'         =\u003e __( 'Schema not found.', 'text-domain' ),\n] );\n$middleware-\u003einitialize();\n```\n\nThat's it!\n\n## Advanced\n\n### GET and DELETE Requests\n\nQuery parameters passed with GET or DELETE requests are validated against the `args` option that is passed when registering the route.\n\n### Technical Details\n \nOn `rest_api_init#100`, the middleware will iterate over the registered routes in the provided namespace. The default WordPress core validation and sanitization functions will be disabled. \n\nSchema validation will be performed on the `rest_dispatch_request#10` hook.\n\n`WP_Error` objects will be returned that match the format in `WP_REST_Request`. Mainly, an error code of `rest_missing_callback_param` or `rest_invalid_param`, a `400` response status code, and detailed error information in `data.params`. \n\nFor missing parameters, `data.params` will contain a list of the missing parameter names. For invalid parameters,\na map of parameter names to a specific validation error message.\n\n### Procedural Validation\nIn the vast majority of cases, validation should be configured using JSON Schema definitions. However, this is not always the case. For example, verifying that a username is not taken requires making calls to the database that would be impossible to replicate in the schema definition. In these cases, a `validate_callback` can still be provided and will be executed before JSON Schema validation takes place.\n\n```php\nreturn [\n    '$schema'    =\u003e 'http://json-schema.org/schema#',\n    'title'      =\u003e 'users',\n    'type'       =\u003e 'object',\n    'properties' =\u003e [\n        'username' =\u003e [\n            'description' =\u003e __( 'Login name for the user.', 'text-domain' ),\n            'type'        =\u003e 'string',\n            'context'     =\u003e [ 'view', 'edit', 'embed' ],\n            'arg_options' =\u003e [\n                'validate_callback' =\u003e function( $value ) {\n                    return ! username_exists( $value );\n                },\n            ],   \n        ],\n    ],\n];\n```\n\n### Variable Schemas\nIn most cases, the schema document should be the same for all HTTP methods on a given endpoint. In the rare case that a separate schema document is provided, a `schema` option can be provided to the route args for that HTTP method. The `title` for the separate schema document MUST be the same as the base schema.\n\n```php\nregister_rest_route( 'namespace/v1', 'route', [\n    [\n        'methods'  =\u003e 'GET',\n        'callback' =\u003e [ $this, 'get_item' ],\n        'args'     =\u003e $this-\u003eget_endpoint_args_for_item_schema( 'GET' ),\n    ],\n    [\n        'methods'  =\u003e 'POST',\n        'callback' =\u003e array( $this, 'create_item' ),\n         // See WP_REST_Controller::get_endpoint_args_for_item_schema() for reference.\n        'args'     =\u003e $this-\u003eget_endpoint_args_for_post_schema(),\n        'schema'   =\u003e [ $this, 'get_public_item_post_schema' ],\n    ],\n    [\n        'methods'  =\u003e 'PUT',\n        'callback' =\u003e [ $this, 'update_item' ],\n        'args'     =\u003e $this-\u003eget_endpoint_args_for_item_schema( 'PUT' ),\n    ],\n    'schema' =\u003e [ $this, 'get_public_item_schema' ],\n] );\n```\n\n### Reusing Schemas\nJSON Schema provides a mechanism to utilize a referenced Schema document for validation. This package allows you to accomplish this by using the `Middleware::get_url_for_schema( $title )` method.\n\nFor example, this Schema will validate the `card` property according to the Schema document with the title `card`.\n```php\n[\n    '$schema'    =\u003e 'http://json-schema.org/schema#',\n    'title'      =\u003e 'transaction',\n    'type'       =\u003e 'object',\n    'properties' =\u003e [\n        'card' =\u003e [\n            '$ref' =\u003e $middleware-\u003eget_url_for_schema( 'card' )   \n        ],\n    ],\n];\n```\n\nBut what if there is no `/cards` route? Or a more general schema is required? In this case, a shared schema can be used.\n```php\n$middleware-\u003eadd_shared_schema( [\n    '$schema'    =\u003e 'http://json-schema.org/schema#',\n    'title'      =\u003e 'card',\n    'type'       =\u003e 'object',\n    'properties' =\u003e [\n        'card_number' =\u003e [\n            'type'    =\u003e 'string',\n            'pattern' =\u003e '^[0-9]{11,19}$',\n        ],\n        'exp_year'  =\u003e [ 'type' =\u003e 'integer' ],\n        'exp_month' =\u003e [ \n            'type' =\u003e 'integer',\n            'minimum' =\u003e 1,\n            'maximum' =\u003e 12,\n         ],\n    ],\n] );\n```\n\n### Schema Routes\n\nAfter all routes have been registered, the middleware will register its own route.\n \n```\nnamespace/v1/schemas/(?P\u003ctitle\u003e[\\S+])\n``` \n\nThis route returns the plain schema document for the given title. To retrieve a schema for a given HTTP method, pass the desired upper-cased HTTP method to the `method` query param.\n\n```HTTP\nGET https://example.org/wp-json/namespace/v1/schemas/transaction?method=POST\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Firon-bound-designs%2Fwp-rest-api-schema-validator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Firon-bound-designs%2Fwp-rest-api-schema-validator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Firon-bound-designs%2Fwp-rest-api-schema-validator/lists"}