Swagger Advanced Features

Using components to reuse definitions

Schema (Data Model) Reuse

components allow you to define elements that can be reused throughout the API documentation, reducing duplication and ensuring consistency:

Example

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          format: int64
        username:
          type: string
        email:
          type: string

Reference method:

Example

paths:
  /users/{id}:
    get:
      responses:
        '200':
          description:User Information
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'

Parameters (Common Parameters) Reuse

Define common parameters:

Example

components:
  parameters:
    PageParam:
      name: page
      in: query
      schema:
        type: integer
        default: 1
      description:Page number
    LimitParam:
      name: limit
      in: query
      schema:
        type: integer
        default: 10
      description:Records per page

Reference method:

Example

paths:
  /products:
    get:
      parameters:
        - $ref: '#/components/parameters/PageParam'
        - $ref: '#/components/parameters/LimitParam'

Responses (Common Responses) Reuse

Define standard responses:

Example

components:
  responses:
    NotFound:
      description:Resource not found
      content:
        application/json:
          schema:
            type: object
            properties:
              code:
                type: integer
                example: 404
              message:
                type: string
                example: "Resource does not exist"
    BadRequest:
      description:Request parameter error
      content:
        application/json:
          schema:
            type: object
            properties:
              code:
                type: integer
                example: 400
              message:
                type: string

Reference method:

Example

paths:
  /users/{id}:
    get:
      responses:
        '200':
          description:Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '404':
          $ref: '#/components/responses/NotFound'
        '400':
          $ref: '#/components/responses/BadRequest'

API Version Control

Distinguish versions via servers

Example

servers:
  - url: https://api.example.com/v1
    description: API v1
  - url: https://api.example.com/v2
    description: API v2

Distinguish versions via path

Example

paths:
  /v1/users:
    get:
# v1 user interface...
 
  /v2/users:
    get:
# v2 user interface...

Distinguish versions via request headers

Example

paths:
  /users:
    get:
      parameters:
        - name: api-version
          in: header
          required: true
          schema:
            type: string
            enum: ['1.0', '2.0']

Mock Data Simulation

Using examples to define sample data

Define examples in the response:

Example

paths:
  /users:
    get:
      responses:
        '200':
          description:User list
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'
              examples:
                userList:
                  summary:Sample user list
                  value:
                    - id: 1
                      username: "user1"
                      email: "user1@example.com"
                    - id: 2
                      username: "user2"
                      email: "user2@example.com"

Using Swagger UI Mock feature

Swagger UI integrates a mock server that can generate mock responses based on your OpenAPI definition.

Configure mockServer in Swagger UI:

Example

SwaggerUI({
  url: "https://petstore.swagger.io/v2/swagger.json",
  dom_id: '#swagger-ui',
  presets: [
    SwaggerUI.presets.apis,
    SwaggerUIStandalonePreset
  ],
  plugins: [
    SwaggerUI.plugins.MockPlugin
  ],
  mockImplementations: {
    '/users': {
      get: () => ({
        status: 200,
        body: [
          { id: 1, name: "Test User 1" },
          { id: 2, name: "Test User 2" }
        ]
      })
    }
  }
})

Using third-party Mock services

  • Prism: OpenAPI mock server
  • Mockoon: a mock API tool that can integrate with Swagger
  • Postman: provides mock server functionality

Advanced Security Configuration

Define multiple authentication methods:

Example

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
    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

Apply security definitions:

Example

security:
  - bearerAuth: []
  - apiKeyAuth: []

paths:
  /users:
    get:
      security:
        - OAuth2: [read]

Document Separation and Organization

Use$refReference external files:

Example

paths:
  /users:
    $ref: './paths/users.yaml'
  /products:
    $ref: './paths/products.yaml'

components:
  schemas:
    User:
      $ref: './schemas/user.yaml'

Tags and Grouping

Use tags to organize API endpoints:

Example

tags:
  - name: users
    description:User Management
  - name: products
    description:Product Management

paths:
  /users:
    get:
      tags:
        - users
  /products:
    get:
      tags:
        - products

Extension Fields

Throughx-Add custom properties with a prefix:

Example

lpaths:
  /users:
    get:
      x-controller: UserController
      x-rate-limit: 100
      x-deprecated: false

These advanced features can help you create more structured, maintainable, and professional API documentation.

Other Extensions