Skip to content

OpenAPI

  • OpenAPI (formerly known as Swagger) is a specification for describing REST APIs.
  • It’s like a blueprint that tells developers exactly how your API works: what endpoints are available, what data they expect, and what they return.
  • Think of it as a user manual for your API that both humans and computers can understand.
  • OpenAPI specifications are written in YAML (or JSON) format and follow a specific structure.


Before diving into OpenAPI, here are the YAML basics you’ll need:

  • Indentation matters: Use 2 spaces (not tabs) for each level.
  • Key-value pairs: key: value
  • Lists: Use hyphens (-) for array items.
  • Strings: Can be quoted or unquoted (quote when containing special characters).
  • Comments: Start with #

Every OpenAPI specification follows this structure. Here’s a complete example:

openapi: 3.2.0
info:
title: My Planets API
description: A simple API for managing planetary data
version: 1.0.0
servers:
- url: https://api.space-research.com/v1
description: Production server
paths:
/planets:
get:
summary: Get all planets
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Planet'
components:
schemas:
Planet:
type: object
required:
- id
- name
- system
properties:
id:
type: integer
example: 1
name:
type: string
example: "Earth"
system:
type: string
example: "Solar System"

Let’s walk through each section.


Provides basic metadata about your API. Always specify a clear title, a brief description, and a version number (use semantic versioning like 1.0.0).

info:
title: Your API Name
description: What your API does
version: 1.0.0
contact:
name: Your Name
email: your.email@example.com

Lists where your API is hosted. You can define multiple servers (e.g., production, staging, development).

servers:
- url: https://api.example.com/v1
description: Production server
- url: https://staging-api.example.com/v1
description: Staging server

This is the core of your specification. For each endpoint, define:

  • The URI path (e.g., /planets, /planets/{id})
  • HTTP methods (get, post, put, delete)
  • Parameters: path parameters (like {id}), query parameters (filters, pagination), and request bodies (for POST/PUT)
  • Responses: all possible HTTP status codes with their content types and schemas
paths:
/planets/{id}:
get:
summary: Get planet by ID
parameters:
- name: id
in: path
required: true
schema:
type: integer
responses:
'200':
description: Planet found
'404':
description: Planet not found

The components section is where you define reusable pieces of your specification. Instead of repeating the same definition in every endpoint, you define it once here and reference it with $ref. It can contain:

  • schemas: Data models (e.g., Planet, ErrorResponse)
  • parameters: Query or path parameters (e.g., page, page_size)
  • responses: Common error responses (e.g., 400 Bad Request, 500 Internal Server Error)
  • securitySchemes: Authentication methods (e.g., API keys, JWT tokens)

See the OpenAPI Example page for a detailed explanation and a complete example using components.


/planets:
get:
summary: Get all planets
parameters:
- name: limit
in: query
schema:
type: integer
default: 10

/planets:
post:
summary: Create a new planet
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/Planet'

/planets/{id}:
put:
summary: Update a planet
parameters:
- name: id
in: path
required: true
schema:
type: integer

/planets/{id}:
delete:
summary: Delete a planet
parameters:
- name: id
in: path
required: true
schema:
type: integer

OpenAPI supports various data types with validation rules:

properties:
age:
type: integer
minimum: 0
maximum: 150
email:
type: string
format: email
website:
type: string
format: uri
birthDate:
type: string
format: date
rating:
type: number
minimum: 1.0
maximum: 5.0
tags:
type: array
items:
type: string

components:
securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key
security:
- ApiKeyAuth: []

components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT

  • Inconsistent indentation: Always use 2 spaces.
  • Missing colons: Every key needs a colon.
  • Incorrect list formatting: Use proper hyphen alignment.
  • Missing required fields: Always mark required fields in your schemas.
  • Inconsistent data types: Use the same type for the same data across endpoints.
  • Missing examples: Always provide realistic examples.
  • Incomplete error handling: Document all possible error scenarios.
  • Vague descriptions: Write clear, specific descriptions for endpoints and parameters.
  • Ignoring status codes: Document all possible HTTP response codes.
  • Non-RESTful patterns: Follow REST principles for consistency.
  • Overly complex schemas: Keep data models simple and focused.
  • Missing versioning: Always include API version information.
  • Inconsistent naming: Use camelCase for properties and kebab-case for paths.

  • Define your API’s basic info (title, version, description).
  • List your server URIs.
  • Document at least one GET endpoint.
  • Create schemas for your main data models.
  • Add request/response examples.
  • Test your specification in Swagger Editor.
  • All endpoints have clear descriptions and realistic examples.
  • Every response code is documented with appropriate schemas.
  • Data models are complete with proper types and validations.
  • Authentication requirements are clearly specified.
  • Error responses include meaningful error messages.
  • File validates without errors in VS Code extension.
  • Specification renders properly in OpenAPI Playground.
  • Generate documentation to share with others.