Cơ BảnFastAPI iconFastAPI

FastAPI response status code nên thiết kế thế nào?

Status code nên phản ánh kết quả API: 200 cho đọc/update thành công, 201 cho create, 204 cho delete/no content, 400 cho input semantic sai, 401 chưa xác thực, 403 không đủ quyền, 404 không tồn tại, 409 conflict.

Ví dụ:

python
@app.post("/users", status_code=status.HTTP_201_CREATED, response_model=UserRead)
async def create_user(payload: UserCreate):
    return await service.create(payload)

Không nên dùng 200 cho mọi thứ vì client, monitoring và retry policy sẽ mất tín hiệu.

Xem toàn bộ FastAPI cùng filter theo level & chủ đề con.

Mở danh sách FastAPI