OpenAPI Specification Basics

The 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; it was later donated to the OpenAPI Initiative and renamed OpenAPI.

The main functions of the OpenAPI Specification include:

  • Provide standardized documentation for APIs
  • Support automated testing of APIs
  • Generate client SDKs
  • Promote separation of frontend and backend development

OpenAPI currently has two widely used versions:

  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.

Structure of the OpenAPI Specification

OpenAPI documents are usually written in YAML or JSON format.

Below is a basic OpenAPI document structure:

Example

openapi: 3.1.0 # OpenAPI version
info:
title: Example API # API name
description: This is an example 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: Return a list of all users in the system
      operationId: getUsers
      tags:
- users # Group tag
parameters: # Request parameters
        - name: limit
          in: query
description: Limit on the number of returned results
          schema:
            type: integer
            default: 20
responses: # Response definitions
'200': # HTTP status code
description: Successfully return 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

Detailed Explanation of OpenAPI Core Concepts

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: [email protected]
  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: Test environment

3. Paths (paths)

The paths section defines all endpoints of the API 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 under a path defines 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 get user information
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '404':
description: User does not exist
          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 methods such as POST, PUT, etc.:

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 the 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 the 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]

Create 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: [email protected]
    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, with pagination and filtering support
      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: Number of 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: Parameter error
          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: [write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProductCreate'
      responses:
        '201':
description: Product created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Product'
        '400':
description: Invalid request data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /products/{productId}:
    get:
summary: Get product details
description: Get detailed information of a specific product by ID
      operationId: getProductById
      tags:
        - products
      parameters:
        - name: productId
          in: path
          required: true
description: Product ID
          schema:
            type: integer
      responses:
        '200':
description: Successfully retrieved product information
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Product'
        '404':
description: Product not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
   
    put:
summary: Update product
description: Update information for a specific product
      operationId: updateProduct
      tags:
        - products
      security:
        - ApiKeyAuth: []
        - OAuth2: [write]
      parameters:
        - name: productId
          in: path
          required: true
description: Product ID
          schema:
            type: integer
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProductUpdate'
      responses:
        '200':
description: Product updated successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Product'
        '400':
description: Invalid request data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '404':
description: Product not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
   
    delete:
summary: Delete product
description: Delete a specific product
      operationId: deleteProduct
      tags:
        - products
      security:
        - ApiKeyAuth: []
        - OAuth2: [write]
      parameters:
        - name: productId
          in: path
          required: true
description: Product ID
          schema:
            type: integer
      responses:
        '204':
description: Product deleted successfully
        '401':
description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '404':
description: Product not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /orders:
    get:
summary: Get order list
description: Returns a list of all orders, with pagination and filtering support
      operationId: getOrders
      tags:
        - orders
      security:
        - ApiKeyAuth: []
        - OAuth2: [read]
      parameters:
        - name: status
          in: query
description: Filter by order status
          schema:
            type: string
            enum: [pending, processing, shipped, delivered, cancelled]
        - name: page
          in: query
description: Page number
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
description: Number of items per page
          schema:
            type: integer
            default: 20
      responses:
        '200':
description: Successfully retrieved order list
          content:
            application/json:
              schema:
                type: object
                properties:
                  total:
                    type: integer
                  orders:
                    type: array
                    items:
                      $ref: '#/components/schemas/Order'
        '401':
description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
   
    post:
summary: Create new order
description: Create a new order
      operationId: createOrder
      tags:
        - orders
      security:
        - ApiKeyAuth: []
        - OAuth2: [write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OrderCreate'
      responses:
        '201':
description: Order created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Order'
        '400':
description: Invalid request data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

components:
  schemas:
    Product:
      type: object
      properties:
        id:
          type: integer
          format: int64
          readOnly: true
        name:
          type: string
          maxLength: 100
        description:
          type: string
        price:
          type: number
          format: float
          minimum: 0
        category:
          type: string
          enum: [electronics, books, clothing, food]
        inStock:
          type: boolean
          default: true
        createdAt:
          type: string
          format: date-time
          readOnly: true
        updatedAt:
          type: string
          format: date-time
          readOnly: true
      required:
        - name
        - price
        - category
   
    ProductCreate:
      type: object
      properties:
        name:
          type: string
          maxLength: 100
        description:
          type: string
        price:
          type: number
          format: float
          minimum: 0
        category:
          type: string
          enum: [electronics, books, clothing, food]
        inStock:
          type: boolean
          default: true
      required:
        - name
        - price
        - category
   
    ProductUpdate:
      type: object
      properties:
        name:
          type: string
          maxLength: 100
        description:
          type: string
        price:
          type: number
          format: float
          minimum: 0
        category:
          type: string
          enum: [electronics, books, clothing, food]
        inStock:
          type: boolean
   
    Order:
      type: object
      properties:
        id:
          type: integer
          format: int64
          readOnly: true
        userId:
          type: integer
          format: int64
        items:
          type: array
          items:
            $ref: '#/components/schemas/OrderItem'
        totalAmount:
          type: number
          format: float
          readOnly: true
        status:
          type: string
          enum: [pending, processing, shipped, delivered, cancelled]
          default: pending
        shippingAddress:
          $ref: '#/components/schemas/Address'
        createdAt:
          type: string
          format: date-time
          readOnly: true
        updatedAt:
          type: string
          format: date-time
          readOnly: true
      required:
        - userId
        - items
        - shippingAddress
   
    OrderCreate:
      type: object
      properties:
        userId:
          type: integer
          format: int64
        items:
          type: array
          items:
            $ref: '#/components/schemas/OrderItem'
        shippingAddress:
          $ref: '#/components/schemas/Address'
      required:
        - userId
        - items
        - shippingAddress
   
    OrderItem:
      type: object
      properties:
        productId:
          type: integer
          format: int64
        quantity:
          type: integer
          minimum: 1
          default: 1
        unitPrice:
          type: number
          format: float
          readOnly: true
      required:
        - productId
        - quantity
   
    Address:
      type: object
      properties:
        street:
          type: string
        city:
          type: string
        state:
          type: string
        zipCode:
          type: string
        country:
          type: string
      required:
        - street
        - city
        - state
        - zipCode
        - country
   
    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

security:
  - ApiKeyAuth: []

Basic Syntax of the OpenAPI Specification

The OpenAPI specification supports two formats:

  1. YAML (recommended)
  2. JSON

YAML Format Example

Example

openapi: 3.0.0
info:
title: Pet Store API
  version: 1.0.0
paths:
  /pets:
    get:
summary: List all pets
      responses:
        '200':
description: Successfully retrieved pet list

JSON Format Example

Example

"openapi": "3.0.0",
  "info": {
    "title": "Pet Store API",
    "version": "1.0.0"
  },
  "paths": {
    "/pets": {
      "get": {
        "summary": "List all pets",
        "responses": {
          "200": {
            "description": "Successfully retrieved pet list"
          }
        }
      }
    }
  }
}

How to Use the OpenAPI Specification

1. Create and Edit OpenAPI Documents

You can use the following tools to create and edit OpenAPI documents:

  • Swagger Editor: Online editor with real-time preview and validation
  • Stoplight Studio: Visual API design tool
  • VS Code + OpenAPI plugin: Edit in integrated development environment

2. Document Generation

The OpenAPI specification can automatically generate beautiful API documentation. Common tools include:

  • Swagger UI: Generate interactive API documentation
  • ReDoc: Provides responsive, customizable documentation
  • Slate: Generate elegant static documentation

3. Code Generation

OpenAPI can automatically generate client and server code in multiple languages:

  • OpenAPI Generator: Supports 40+ programming languages
  • Swagger Codegen: Generate client and server code
  • NSwag: Code generator for the .NET ecosystem

4. API Testing and Mocking

The OpenAPI specification can also be used for:

  • Automated testing: Using tools such as Postman, SoapUI
  • API mocking: Prism, Microcks, etc. can mock APIs based on the OpenAPI specification

Best Practices

1. Design Principles

  • Keep endpoint naming consistent
  • Use appropriate HTTP methods and status codes
  • Design a clear URL path structure

2. Documentation Recommendations

  • Provide detailed descriptions and examples
  • Use tags to group APIs
  • Clearly specify required parameters

3. Version Control Strategy

  • Include the version number in the URL (/v1/users)
  • Use request headers to specify the version (Accept: application/vnd.example.v1+json)
  • Clearly specify version information in the OpenAPI document

Frequently Asked Questions

1. What is the difference between OpenAPI and Swagger?

Swagger is the predecessor of the OpenAPI specification. In 2016, the Swagger specification was donated to the Linux Foundation and renamed the OpenAPI specification. Now, "Swagger" usually refers to the toolset built around the OpenAPI specification.

2. What are the main differences between OpenAPI 2.0 and 3.x?

OpenAPI 3.x introduced many new features, including:

  • Improved component reuse
  • More flexible request body definitions
  • More powerful security definitions
  • Improved JSON Schema support
  • links and callbacks support

3. How to handle authentication and authorization?

OpenAPI supports multiple security mechanisms:

  • API keys
  • HTTP basic authentication
  • OAuth2.0
  • OpenID Connect
  • Custom header authentication

Learning Resources

  1. Official documentation:OpenAPI Initiative
  2. Tools:
  3. Learning resources:
Other extensions