โมเดล Request และ Response

การ Deploy AI สู่ Production ด้วย FastAPI

Matt Eckerle

Software and Data Engineering Leader

โครงสร้าง Request และ Response ใน API

โครงสร้าง Request
  • ข้อมูลที่ client ส่งไปยัง API
  • โดยทั่วไปประกอบด้วย:
    • HTTP method (GET, POST เป็นต้น)
    • Headers
    • Query parameters
    • Request body

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

  • :8000: หมายเลข port — FastAPI ใช้ 8000 เป็นค่าเริ่มต้น
  • /users/: path ของ endpoint ที่เข้าถึง
  • ?: จุดเริ่มต้นของ query parameters
  • `[email protected]`: query parameter ที่ส่งอีเมลไปยัง endpoint
การ Deploy AI สู่ Production ด้วย FastAPI

โครงสร้าง Response

  • ข้อมูลที่ API ส่งกลับไปยัง client
    • JSON response payload พร้อมข้อมูลผู้ใช้
  • โดยทั่วไปประกอบด้วย:
    • Status code (200 OK, 404 Not Found เป็นต้น)
    • Headers
    • Response body (ข้อมูลที่ร้องขอหรือผลการดำเนินการ)
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
}
การ Deploy AI สู่ Production ด้วย FastAPI

Pydantic model

  • การสร้าง User
  • การใช้ Pydantic
from pydantic import BaseModel
class User(BaseModel):
    username: str
    email: str
    age: int
  • รับช่วงต่อจาก BaseModel
  • กำหนด attribute พร้อม type annotation
  • ตรวจสอบความถูกต้องตาม type โดยอัตโนมัติ
การ Deploy AI สู่ Production ด้วย FastAPI

Validation error

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]
การ Deploy AI สู่ Production ด้วย FastAPI

การใช้ Pydantic model ใน 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
  • ใช้โมเดลเป็น response_model
  • ใช้โมเดลเป็น type hint ของ parameter
  • ตรวจสอบ request โดยอัตโนมัติ
  • ทำ De/serialization ให้กับ request/response
  • สร้างเอกสาร API โดยอัตโนมัติ
การ Deploy AI สู่ Production ด้วย FastAPI

รูปแบบ Request และ 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
}
การ Deploy AI สู่ Production ด้วย FastAPI

มาฝึกกันเถอะ!

การ Deploy AI สู่ Production ด้วย FastAPI

Preparing Video For Download...