Implementing Request Validation
1. Validating Request Headers
| Check | Example |
|---|---|
| Required present | Authorization missing → 401 |
| Format regex | X-Request-ID = UUID |
| Allowed values | Accept: application/json |
| Max length | Header > 8KB → 431 |
2. Validating Request Body Schema
Example: JSON schema validation
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["email", "age"],
"properties": {
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 0, "maximum": 150 }
},
"additionalProperties": false
}
3. Using OpenAPI Validation
| Tool | Use |
|---|---|
Kong oas-validation | Spec-driven validation |
Envoy json_to_metadata | Body extraction |
| AWS APIGW model | Request validators |
| Spectral lint | CI-time spec quality |
4. Validating Query Parameters
Example: Query validator
parameters:
- name: page
in: query
schema: { type: integer, minimum: 1, maximum: 1000, default: 1 }
- name: sort
in: query
schema: { type: string, enum: [asc, desc] }
5. Validating Path Parameters
| Param | Rule |
|---|---|
:id | UUID v4 regex |
:slug | ^[a-z0-9-]{1,64}$ |
:year | 1900–2100 integer |
:locale | BCP-47 (en-US) |
6. Implementing Content-Type Validation
| Endpoint | Allowed Content-Type |
|---|---|
| JSON API | application/json |
| Upload | multipart/form-data |
| Form POST | application/x-www-form-urlencoded |
| gRPC | application/grpc |
7. Setting Request Size Validation
| Endpoint Type | Recommended Max |
|---|---|
| JSON API | 256KB - 1MB |
| File upload | 50MB - 5GB |
| GraphQL query | 16KB |
| Webhook | 1MB |
8. Using Custom Validation Rules
Example: Custom Lua validator (Kong)
local body, err = kong.request.get_body()
if not body or not body.amount or body.amount <= 0 then
return kong.response.exit(400, {
error = "amount must be positive",
code = "INVALID_AMOUNT"
})
end
9. Setting Up Sanitization Rules
| Attack | Sanitization |
|---|---|
| SQL injection | Reject ;--, parametrize at app |
| XSS | Strip <script>, encode output |
| Path traversal | Block ../ in path |
| Header injection | Reject \r\n in headers |
| LDAP injection | Escape (), *, \ |
10. Configuring Validation Error Responses
Example: RFC 7807 Problem Details
{
"type": "https://api.example.com/errors/validation",
"title": "Validation Failed",
"status": 400,
"detail": "Request body failed schema validation",
"instance": "/v1/users",
"errors": [
{ "field": "email", "code": "invalid_format" },
{ "field": "age", "code": "out_of_range" }
]
}