Nguyên tắc Thiết kế API
- Giữ mức độ chi tiết và số lượng endpoint hợp lý
- Tên gọi đơn giản, dễ hiểu và nhất quán
- Ưu tiên thiết kế trước khi triển khai mã
Thiết kế URL
Phương thức HTTP
GET: Đọc dữ liệu
POST: Tạo mới tài nguyên
PUT: Cập nhật toàn bộ
PATCH: Cập nhật một phần
DELETE: Xóa tài nguyên
Quy tắc Đặt tên
| Đơn giản | Phức tạp |
| captcha | get-captcha-image |
| info | get-user-info |
| cars | retrieve-all-cars |
| Tốt | Xấu |
| delete | delete-system-user |
| add | add-distribution |
| update | update-distribution |
| get | app-get-by-number |
Tránh tạo quá nhiều endpoint. Mỗi controller không vượt quá 6 endpoint. Hợp nhất các chức năng tương đồng để giảm độ phức tạp.
HTTP Status Codes
2xx: Thành công
4xx: Lỗi client
5xx: Lỗi server
200: OK
201: Created
400: Bad Request
401: Unauthorized
403: Forbidden
404: Not Found
405: Method Not Allowed
415: Unsupported Media Type
500: Internal Server Error
503: Service Unavailable
Định dạng Phản hồi
{
"code": 200,
"message": "Thao tác thành công",
"data": {}
}
Lỗi Server
{
"code": 500,
"message": "Lỗi nội bộ",
"data": null
}
Xác thực Thất bại
{
"code": 400,
"message": "Lỗi xác thực",
"data": [
"Tên không được để trống",
"Độ dài phải từ 1-50 ký tự"
]
}
Danh sách
{
"code": 200,
"message": "Thành công",
"data": {
"items": [
{
"id": 5,
"name": "Trắng",
"priority": 0,
"updatedAt": "2019-07-11T01:11:12.849Z"
}
],
"total": 19
}
}
Đơn đối tượng
{
"code": 200,
"message": "Thành công",
"data": {
"id": 4,
"name": "Nâu",
"priority": 0,
"updatedAt": "2019-07-11T01:06:20.062Z"
}
}
Cấu trúc Cây
{
"code": 200,
"message": "Thành công",
"data": [
{
"id": 365,
"text": "Stone Blocks",
"parentId": 0,
"expanded": true,
"hasChildren": true,
"children": [
{
"id": 366,
"text": "Marble Blocks",
"parentId": 365,
"expanded": true,
"hasChildren": false
}
]
}
]
}
Danh sách Dropdown
{
"code": 200,
"message": "Thành công",
"data": [
{
"label": "Việt Nam",
"value": "VN"
},
{
"label": "Hoa Kỳ",
"value": "US"
}
]
}
Thực thi Gọi API
// GET với tham số
var request = new RestRequest("/v1/users", Method.Get);
request.AddParameter("page", 1);
var response = client.Execute(request);
// POST
var payload = new { name = "Test" };
var response = client.Execute(new RestRequest("/v1/users", Method.Post) {
RequestBody = JsonConvert.SerializeObject(payload)
});