Openapi Basic
OpenAPI Specification (OAS) is a standard format for describing RESTful APIs.
The OpenAPI Specification allows developers to define API structure, parameters, responses, and other information in a machine-readable way.
The OpenAPI Specification was originally called the Swagger Specification, later donated to the OpenAPI Initiative and renamed to OpenAPI.
The main purposes of the OpenAPI Specification include:
* Providing standardized documentation for APIs
* Supporting automated testing of APIs
* Generating client SDKs
* Promoting front-end and back-end separation development
Currently, there are two widely used versions of OpenAPI:
1. OpenAPI 2.0 (formerly Swagger 2.0)
2. OpenAPI 3.x (latest stable version)
It is recommended to use OpenAPI 3.x for new projects as it provides more features and improvements.
### OpenAPI Specification Structure
OpenAPI documents are typically written in YAML or JSON format.
Below is a basic OpenAPI document structure:
## Example
openapi: 3.1.0 # OpenAPI version
info:
title: Sample API # API name
description: This is a sample API document
version: 1.0.0 # API version
servers:
- url: https://api.example.com/v1 # API server address
description: Production environment
- url: https://dev-api.example.com/v1
description: Development environment
paths: # API path definitions
/users: # Endpoint path
get: # HTTP method
summary: Get all users
description: Returns a list of all users in the system
operationId: getUsers
tags:
- users # Grouping tag
parameters: # Request parameters
- name: limit
in: query
description: Limit the number of returned results
schema:
type: integer
default: 20
responses: # Response definitions
'200': # HTTP status code
description: Successfully returned user list
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
'400':
description: Invalid request parameters
components: # Reusable components
schemas: # Data model definitions
User:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
email:
type: string
format: email
required:
- id
- name
* * *
## OpenAPI Core Concepts Explained
### 1. Document Metadata (info)
The info section contains basic information about the API, such as title, description, version, etc.:
## Example
info:
title: User Management API
description: API for managing user information in the system
version: 1.0.0
contact:
name: API Support Team
email: support@example.com
license:
name: Apache 2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
### 2. Server Information (servers)
The servers section defines the list of available API servers:
## Example
servers:
- url: https://api.example.com/v1
description: Production environment
- url: https://staging-api.example.com/v1
description: Testing environment
### 3. Paths (paths)
The paths section defines all API endpoints and the HTTP methods they support:
## Example
paths:
/users:
get:
# Get user list
post:
# Create new user
/users/{userId}:
get:
# Get specific user
put:
# Update user
delete:
# Delete user
### 4. Operations (operations)
Each HTTP method defined under a path represents an API operation:
## Example
paths:
/users/{userId}:
get:
summary: Get user details
description: Get detailed user information by user ID
operationId: getUserById
tags:
- users
parameters:
- name: userId
in: path
required: true
description: User ID
schema:
type: integer
responses:
'200':
description: Successfully retrieved user information
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'404':
description: User not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
### 5. Parameters (parameters)
Parameters can be defined in multiple locations:
## Example
parameters:
- name: userId
in: path # Path parameter
required: true
schema:
type: integer
- name: filter
in: query # Query parameter
schema:
type: string
- name: X-API-Key
in: header # Header parameter
schema:
type: string
- name: trace
in: cookie # Cookie parameter
schema:
type: string
### 6. Request Body (requestBody)
Define the request body for POST, PUT, and other methods:
## Example
requestBody:
description: User data
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/User'
application/x-www-form-urlencoded:
schema:
$ref: '#/components/schemas/UserForm'
### 7. Responses (responses)
Define possible responses for each operation:
## Example
responses:
'200':
description: Operation successful
content:
application/json:
schema:
$ref: '#/components/schemas/SuccessResponse'
'400':
description: Invalid request parameters
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
### 8. Components (components)
The components section is used to store elements that can be reused throughout the API document:
## Example
components:
schemas:
User:
type: object
properties:
id:
type: integer
name:
type: string
email:
type: string
format: email
roles:
type: array
items:
type: string
enum: [admin, user, editor]
required:
- name
- email
Error:
type: object
properties:
code:
type: integer
message:
type: string
required:
- code
- message
securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key
OAuth2:
type: oauth2
flows:
implicit:
authorizationUrl: https://example.com/oauth/authorize
scopes:
read: Read permission
write: Write permission
### 9. Data Models (schemas)
Define data structures used in the API:
## Example
schemas:
Product:
type: object
properties:
id:
type: integer
name:
type: string
maxLength: 100
price:
type: number
format: float
minimum: 0
category:
type: string
enum: [electronics, books, clothing]
### 10. Security (security)
Define authentication and authorization methods for the API:
## Example
security:
- ApiKeyAuth: []
- OAuth2: [read, write]
* * *
## Creating a Complete OpenAPI Document Example
Below is a more complete e-commerce API example:
## Example
openapi: 3.1.0
info:
title: E-commerce API
description: API for managing products and orders in an online store
version: 1.0.0
contact:
name: API Support Team
email: support@example.com
url: https://api.example.com/support
license:
name: MIT
url: https://opensource.org/licenses/MIT
servers:
- url: https://api.example.com/v1
description: Production environment
- url: https://dev-api.example.com/v1
description: Development environment
tags:
- name: products
description: Product-related operations
- name: orders
description: Order-related operations
- name: users
description: User-related operations
paths:
/products:
get:
summary: Get product list
description: Returns a list of all available products, supports pagination and filtering
operationId: getProducts
tags:
- products
parameters:
- name: category
in: query
description: Filter by product category
schema:
type: string
- name: page
in: query
description: Page number
schema:
type: integer
default: 1
- name: limit
in: query
description: Items per page
schema:
type: integer
default: 20
responses:
'200':
description: Successfully retrieved product list
content:
application/json:
schema:
type: object
properties:
total:
type: integer
products:
type: array
items:
$ref: '#/components/schemas/Product'
'400':
description: Invalid parameters
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
post:
summary: Create new product
description: Create new product information
operationId: createProduct
tags:
- products
security:
- ApiKeyAuth: []
- OAuth2:
YouTip