OpenAPI Request and Response Schemas
Master OpenAPI schema definitions for request bodies and responses. Learn about type constraints, required fields, nested objects, arrays, enums, and $ref references for reusable schemas.
Detailed Explanation
Request and Response Schemas in OpenAPI
Schemas are the heart of an OpenAPI specification. They define the exact shape of data that your API accepts and returns, serving as both documentation and a contract between client and server.
Basic Schema Types
OpenAPI supports these primitive types:
# String
name:
type: string
minLength: 1
maxLength: 200
# Integer
age:
type: integer
minimum: 0
maximum: 150
# Number (float)
price:
type: number
format: double
# Boolean
active:
type: boolean
# Enum
status:
type: string
enum: [draft, published, archived]
Object Schemas
Objects combine multiple fields with optional required constraints:
User:
type: object
required:
- email
- name
properties:
id:
type: string
format: uuid
readOnly: true
email:
type: string
format: email
name:
type: string
bio:
type: string
nullable: true
Array Schemas
Arrays wrap another schema type:
Tags:
type: array
items:
type: string
minItems: 1
maxItems: 10
uniqueItems: true
Nested Objects
Schemas can nest arbitrarily deep:
Order:
type: object
properties:
items:
type: array
items:
type: object
properties:
product_id:
type: string
quantity:
type: integer
price:
type: number
Schema Reuse with $ref
The $ref keyword prevents duplication:
paths:
/users:
post:
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/CreateUser"
responses:
"201":
content:
application/json:
schema:
$ref: "#/components/schemas/User"
Composition with allOf, oneOf, anyOf
Combine schemas for polymorphism:
# Inheritance
AdminUser:
allOf:
- $ref: "#/components/schemas/User"
- type: object
properties:
permissions:
type: array
items:
type: string
Using allOf for schema inheritance, oneOf for exclusive variants, and anyOf for flexible unions gives you powerful type composition.
Use Case
Well-defined schemas are critical for API contract testing, client code generation, and documentation accuracy. Teams using OpenAPI for design-first development rely on precise schema definitions to generate SDKs in multiple languages, validate requests and responses in middleware, and produce accurate interactive documentation.