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.
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.
Note: "Swagger" giờ chỉ tools (Swagger UI, Swagger Editor), còn "OpenAPI" là 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: []
| 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) |
Interactive documentation tự động generated từ OpenAPI spec
Online editor để viết OpenAPI specs
Alternative UI, clean và responsive
Generate client SDKs và server stubs
API Blueprint là một Markdown-based format để document REST APIs. Nó sử dụng Markdown syntax, dễ đọc và dễ viết.
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"
}
| 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 (RESTful API Modeling Language) là một YAML-based language để describe REST APIs với focus vào reusability.
#%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"
| 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 |
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à 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.
{
"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"
}
]
}
// 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");
});
// Set timestamp
pm.environment.set("timestamp", Date.now());
// Generate token
const token = CryptoJS.HmacSHA256("message", "secret");
pm.environment.set("token", token.toString());
// Development
{
"baseUrl": "http://localhost:3000",
"token": "dev_token_123"
}
// Production
{
"baseUrl": "https://api.example.com",
"token": "prod_token_456"
}
# 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 |
|---|---|
| ✓ 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 |
GraphQL Schema là type system để define GraphQL APIs. Schema language (SDL - Schema Definition Language) là documentation format native của GraphQL.
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.
"""
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
}
query GetUserWithPosts($userId: ID!) {
user(id: $userId) {
id
name
email
posts {
id
title
publishedAt
}
}
}
# Variables
{
"userId": "123"
}
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) {
id
name
email
createdAt
}
}
# Variables
{
"input": {
"name": "Nguyễn Văn A",
"email": "vana@example.com"
}
}
| 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 |
|---|---|
| ✓ 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 |
Mỗi endpoint cần:
# 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 |