JSON Body Validation Policy
This policy is deprecated
Use the new Request Validation Policy. The new policy validates JSON bodies like this policy, but also supports validation of parameters, query strings, etc.
The Validate JSON Schema policy is used to validate the body of incoming
requests. It works using JSON Schemas defined in the Schemas
folder of your
project.
When configured, any requests that do not have a body conforming to your JSON
schema will be rejected with a 400: Bad Request
response containing a detailed
error message (in JSON) explaining why the body was not accepted.
Configuration
The configuration shows how to configure the policy in the 'policies.json' document.
Policy Options
The options for this policy are specified below. All properties are optional unless specifically marked as required.
validator
<string> (Required) -The JSON schema to validate against.
Using the Policy
Here's a simple, example JSON Schema
Note - "title" is a required property of JSON schema
This defines a body that should be of type object with required string
properties make
and model
. It also defines two optional properties
maxSpeed
and color
. The former must be an integer greater than or equal to
zero and color
can (in this silly example) can be one of "black", "brown",
"red", "silver" or "blue". No other properties can be on this object.
The schemas file should live in the schemas
folder of your project - for the
purposes of this example let's imagine it is called car.json
.
Create Project
This sample is available on on GitHub or click the button below to open the code directly in the portal.
Configuration#
Here is an example configuration (this would go in policies.json
).
name
the name of your policy instance, this is used to refer to your policy from your routes, see below.policyType
the identifier of the policy. This is used by the Zuplo UI. Value should bevalidate-json-schema-inbound
.handler/export
The name of the exported type. Value should beValidateJsonSchemaInboundPolicy
.handler/module
the module containing the policy. Value should be@zuplo/runtime
.handler/options
The options for this policy:validator
a '$import' reference to the schema - e.g.$import(./schemas/car.json)
This policy is then referenced from each route where you want the policy to be enforced, for example:
You can test this in the API Test Console with the following (correct) body
Errors#
Missing fields#
If the request body is missing a required field, an error similar to the following will be returned.
Invalid Field Type#
If the request body contains a field that is not of the correct type, an error similar to the following will be returned.
Read more about how policies work