Mô hình request và response

Triển khai AI vào môi trường sản xuất với FastAPI

Matt Eckerle

Software and Data Engineering Leader

Cấu trúc request và response trong API

Cấu trúc request
  • Dữ liệu client gửi đến API
  • Thường gồm:
    • HTTP method (GET, POST, v.v.)
    • Headers
    • Query parameters
    • Request body

http://localhost:8000/users/? [email protected]

  • :8000: Số cổng. FastAPI mặc định dùng 8000.
  • /users/: Đường dẫn tới endpoint cụ thể.
  • ?: Bắt đầu phần query parameters.
  • `[email protected]`: Query parameter. Ở đây truyền email vào endpoint.
Triển khai AI vào môi trường sản xuất với FastAPI

Cấu trúc response

  • Dữ liệu API trả về cho client
    • JSON payload chứa thông tin người dùng
  • Thường gồm:
    • Status code (200 OK, 404 Not Found, v.v.)
    • Headers
    • Response body (dữ liệu yêu cầu hoặc kết quả thao tác)
HTTP/1.1 200 OK
date: Fri, 18 Oct 2024 12:34:56 GMT
server: uvicorn
content-length: 76
content-type: application/json

{
  "username": "johndoe",
  "email": "[email protected]",
  "age": 30
}
Triển khai AI vào môi trường sản xuất với FastAPI

Mô hình Pydantic

  • Tạo User
  • Sử dụng Pydantic
from pydantic import BaseModel
class User(BaseModel):
    username: str
    email: str
    age: int
  • Kế thừa từ BaseModel
  • Khai báo thuộc tính kèm kiểu dữ liệu
  • Tự động kiểm tra hợp lệ theo kiểu
Triển khai AI vào môi trường sản xuất với FastAPI

Lỗi xác thực

from pydantic import ValidationError
try:
    invalid_user = User(username="john_doe", email="[email protected]", 
                        age="thirty")
    print("Invalid User:", invalid_user)
except ValidationError as e:
    print("Validation Error:", e)
Validation Error: 1 validation error for User age
Input should be a valid integer, unable to parse string as an integer 
[type=int_parsing, input_value='thirty', input_type=str]
Triển khai AI vào môi trường sản xuất với FastAPI

Dùng Pydantic trong FastAPI

from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()

class User(BaseModel): username: str email: str age: int
@app.post("/users", response_model=User)
async def create_user(user: User): return user
  • Dùng model làm response_model
  • Dùng model cho type hint tham số
  • Tự động kiểm tra request
  • De/serialize request/response
  • Tạo tài liệu API
Triển khai AI vào môi trường sản xuất với FastAPI

Định dạng request và response

curl -X 'POST' \
  'http://localhost:8000/users/' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "username": "john_doe",
  "email": "[email protected]",
  "age": 30
  }'

 

{
  "username": "john_doe",
  "email": "[email protected]",
  "age": 30
}
Triển khai AI vào môi trường sản xuất với FastAPI

Cùng luyện tập nào!

Triển khai AI vào môi trường sản xuất với FastAPI

Preparing Video For Download...