πŸ”§ DevOps

Swagger

Swagger

An API documentation tool. OpenAPI spec. Automatic documentation generation.

Detailed Explanation

Swagger is a set of tools for designing, documenting, and testing RESTful APIs. It has now been standardized under the name OpenAPI Specification (OAS), and by defining the structure of an API in YAML or JSON, documentation and client SDKs can be generated automatically.

The Swagger/OpenAPI ecosystem consists of three main parts: Swagger Editor (writing specs), Swagger UI (interactive documentation), and Swagger Codegen (code generation). In the API-First design approach, the OpenAPI spec is defined before any code is written, and server stubs and client SDKs are automatically generated from it. Frontend and backend teams can develop in parallel, which greatly improves productivity.

Code Example

OpenAPI 3.0 Spec Example

# openapi.yaml
openapi: 3.0.3
info:
  title: E-Commerce API
  description: μ „μžμƒκ±°λž˜ ν”Œλž«νΌ REST API
  version: 1.0.0
  contact:
    name: API Support
    email: api@example.com
servers:
  - url: https://api.example.com/v1
    description: Production
  - url: https://staging-api.example.com/v1
    description: Staging

paths:
  /products:
    get:
      summary: μƒν’ˆ λͺ©λ‘ 쑰회
      tags:
        - Products
      parameters:
        - name: category
          in: query
          schema:
            type: string
          description: μΉ΄ν…Œκ³ λ¦¬ ν•„ν„°
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
            maximum: 100
      responses:
        '200':
          description: 성곡
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Product'
                  pagination:
                    $ref: '#/components/schemas/Pagination'

  /products/{productId}:
    get:
      summary: μƒν’ˆ 상세 쑰회
      tags:
        - Products
      parameters:
        - name: productId
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: 성곡
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Product'
        '404':
          $ref: '#/components/responses/NotFound'

components:
  schemas:
    Product:
      type: object
      required:
        - id
        - name
        - price
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
          minLength: 1
          maxLength: 200
        price:
          type: number
          format: float
          minimum: 0
        description:
          type: string
        category:
          type: string
        createdAt:
          type: string
          format: date-time

    Pagination:
      type: object
      properties:
        total:
          type: integer
        page:
          type: integer
        limit:
          type: integer

  responses:
    NotFound:
      description: λ¦¬μ†ŒμŠ€λ₯Ό 찾을 수 μ—†μŒ
      content:
        application/json:
          schema:
            type: object
            properties:
              error:
                type: string
              message:
                type: string

  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

security:
  - bearerAuth: []

Setting Up Swagger UI in Express.js

// app.js
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');

const app = express();
const swaggerDocument = YAML.load('./openapi.yaml');

// Swagger UI μ„€μ •
const swaggerOptions = {
  customCss: '.swagger-ui .topbar { display: none }',
  customSiteTitle: "E-Commerce API Docs",
  swaggerOptions: {
    persistAuthorization: true,
    displayRequestDuration: true,
  }
};

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, swaggerOptions));

// API μ—”λ“œν¬μΈνŠΈ
app.get('/products', (req, res) => {
  // OpenAPI μŠ€νŽ™μ— μ •μ˜λœ λŒ€λ‘œ 응닡
  res.json({
    data: [...],
    pagination: { total: 100, page: 1, limit: 20 }
  });
});

app.listen(3000, () => {
  console.log('API μ„œλ²„ μ‹€ν–‰ 쀑: http://localhost:3000');
  console.log('API λ¬Έμ„œ: http://localhost:3000/api-docs');
});

Practical Conversation

Frontend Developer

"I can't start the frontend work until the backend API development is finished, so the schedule is tight."

Backend developer

"I'll write the OpenAPI spec first and share it. If we provide mock responses through Swagger UI, we can develop in parallel."

Frontend Developer

"Do I have to define the types manually too? It's easy to miss things when the API response types change..."

Backend developer

"With a tool like openapi-typescript, you can automatically generate TypeScript types from the OpenAPI spec. When the spec changes, the types are updated automatically too, so it's safe."

QA Engineer

"Can I also test API calls directly in Swagger UI?"

Backend developer

"Yes, you can test right away with the 'Try it out' button. It's convenient if you set up the authentication token as well."

Cautions

  • Keep the spec and implementation in sync: If the OpenAPI spec differs from the actual API implementation, confusion results. Generate the spec automatically from the code, or use spec-based validation middleware.
  • Exposure of sensitive information: Be careful that internal APIs or sensitive endpoints are not exposed in the production Swagger UI. Set up access restrictions if necessary.
  • Version control: When the API version changes, version-control the OpenAPI spec along with it. It is good to specify the version in the path, such as /v1, /v2.
  • Excessive documentation: Do not try to put every detail into the spec. Focus on the core contract (request/response schemas).
  • Example data: Providing realistic example data in the example field greatly improves documentation readability.

Learn More