Swagger First Doc
Swagger (OpenAPI) is a specification and toolkit used to describe, generate, and visualize RESTful web services.
Below, I will provide a detailed guide on how to write your first Swagger document from scratch.
Swagger documents are primarily written in YAML or JSON format, defining various aspects of the API, including:
* Basic API information (title, version, etc.)
* Available endpoints and operations
* Input parameters and output responses
* Authentication methods
* Data model definitions
* * *
## Creation Steps
### 1. Create a Basic File Structure
First, create a file named `swagger.yaml` or `swagger.json`. This tutorial uses YAML format as it is easier to read and write.
## Example
openapi: 3.0.0
info:
title: My First API
description: This is a simple API example document
version: 1.0.0
contact:
name: API Support Team
email: support@example.com
url: https://www.example.com/support
servers:
- url: https://api.example.com/v1
description: Production environment
- url: https://dev-api.example.com/v1
description: Development environment
### 2. Add Basic Document Information
## Example
openapi: 3.0.0
info:
title: My First API
description: This is a simple API example document
version: 1.0.0
contact:
name: API Support Team
email: support@example.com
url: https://www.example.com/support
servers:
- url: https://api.example.com/v1
description: Production environment
- url: https://dev-api.example.com/v1
description: Development environment
### 3. Define Endpoints and Operations
Endpoints define the accessible points of the API, while operations specify the HTTP methods (GET, POST, PUT, DELETE, etc.) that can be performed on these endpoints.
## Example
paths:
/users:
get:
summary: Get all users list
description: Returns all user information in the system
operationId: getUsers
parameters:
- name: limit
in: query
description: Maximum number of results to return
required: false
schema:
type: integer
format: int32
minimum: 1
maximum: 100
default: 20
responses:
'200':
description: Successfully retrieved user list
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
'400':
description: Invalid request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
post:
summary: Create a new user
description: Creates a new user in the system
operationId: createUser
requestBody:
description: User information
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/NewUser'
responses:
'201':
description: User created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: Invalid request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
### 4. Define Components and Models
Define reusable models in the `components` section:
## Example
components:
schemas:
User:
type: object
properties:
id:
type: integer
format: int64
description: Unique user identifier
username:
type: string
description: Username
email:
type: string
format: email
description: User's email
status:
type: string
enum: [active, inactive, banned]
description: User status
createdAt:
type: string
format: date-time
description: Creation time
required:
- id
- username
- email
- status
NewUser:
type: object
properties:
username:
type: string
description: Username
email:
type: string
format: email
description: User's email
password:
type: string
format: password
description: User's password
minLength: 8
required:
- username
- email
- password
Error:
type: object
properties:
code:
type: integer
format: int32
message:
type: string
required:
- code
- message
### 5. Add Security Definitions
Define security requirements for the API:
## Example
security:
- bearerAuth: []
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
### 6. Complete Document Example
Combine all the above sections to form a complete Swagger document.
## Example
openapi: 3.0.0
info:
title: My First API
description: This is a simple API example document
version: 1.0.0
contact:
name: API Support Team
email: support@example.com
url: https://www.example.com/support
servers:
- url: https://api.example.com/v1
description: Production environment
- url: https://dev-api.example.com/v1
description: Development environment
paths:
/users:
get:
summary: Get all users list
description: Returns all user information in the system
operationId: getUsers
parameters:
- name: limit
in: query
description: Maximum number of results to return
required: false
schema:
type: integer
format: int32
minimum: 1
maximum: 100
default: 20
responses:
'200':
description: Successfully retrieved user list
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
'400':
description: Invalid request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
post:
summary: Create a new user
description: Creates a new user in the system
operationId: createUser
requestBody:
description: User information
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/NewUser'
responses:
'201':
description: User created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: Invalid request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
components:
schemas:
User:
type: object
properties:
id:
type: integer
format: int64
description: Unique user identifier
username:
type: string
description: Username
email:
type: string
format: email
description: User's email
status:
type: string
enum: [active, inactive, banned]
description: User status
createdAt:
type: string
format: date-time
description: Creation time
required:
- id
- username
- email
- status
NewUser:
type: object
properties:
username:
type: string
description: Username
email:
type: string
format: email
description: User's email
password:
type: string
format: password
description: User's password
minLength: 8
required:
- username
- email
- password
Error:
type: object
properties:
code:
type: integer
format: int32
message:
type: string
required:
- code
- message
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
security:
- bearerAuth: []
### 7. Use Swagger Tools
There are several ways to visualize and test your Swagger document:
1. **Swagger UI**: An interactive documentation page
2. **Swagger Editor**: An online editor that allows real-time preview of the document
3. **Swagger Codegen**: A tool for generating client-side code
### 8. Test Your Document Online
You can use (https://editor.swagger.io/) to test your document online. Simply copy and paste your YAML or JSON into the editor, and the right-hand panel will display a visualized API document.
!(#)
### 9. Best Practices
* Use meaningful operation IDs
* Provide detailed descriptions for each endpoint
* Ensure all parameters have clear descriptions
* Document all possible response status codes
* Use model references to reduce redundancy
* Keep your documentation updated
* Add example requests and responses for each endpoint
### 10. Common Parameter Positions
Swagger defines several parameter positions:
* `path`: Parameters embedded in the URL path, such as `/users/{id}`
* `query`: Query parameters in the URL, like `/users?limit=10`
* `header`: HTTP header parameters
* `cookie`: Cookie parameters
* `body`: Request body parameters (use `requestBody` instead in OpenAPI 3.0)
### 11. Extend Your Document
As your API evolves, continue expanding your Swagger document:
* Add more endpoints
* Define additional models
* Include more detailed explanations
* Add example requests and responses
### 12. Integration in Actual Development
In real-world development, you can:
* Integrate Swagger into your codebase
* Use automated generation tools
* Generate documentation directly from code comments
* Embed Swagger UI within your applications
YouTip