4.9 KiB
4.9 KiB
Swagger API Documentation
🚀 Truy cập Swagger UI
Sau khi start server, truy cập:
http://localhost:3000/api-docs
📚 Swagger JSON
Lấy định nghĩa OpenAPI 3.0 JSON:
http://localhost:3000/api-docs.json
🔐 Authentication trong Swagger UI
Bước 1: Login để lấy token
- Mở endpoint
POST /api/auth/login - Click "Try it out"
- Nhập:
{
"username": "student001",
"password": "password123"
}
- Click "Execute"
- Copy
tokentừ response
Bước 2: Authorize
- Click nút "Authorize" 🔓 ở góc trên bên phải
- Nhập token vào ô bearerAuth:
<token_vừa_copy> - Click "Authorize"
- Click "Close"
Bước 3: Test các API cần authentication
Giờ bạn có thể test các endpoint như:
GET /api/auth/mePOST /api/auth/logoutPOST /api/auth/verify-token
Token sẽ tự động được thêm vào header Authorization: Bearer <token>
📋 Endpoints đã document
Authentication APIs
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /api/auth/login |
Đăng nhập | ❌ |
| POST | /api/auth/register |
Đăng ký tài khoản | ❌ |
| POST | /api/auth/verify-token |
Xác thực token | ✅ |
| POST | /api/auth/logout |
Đăng xuất | ✅ |
| GET | /api/auth/me |
Lấy thông tin user hiện tại | ✅ |
🎨 Tính năng Swagger UI
- ✅ Persist Authorization: Token được lưu tự động sau khi authorize
- ✅ Display Request Duration: Hiển thị thời gian response
- ✅ Filter: Tìm kiếm endpoints nhanh
- ✅ Syntax Highlight: Code highlighting với theme Monokai
- ✅ Try it out: Test API trực tiếp từ UI
📖 Response Examples
Login Success Response
{
"success": true,
"message": "Đăng nhập thành công",
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "123e4567-e89b-12d3-a456-426614174000",
"username": "student001",
"email": "student@example.com",
"profile": {
"full_name": "Nguyễn Văn A",
"avatar_url": "https://...",
"primary_role_info": {
"role_code": "student",
"role_name": "Học sinh",
"school": {
"id": "uuid",
"name": "SENA Hà Nội"
},
"class": {
"id": "uuid",
"name": "K1A"
}
}
},
"role": {
"role_id": "uuid",
"role_code": "student",
"role_name": "Học sinh",
"school": { "id": "uuid", "name": "SENA HN" },
"class": { "id": "uuid", "name": "K1A" }
},
"permissions": [
{
"code": "view_own_grades",
"name": "Xem điểm của mình",
"resource": "grades",
"action": "view"
}
],
"last_login": "2026-01-19T10:30:00.000Z",
"login_count": 15
}
}
}
Error Response
{
"success": false,
"message": "Username hoặc password không đúng",
"attemptsLeft": 3
}
🔧 Cấu hình Swagger
File config: config/swagger.js
Thêm endpoint mới
Thêm Swagger JSDoc comment vào controller:
/**
* @swagger
* /api/your-endpoint:
* get:
* tags: [YourTag]
* summary: Your summary
* description: Your description
* responses:
* 200:
* description: Success
*/
async yourMethod(req, res) {
// Your code
}
Thêm schema mới
Trong config/swagger.js, thêm vào components.schemas:
YourSchema: {
type: 'object',
properties: {
id: { type: 'string', format: 'uuid' },
name: { type: 'string' },
}
}
🐛 Troubleshooting
Swagger UI không hiển thị
- Check server đã start:
npm run dev - Check port 3000 không bị chiếm
- Check console có error không
Token không work sau authorize
- Đảm bảo format:
Bearer <token>(không có dấu ngoặc) - Token phải valid (chưa expire sau 24h)
- Check response từ login có token không
CSP errors trong console
Đã được fix trong app.js bằng cách thêm:
scriptSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:", "validator.swagger.io"]
📝 Best Practices
- Luôn test API trong Swagger trước khi code client
- Update documentation khi thêm/sửa endpoint
- Dùng "Try it out" để verify request/response schema
- Copy curl command từ Swagger để debug
- Export Swagger JSON để generate client SDK
🎯 Next Steps
Để thêm documentation cho các controller khác:
- Mở file controller (vd:
controllers/studentController.js) - Thêm Swagger JSDoc comments
- Restart server
- Refresh Swagger UI
Last updated: January 19, 2026
Swagger Version: OpenAPI 3.0.0