Generate JSON Schema for REST API Request Bodies
Generate a complete JSON Schema for a REST API request body from a sample payload. Includes nested objects, arrays, enums, and required field validation.
Detailed Explanation
Building API Request Schemas from Sample Data
One of the most practical uses of JSON Schema generation is creating validation schemas for REST API request bodies. Instead of writing schemas from scratch, you paste a sample payload and refine the output.
Sample API Request
Consider a typical e-commerce order creation endpoint:
{
"customerId": "cust_abc123",
"items": [
{
"productId": "prod_001",
"quantity": 2,
"price": 29.99
}
],
"shipping": {
"method": "express",
"address": {
"street": "123 Main St",
"city": "Portland",
"state": "OR",
"zip": "97201"
}
},
"couponCode": null
}
Generated Schema (After Refinement)
The initial generation gives you the structure. After refinement you might have:
{
"type": "object",
"properties": {
"customerId": { "type": "string", "pattern": "^cust_[a-z0-9]+$" },
"items": {
"type": "array",
"items": { ... },
"minItems": 1
},
"shipping": { "type": "object", "properties": { ... } },
"couponCode": { "type": ["string", "null"] }
},
"required": ["customerId", "items", "shipping"],
"additionalProperties": false
}
Post-Generation Refinement Steps
- Add
additionalProperties: falseto reject unexpected fields. - Review
required:couponCodeshould be optional since it is nullable. - Add constraints:
minItems: 1for the items array (empty orders make no sense),minimum: 0for price and quantity. - Add
enumforshipping.method:["standard", "express", "overnight"]. - Add
patternfor ID fields to enforce your naming convention.
Integrating with API Frameworks
Once your schema is ready, you can plug it directly into:
- Express.js: Use Ajv middleware to validate incoming request bodies.
- FastAPI: Convert to Pydantic models for automatic validation.
- OpenAPI/Swagger: Embed the schema in your API specification for documentation and client code generation.
The generate-then-refine workflow is significantly faster than writing schemas by hand, especially for large payloads with nested objects and arrays.
Use Case
Generate schemas for REST API request validation, whether for order creation, user registration, search queries, or any POST/PUT endpoint that accepts structured JSON bodies.