← Trở về trang chủ

API Documentation Standards

API Documentation là gì?

API Documentation là tài liệu hướng dẫn chi tiết về cách sử dụng API, bao gồm endpoints, parameters, request/response formats, authentication, và examples.

Tại sao cần documentation tốt?

1. Developer Experience (DX)

  • ✓ Developers hiểu nhanh cách sử dụng API
  • ✓ Giảm learning curve
  • ✓ Self-service: Tìm thông tin mà không cần hỏi
  • ✓ Tăng satisfaction và productivity

2. Adoption và Usage

  • ✓ More developers = more adoption
  • ✓ Clear docs = faster integration
  • ✓ Good examples = fewer mistakes
  • ✓ Better docs = competitive advantage

3. Reduce Support Burden

  • ✓ FAQs trong docs thay vì support tickets
  • ✓ Troubleshooting guides giảm debugging requests
  • ✓ Code examples giảm "how to" questions
  • ✓ More time for actual development

4. Consistency

  • ✓ Standardized API design
  • ✓ Consistent naming conventions
  • ✓ Predictable behavior
  • ✓ Easy to maintain và scale

Các thành phần của Good Documentation

  • Getting Started: Quick start guide, authentication setup
  • Reference: Complete API reference với all endpoints
  • Examples: Code examples trong nhiều ngôn ngữ
  • Tutorials: Step-by-step guides cho common use cases
  • Concepts: Explain core concepts và architecture
  • Error Handling: Error codes và troubleshooting
  • Changelog: Version history và breaking changes
  • Interactive: Try-it-out features, sandbox

OpenAPI Specification (OAS) là gì?

OpenAPI Specification là một machine-readable format để định nghĩa RESTful APIs. Nó cho phép describe toàn bộ API trong một file YAML hoặc JSON.

Lịch sử: Swagger → OpenAPI

  • 2011: Swagger được tạo bởi Wordnik
  • 2015: SmartBear mua lại Swagger
  • 2016: Swagger Specification đổi tên thành OpenAPI Specification
  • 2017: OpenAPI 3.0.0 released
  • 2021: OpenAPI 3.1.0 released (current stable)

Note: "Swagger" giờ chỉ tools (Swagger UI, Swagger Editor), còn "OpenAPI" là specification.

Benefits của OpenAPI

  • Machine-readable: Tools có thể parse và process
  • Auto-generate docs: Swagger UI, Redoc tự động tạo interactive docs
  • Code generation: Generate client/server code nhiều ngôn ngữ
  • Testing integration: Import vào Postman, Insomnia, Paw
  • Validation: Validate requests/responses
  • Mock servers: Generate mock servers từ spec
  • API-first design: Design trước, implement sau

Cấu trúc OpenAPI Specification

openapi: 3.0.0
info:
  title: Sample API
  version: 1.0.0
  description: API description here
  contact:
    name: API Support
    email: support@example.com
  license:
    name: MIT
    url: https://opensource.org/licenses/MIT

servers:
  - url: https://api.example.com/v1
    description: Production server
  - url: https://staging-api.example.com/v1
    description: Staging server

paths:
  /users/{id}:
    get:
      summary: Get user by ID
      description: Returns a single user
      tags:
        - Users
      parameters:
        - name: id
          in: path
          required: true
          description: User ID
          schema:
            type: integer
            example: 123
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
              example:
                id: 123
                name: "Nguyễn Văn A"
                email: "vana@example.com"
        '404':
          description: User not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

  /users:
    post:
      summary: Create user
      tags:
        - Users
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UserInput'
      responses:
        '201':
          description: User created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          example: 123
        name:
          type: string
          example: "Nguyễn Văn A"
        email:
          type: string
          format: email
          example: "vana@example.com"
      required:
        - id
        - name
        - email

    UserInput:
      type: object
      properties:
        name:
          type: string
        email:
          type: string
          format: email
      required:
        - name
        - email

    Error:
      type: object
      properties:
        error:
          type: string
        code:
          type: integer

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

security:
  - bearerAuth: []

Key Components

Component Mô tả
info Metadata: title, version, description, contact
servers Base URLs (production, staging, dev)
paths Endpoints và operations (GET, POST, ...)
components Reusable: schemas, parameters, responses, security
security Authentication methods
tags Grouping endpoints (Users, Products, Orders)

OpenAPI Tools

1. Swagger UI

Interactive documentation tự động generated từ OpenAPI spec

  • ✓ Try-it-out feature
  • ✓ Syntax highlighting
  • ✓ Model schemas
  • ✓ Free và open-source

Demo: https://petstore.swagger.io/

2. Swagger Editor

Online editor để viết OpenAPI specs

  • ✓ Live preview
  • ✓ Validation
  • ✓ Auto-complete
  • ✓ Export to YAML/JSON

Link: https://editor.swagger.io/

3. Redoc

Alternative UI, clean và responsive

  • ✓ 3-panel layout
  • ✓ Better for large APIs
  • ✓ Search functionality
  • ✓ Mobile-friendly

Demo: https://redocly.github.io/redoc/

4. Swagger Codegen

Generate client SDKs và server stubs

  • ✓ 50+ languages
  • ✓ Client: JavaScript, PHP, Python, Java, ...
  • ✓ Server: Node.js, Spring Boot, Laravel, ...
  • ✓ CLI tool

5. Other Tools

  • Postman: Import OpenAPI specs
  • Insomnia: REST client with OpenAPI support
  • Stoplight: API design platform
  • SwaggerHub: Hosted OpenAPI platform
  • Prism: Mock server from OpenAPI

API Blueprint là gì?

API Blueprint là một Markdown-based format để document REST APIs. Nó sử dụng Markdown syntax, dễ đọc và dễ viết.

Đặc điểm chính:

  • Markdown-based: Dễ viết, dễ đọc cho humans
  • Simple syntax: Learning curve thấp
  • Apiary support: Integration với Apiary platform
  • Testing support: Dredd testing tool

Ví dụ API Blueprint

FORMAT: 1A

# My API

API description here.

# Group Users

## User [/users/{id}]

+ Parameters
    + id: 123 (number, required) - User ID

### Get User [GET]

+ Response 200 (application/json)

        {
            "id": 123,
            "name": "Nguyễn Văn A",
            "email": "vana@example.com"
        }

+ Response 404 (application/json)

        {
            "error": "User not found"
        }

## Users Collection [/users]

### Create User [POST]

+ Request (application/json)

        {
            "name": "Nguyễn Văn B",
            "email": "vanb@example.com"
        }

+ Response 201 (application/json)

        {
            "id": 456,
            "name": "Nguyễn Văn B",
            "email": "vanb@example.com"
        }

Tools & Ecosystem

  • Apiary: Hosted documentation platform
  • Dredd: API testing tool
  • Aglio: Static HTML generator
  • Snowboard: Modern API Blueprint viewer

Pros & Cons

Pros Cons
✓ Dễ học (Markdown) ✗ Ít phổ biến hơn OpenAPI
✓ Human-readable ✗ Ít tools hơn OpenAPI
✓ Tốt cho simple APIs ✗ Không tốt cho complex APIs
✓ Integration với Apiary ✗ Code generation hạn chế

RAML là gì?

RAML (RESTful API Modeling Language) là một YAML-based language để describe REST APIs với focus vào reusability.

Đặc điểm chính:

  • YAML syntax: Clean và concise
  • Reusability: Traits, resource types, data types
  • Modularity: Include files, fragments
  • Design patterns: Encourage best practices

Ví dụ RAML

#%RAML 1.0
title: My API
version: v1
baseUri: https://api.example.com/{version}
mediaType: application/json

types:
  User:
    type: object
    properties:
      id: integer
      name: string
      email:
        type: string
        pattern: ^.+@.+\..+$

traits:
  pageable:
    queryParameters:
      page:
        type: integer
        default: 1
      limit:
        type: integer
        default: 20

/users:
  get:
    is: [pageable]
    responses:
      200:
        body:
          type: User[]
          example:
            - id: 123
              name: "Nguyễn Văn A"
              email: "vana@example.com"

  post:
    body:
      type: User
      example:
        name: "Nguyễn Văn B"
        email: "vanb@example.com"
    responses:
      201:
        body:
          type: User

  /{id}:
    uriParameters:
      id:
        type: integer
    get:
      responses:
        200:
          body:
            type: User
        404:
          body:
            example:
              error: "User not found"

Tools & Ecosystem

  • API Workbench: IDE plugin (Atom, VS Code)
  • RAML Console: Interactive documentation
  • raml2html: Generate HTML docs
  • Mulesoft Anypoint: Enterprise platform

Pros & Cons

Pros Cons
✓ Reusability (traits, types) ✗ Ít phổ biến (declining)
✓ Modularity (includes) ✗ Community nhỏ
✓ Clean YAML syntax ✗ Ít tools hơn OpenAPI
✓ Mulesoft support ✗ Future uncertain

⚠️ Note:

RAML đang decline về popularity. OpenAPI đã trở thành industry standard cho REST APIs. Chỉ nên dùng RAML nếu đã có existing RAML specs hoặc đang dùng Mulesoft ecosystem.

Postman Collections là gì?

Postman Collections là một JSON format để organize và share API requests. Nó là native format của Postman, tool phổ biến nhất cho API testing.

Đặc điểm chính:

  • Testing focus: Built for API testing
  • Collaboration: Share với team dễ dàng
  • Environments: Variables, environments
  • Automation: Newman CLI, CI/CD integration
  • Mock servers: Built-in mock servers

Ví dụ Postman Collection JSON

{
  "info": {
    "name": "My API",
    "description": "API collection",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
  },
  "item": [
    {
      "name": "Users",
      "item": [
        {
          "name": "Get User",
          "request": {
            "method": "GET",
            "header": [
              {
                "key": "Authorization",
                "value": "Bearer {{token}}"
              }
            ],
            "url": {
              "raw": "{{baseUrl}}/users/:id",
              "host": ["{{baseUrl}}"],
              "path": ["users", ":id"],
              "variable": [
                {
                  "key": "id",
                  "value": "123"
                }
              ]
            }
          },
          "response": [
            {
              "name": "Success",
              "status": "OK",
              "code": 200,
              "body": "{\n  \"id\": 123,\n  \"name\": \"Nguyễn Văn A\"\n}"
            }
          ]
        },
        {
          "name": "Create User",
          "request": {
            "method": "POST",
            "header": [
              {
                "key": "Content-Type",
                "value": "application/json"
              }
            ],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"name\": \"Nguyễn Văn B\",\n  \"email\": \"vanb@example.com\"\n}"
            },
            "url": {
              "raw": "{{baseUrl}}/users",
              "host": ["{{baseUrl}}"],
              "path": ["users"]
            }
          }
        }
      ]
    }
  ],
  "variable": [
    {
      "key": "baseUrl",
      "value": "https://api.example.com"
    }
  ]
}

Postman Features

1. Testing Scripts

// Test response
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

pm.test("Response has user data", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.name).to.eql("Nguyễn Văn A");
});

2. Pre-request Scripts

// Set timestamp
pm.environment.set("timestamp", Date.now());

// Generate token
const token = CryptoJS.HmacSHA256("message", "secret");
pm.environment.set("token", token.toString());

3. Environments

// Development
{
  "baseUrl": "http://localhost:3000",
  "token": "dev_token_123"
}

// Production
{
  "baseUrl": "https://api.example.com",
  "token": "prod_token_456"
}

Newman CLI

Run collection từ command line:

# Install Newman
npm install -g newman

# Run collection
newman run my-collection.json \
  --environment production.json \
  --reporters cli,json,html

# CI/CD usage
newman run my-collection.json \
  --bail \
  --reporters junit \
  --reporter-junit-export results.xml

Pros & Cons

Pros Cons
✓ Very popular (most used tool) ✗ Không phải documentation-first
✓ Excellent testing features ✗ JSON format khó đọc
✓ Great collaboration ✗ Free tier limitations
✓ CI/CD integration ✗ Phụ thuộc vào Postman platform
✓ Mock servers ✗ Versioning phức tạp

💡 Best Use Cases:

  • API Testing: Primary use case
  • Team Collaboration: Share requests với team
  • Manual Testing: Ad-hoc testing, debugging
  • CI/CD: Automated testing với Newman

GraphQL Schema là gì?

GraphQL Schema là type system để define GraphQL APIs. Schema language (SDL - Schema Definition Language) là documentation format native của GraphQL.

⚠️ Important:

GraphQL không phải REST. Nó là một query language khác biệt hoàn toàn. OpenAPI không dùng được cho GraphQL APIs.

Ví dụ GraphQL Schema

"""
User type represents a user in the system
"""
type User {
  """
  Unique user identifier
  """
  id: ID!

  """
  User's full name
  """
  name: String!

  """
  User's email address
  """
  email: String!

  """
  User's posts
  """
  posts: [Post!]!

  """
  When the user was created
  """
  createdAt: DateTime!
}

"""
Post type represents a blog post
"""
type Post {
  id: ID!
  title: String!
  content: String!
  author: User!
  publishedAt: DateTime
}

"""
Root Query type
"""
type Query {
  """
  Get user by ID
  """
  user(id: ID!): User

  """
  Get all users with pagination
  """
  users(
    """
    Number of results to skip
    """
    offset: Int = 0

    """
    Maximum number of results to return
    """
    limit: Int = 20
  ): [User!]!

  """
  Search posts by title
  """
  searchPosts(query: String!): [Post!]!
}

"""
Root Mutation type
"""
type Mutation {
  """
  Create a new user
  """
  createUser(input: CreateUserInput!): User!

  """
  Update existing user
  """
  updateUser(id: ID!, input: UpdateUserInput!): User!

  """
  Delete user by ID
  """
  deleteUser(id: ID!): Boolean!
}

"""
Input type for creating user
"""
input CreateUserInput {
  name: String!
  email: String!
}

"""
Input type for updating user
"""
input UpdateUserInput {
  name: String
  email: String
}

GraphQL Query Examples

Query - Get user với nested posts:

query GetUserWithPosts($userId: ID!) {
  user(id: $userId) {
    id
    name
    email
    posts {
      id
      title
      publishedAt
    }
  }
}

# Variables
{
  "userId": "123"
}

Mutation - Create user:

mutation CreateUser($input: CreateUserInput!) {
  createUser(input: $input) {
    id
    name
    email
    createdAt
  }
}

# Variables
{
  "input": {
    "name": "Nguyễn Văn A",
    "email": "vana@example.com"
  }
}

GraphQL Documentation Tools

1. GraphiQL

  • ✓ Interactive in-browser IDE
  • ✓ Auto-complete
  • ✓ Documentation explorer
  • ✓ Query history

2. GraphQL Playground

  • ✓ Modern GraphiQL alternative
  • ✓ Better UX
  • ✓ Multiple tabs
  • ✓ Request tracing

3. Apollo Studio

  • ✓ Enterprise GraphQL platform
  • ✓ Schema registry
  • ✓ Performance monitoring
  • ✓ Team collaboration

4. Spectaql

  • ✓ Static documentation generator
  • ✓ Beautiful HTML output
  • ✓ Customizable themes

GraphQL vs REST Documentation

Aspect GraphQL REST
Schema Strongly typed schema No native schema (need OpenAPI)
Documentation Self-documenting Cần external docs
Discovery Introspection query Không có introspection
Validation Built-in type validation Manual validation
Versioning Schema evolution URL versioning (/v1, /v2)

Pros & Cons

Pros Cons
✓ Self-documenting ✗ Chỉ cho GraphQL APIs
✓ Type safety ✗ Learning curve cao
✓ Introspection ✗ Không dùng được cho REST
✓ Interactive tools ✗ Caching phức tạp hơn REST
✓ Strong ecosystem ✗ Overhead cho simple APIs

💡 Khi nào dùng GraphQL?

  • ✓ Complex data requirements
  • ✓ Multiple clients (web, mobile, IoT)
  • ✓ Nested/related data (reduce over-fetching)
  • ✓ Rapid frontend development

Khi nào dùng REST?

  • ✓ Simple CRUD operations
  • ✓ Caching requirements cao
  • ✓ File uploads/downloads
  • ✓ Team quen với REST

Essential Content

1. Getting Started

  • Quick start guide (5-10 phút để first API call)
  • Authentication setup
  • First API call example
  • Common prerequisites

2. Authentication & Authorization

  • Methods supported (API key, OAuth, JWT, Basic Auth)
  • How to obtain credentials
  • Token lifecycle
  • Example requests with auth

3. Endpoints Documentation

Mỗi endpoint cần:

  • ✓ Description (what it does)
  • ✓ HTTP method
  • ✓ URL path
  • ✓ Path/query/body parameters
  • ✓ Request examples
  • ✓ Response examples
  • ✓ Status codes
  • ✓ Error responses

4. Error Handling

  • Error format (JSON structure)
  • Common error codes
  • Troubleshooting guide
  • Error examples

5. Rate Limiting

  • Limits (requests per minute/hour)
  • Headers (X-RateLimit-Remaining, X-RateLimit-Reset)
  • Handling limits (429 status, retry logic)

6. Versioning

  • Current version
  • Deprecation policy
  • Migration guides
  • Backward compatibility

7. SDKs & Libraries

  • Official clients
  • Community libraries
  • Code examples
  • Installation guides

8. Changelog

  • Version history
  • Breaking changes
  • New features
  • Bug fixes

Writing Guidelines

  • Clear and concise: No jargon, simple language
  • Use examples liberally: Show, don't just tell
  • Consistent terminology: Same words for same concepts
  • Step-by-step tutorials: Guided walkthroughs
  • Interactive examples: Try-it-out features
  • Search functionality: Easy to find info
  • Mobile-friendly: Responsive design
  • Update regularly: Keep in sync with API

Code Examples - Multiple Languages

# cURL
curl -X GET https://api.example.com/users/123 \
  -H "Authorization: Bearer TOKEN"
// JavaScript
fetch('https://api.example.com/users/123', {
  headers: {
    'Authorization': 'Bearer TOKEN'
  }
})
.then(res => res.json())
.then(data => console.log(data));
// PHP
$ch = curl_init('https://api.example.com/users/123');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
  'Authorization: Bearer TOKEN'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$user = json_decode($response, true);
# Python
import requests

response = requests.get(
    'https://api.example.com/users/123',
    headers={'Authorization': 'Bearer TOKEN'}
)
user = response.json()
Feature OpenAPI API Blueprint RAML Postman GraphQL
Format YAML/JSON Markdown YAML JSON SDL
Learning Curve Medium Easy Medium Easy Medium
Tooling Excellent Good Good Excellent Excellent
Popularity Very High Medium Low Very High High
REST Focus Yes Yes Yes Yes No
Code Gen Yes Limited Yes Yes Yes
Interactive Yes Yes Yes Yes Yes
Testing Via tools Via Dredd Limited Built-in Via tools
Best For Enterprise APIs Simple APIs Reusable designs Testing & collaboration GraphQL APIs only

Khuyến nghị:

  • OpenAPI: Phổ biến nhất, tooling tốt nhất, nên dùng cho hầu hết REST APIs
  • Postman: Tốt cho testing và collaboration, dễ share với team
  • GraphQL: Bắt buộc nếu dùng GraphQL (không phải REST)
  • API Blueprint: Nếu thích Markdown format
  • RAML: Ít phổ biến, chỉ dùng nếu đã có existing RAML specs

Must Have (Bắt buộc)

  • Base URL và endpoints list
  • Authentication method
  • Request/response examples
  • Status codes explained
  • Error responses format
  • Rate limits information

Should Have (Nên có)

  • Quick start guide
  • SDKs/libraries links
  • Interactive playground
  • Code examples (multiple languages)
  • Changelog
  • Migration guides
  • Pagination documentation
  • Filtering/sorting documentation

Nice to Have (Tốt nếu có)

  • Video tutorials
  • Use case examples
  • Community forum
  • Webhooks documentation
  • Postman collection
  • OpenAPI spec download
  • Sandbox environment
  • API status page