Validation
Body Validation
Body Validation is useful for ensuring that data transmitted in API requests adheres to specific criteria. By validating the request body, you can maintain the integrity and security of your API and safeguard it against invalid or malicious data.
The Validation
tab, located at the topmost action in a route, enables you to validate JSON data within incoming API requests. If the body of the request fails to align with the specified validation schema, the request will be immediately terminated.
General structure
The schema is defined using JSON syntax, with each key corresponding to a JSON key in the request body.
Each value in the schema must be an object that includes, at a minimum, the type key, which can be one of the following: number, string, list, or object. Various keys are available for data validation, depending on the chosen type.
Numbers
To validate numerical values, use the number
data type. The required
key in the validation schema specifies whether a particular field is mandatory or optional and required
can be set for all data types:
{
"myNumericProp": {
"type": "number",
"required": true
}
}
Text
To validate text values, use the string
data type. You can specify additional validation rules, such as a regular expression pattern or minimum and maximum length constraints:
{
"myStringProp": {
"type": "string",
"required": true,
"regex": "^[a-zA-Z0-9]+$",
"minLength": 3,
"maxLength": 10
}
}
Object
To validate text values, use the object
data type. The objectValidation
key can then be used to further specify the expected schema for each nested property within the object:
{
"myObjectProp": {
"type": "object",
"objectValidation": {
"myNestedProp": {
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 50
}
}
}
}
List
To validate list values, use the list
data type. You can specify minimum and maximum length constraints, as well as validation rules for each item within the list:
{
"myListProp": {
"type": "list",
"minLength": 1,
"maxLength": 1,
"itemValidation": {
"type": "number"
}
}
}