OpenAPI/Swagger Introduction
OpenAPI (formerly Swagger) is the industry standard for describing REST APIs. It enables automatic documentation, code generation, and testing.
What is OpenAPI?
OpenAPI is a specification format (YAML or JSON) that describes:
- Available endpoints
- Request/response formats
- Authentication methods
- Data models
Basic Structure
openapi: 3.0.0
info:
title: My API
version: 1.0.0
description: A sample API
servers:
- url: https://api.example.com/v1
paths:
/users:
get:
summary: List users
responses:
'200':
description: Success
components:
schemas:
User:
type: object
properties:
id:
type: string
Key Sections
Info
info:
title: Pet Store API
version: 1.0.0
description: |
The Pet Store API allows you to manage pets.
## Authentication
Use Bearer token authentication.
contact:
email: api@petstore.com
license:
name: MIT
Servers
servers:
- url: https://api.petstore.com/v1
description: Production
- url: https://sandbox.petstore.com/v1
description: Sandbox
Paths (Endpoints)
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- Pets
parameters:
- name: limit
in: query
schema:
type: integer
maximum: 100
responses:
'200':
description: A list of pets
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
Components (Reusable Definitions)
components:
schemas:
Pet:
type: object
required:
- id
- name
properties:
id:
type: integer
name:
type: string
status:
type: string
enum: [available, pending, sold]
securitySchemes:
bearerAuth:
type: http
scheme: bearer
Exercise: Write OpenAPI Paths
Loading JavaScript Exercise...
Tools Ecosystem
Documentation Generators
- Swagger UI - Interactive documentation
- Redoc - Clean, responsive docs
- Stoplight Elements - Modern doc components
Code Generators
- OpenAPI Generator - Generate client/server code
- Swagger Codegen - Multi-language generation
Validators
- Spectral - Linting for OpenAPI
- swagger-cli - Validation and bundling
Best Practices
- Use $ref for reusability - Define schemas once
- Include examples - Real-world data samples
- Document errors - All possible error responses
- Use tags - Organize endpoints logically
- Add descriptions - Explain not just document
Summary
OpenAPI provides:
- Standard API description format
- Automatic documentation generation
- Client/server code generation
- Validation and testing tools
- Industry-wide adoption

