Schemas in OpenAPI — Data Models with JSON Schema
In this tutorial, you will learn about Schemas in OpenAPI. We cover key concepts, practical examples, and best practices to help you master this topic.
OpenAPI schemas define the structure of data exchanged by your API using JSON Schema, supporting all primitive types, complex nested objects, arrays, enums, and composition patterns.
In this tutorial, you will learn how to create comprehensive schema definitions with proper validation, documentation, and reusability.
What You'll Learn
You will learn JSON Schema basics within OpenAPI, how to define properties with validation, nested objects, arrays, enums, oneOf/anyOf composition, and best practices.
flowchart LR A[Schemas] --> B[Primitives] A --> C[Objects] A --> D[Arrays] A --> E[Composition] B:::current classDef current fill:#f90,color:#fff,stroke:#333,stroke-width:2px
Primitive Types and Formats
components:
schemas:
PrimitiveTypes:
type: object
properties:
name:
type: string
age:
type: integer
height:
type: number
isActive:
type: boolean
email:
type: string
format: email
website:
type: string
format: uri
uuid:
type: string
format: uuid
createdAt:
type: string
format: date-time
Validation Constraints
ValidationExample:
type: object
properties:
username:
type: string
minLength: 3
maxLength: 50
pattern: "^[a-zA-Z0-9_]+$"
age:
type: integer
minimum: 0
maximum: 150
score:
type: number
multipleOf: 0.5
status:
type: string
enum: [active, inactive, suspended]
required:
- username
- email
Composition Patterns
PaymentMethod:
oneOf:
- $ref: "#/components/schemas/CreditCard"
- $ref: "#/components/schemas/PayPal"
discriminator:
propertyName: type
Common Mistakes
- Missing required fields — Defining properties without marking which are required.
- No examples — Omitting the example field on properties.
- Deep nesting — Objects nested 5+ levels. Flatten where possible.
- Overly permissive schemas — Using type: string without format for structured data.
Practice Questions
- What JSON Schema types are supported?
- How do you define string formats?
- What is the difference between oneOf and anyOf?
- How do you make properties required?
- What validation constraints apply to numeric fields?
Challenge
Design a complete schema set for a hotel booking API: Hotel, Room, Guest, Booking, Payment, Review, and SearchResult. Include appropriate types, formats, constraints, and composition.
What's Next
In the next lesson, you will learn the components object for reusable definitions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro