OpenAPI Structure and Syntax — Complete Guide
In this tutorial, you will learn about OpenAPI Structure and Syntax. We cover key concepts, practical examples, and best practices to help you master this topic.
OpenAPI 3.1 structure organizes API descriptions into a hierarchy of info, servers, paths, operations, parameters, request bodies, responses, and components that together form a complete machine-readable contract for your REST API.
What You'll Learn
The complete OpenAPI 3.1 object hierarchy, how to write each section with correct syntax, how to use $ref for reusable components, how to define parameters and schemas with JSON Schema, and how to organize large specs with tags.
Why It Matters
A well-structured OpenAPI spec is readable by humans and machines. It generates accurate interactive documentation, produces correct client SDKs, and serves as a validation contract. A poorly structured spec causes tooling errors, missing docs, and developer confusion.
Real-World Use
The DodaTech API spec has grown to over 3,000 lines across 50+ endpoints. By using reusable components, tags for grouping, and consistent parameter patterns, the team maintains the spec alongside the codebase. CI validates every Pull Request against the spec.
OpenAPI Object Hierarchy
flowchart TD A[openapi: 3.1.0] --> B[info] A --> C[servers[]] A --> D[paths] A --> E[components] A --> F[tags] A --> G[security] D --> H[/path] H --> I[get / post / put / delete] I --> J[parameters[]] I --> K[requestBody] I --> L[responses] I --> M[security[]] E --> N[schemas] E --> O[securitySchemes] E --> P[parameters] E --> Q[responses] A:::current classDef current fill:#f90,color:#fff,stroke:#333,stroke-width:2px
Info Object
The info object provides metadata: title, version, description, terms of service, contact, and license.
openapi: 3.1.0
info:
title: DodaTech File Processing API
version: 2.1.0
description: |
Compress, decompress, and analyze files at scale.
Built by the developers of DodaZIP and Durga Antivirus Pro.
termsOfService: https://dodatech.com/terms
contact:
name: API Support
email: api@dodatech.com
url: https://docs.dodatech.com/support
license:
name: Apache 2.0
url: https://www.apache.org/licenses/LICENSE-2.0
Servers Array
Define all environments where the API runs. Use variables for dynamic values.
servers:
- url: https://{environment}.dodatech.com/v2
description: Dynamic environment
variables:
environment:
default: api
enum:
- api
- sandbox
- staging
- url: http://localhost:3000
description: Local development
Paths and Operations
Each path maps to an endpoint. Operations define the HTTP method behavior.
paths:
/files:
get:
operationId: listFiles
summary: List all files
description: Returns paginated list of uploaded files.
tags: [Files]
parameters:
- name: page
in: query
required: false
schema:
type: integer
default: 1
responses:
"200":
description: Paginated file list
content:
application/json:
schema:
$ref: "#/components/schemas/FileList"
"401":
$ref: "#/components/responses/Unauthorized"
Parameter Definitions
Parameters can be path, query, header, or cookie. Define them inline or in components.
parameters:
- name: fileId
in: path
required: true
description: Unique identifier for the file
schema:
type: string
pattern: "^file_[a-zA-Z0-9]{16}$"
example: "file_a1b2c3d4e5f6g7h8"
- name: page
in: query
required: false
schema:
type: integer
minimum: 1
default: 1
- name: X-Request-ID
in: header
required: false
description: Correlate requests across systems
schema:
type: string
format: uuid
Request Bodies
Define request body content with media type and schema.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [file_url]
properties:
file_url:
type: string
format: uri
example: "https://example.com/data.csv"
format:
type: string
enum: [zip, gzip, sevenz]
default: zip
examples:
zip:
summary: ZIP compression
value:
file_url: "https://example.com/data.csv"
format: zip
encrypted:
summary: Encrypted archive
value:
file_url: "https://example.com/data.csv"
format: zip
password: my-secure-password
Responses
Every response needs a status code, description, and optional content schema.
responses:
"200":
description: Compression completed successfully
content:
application/json:
schema:
$ref: "#/components/schemas/CompressResponse"
headers:
X-Request-ID:
schema:
type: string
format: uuid
"413":
description: File exceeds size limit
content:
application/problem+json:
schema:
$ref: "#/components/schemas/Error"
Reusable Components
Components section stores shared schemas, parameters, responses, and security schemes.
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
schemas:
Error:
type: object
properties:
code:
type: string
message:
type: string
docs_url:
type: string
format: uri
required: [code, message]
responses:
Unauthorized:
description: Missing or invalid authentication
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
Tags for Organization
Tags group related endpoints in generated documentation.
tags:
- name: Files
description: File upload and management
- name: Compression
description: File compression operations
- name: Jobs
description: Async job monitoring
- name: Webhooks
description: Event notifications
Common Mistakes
1. Missing $ref for Shared Schemas
Duplicating the same schema across multiple endpoints creates inconsistency. Use $ref to reference a single source of truth in components.
2. Incorrect Indentation
OpenAPI is sensitive to YAML indentation. Two-space indentation is standard. Mixing tabs and spaces causes Parsing errors.
3. Omitting operationId
Without operationId, generated SDKs generate unpredictable method names. Every operation needs a unique operationId.
4. Empty or Missing Descriptions
Parameters and schemas without descriptions are useless in generated docs. Every field needs a clear description of what it does.
5. Mixing Media Types Incorrectly
Declaring application/json content when the endpoint accepts multipart/form-data breaks client generation. Use the correct media type for each operation.
6. No Error Response Schemas
Defining only success responses means generated docs show no error formats. Every status code needs a response definition.
7. Inconsistent Parameter Styles
Some parameters in path, some in query, some in header without clear convention. Group related parameters and document the location convention.
Practice Questions
1. What are the four parameter locations in OpenAPI?
Path parameters (in the URL path), query parameters (after ? in the URL), header parameters (in HTTP headers), and cookie parameters (in HTTP cookies).
2. How does $ref work in OpenAPI?
The $ref keyword references a component definition by its JSON path. For example, $ref: "#/components/schemas/User" references the User schema in components. The reference is resolved at parse time.
3. What is the purpose of the operationId field?
OperationId provides a unique identifier for each operation. SDK generators use it to name methods. Client libraries expose client.listFiles() instead of client.get("/files").
4. Why use examples in OpenAPI schemas?
Examples show developers what real data looks like. They appear in generated documentation and help users understand the expected format without reading the full schema.
5. Challenge: Take the notes API spec from Lesson 3 and refactor it to use reusable components for schemas, parameters, and responses. Add tags for grouping. Validate the final spec with Spectral.
FAQ
Mini Project: Complete OpenAPI Spec
Write a complete OpenAPI 3.1 spec for a task management API with at least 8 endpoints across 3 tags. Include paginated list endpoints, create/update/delete operations, authentication, error responses, and reusable components. Validate with Spectral and generate docs with Redoc.
What's Next
Master the spec format, then apply it to creating API Reference Documentation that developers can navigate. Next, learn to write Conceptual Documentation that explains the big picture.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro