Các thao tác POST

Nhập môn FastAPI

Matt Eckerle

Software and Data Engineering Leader

GET so với POST

Các thao tác GET

  • Mục đích truyền thống: yêu cầu thông tin về một đối tượng

  • Tham số gửi qua query string

  • Có thể gửi từ trình duyệt web

api = "http://moviereviews.co/reviews/1"
response = requests.get(api)

Các thao tác POST

  • Mục đích truyền thống: tạo đối tượng mới

  • Tham số gửi qua query string và cả request body

  • Cần ứng dụng hoặc framework

    • ví dụ: cURL, requests
api = "http://moviereviews.co/reviews/"
body = {"text": "A great movie!"}
response = requests.post(api, json=body)
Nhập môn FastAPI

HTTP Request Body

  • Dữ liệu gửi sau phần header của yêu cầu HTTP
  • Header chỉ định cách mã hóa body
  • Hỗ trợ cấu trúc lồng nhau
  • JSON và XML là mã hóa phổ biến cho API
  • JSON là mặc định của FastAPI

Ví dụ JSON

# Tạo bản ghi đánh giá phim
{"movie": "The Neverending Story",
 "review": {"num_stars": 4,
            "text": "Great movie!",
            "public": true}}
Nhập môn FastAPI

Dùng BaseModel của pydantic

pydantic: giao diện để định nghĩa schema cho request và response body

Lưu ý

Ta lồng Review bên trong MovieReview

from pydantic import BaseModel

class Review(BaseModel):
    num_stars: int
    text: str
    public: bool = False

class MovieReview(BaseModel):
    movie: str
    # Nest Review in MovieReview
    review: Review
Nhập môn FastAPI

Xử lý thao tác POST

Endpoint POST để tạo đánh giá phim mới:

  • Endpoint: /reviews
  • Input: MovieReview (từ slide trước)
  • Output: db_review (định nghĩa ở nơi khác)
@app.post("/reviews", response_model=DbReview)
def create_review(review: MovieReview):
    # Persist the movie review to the database
    db_review = crud.create_review(review)
    # Return the review including database ID
    return db_review
1 https://fastapi.tiangolo.com/tutorial/sql-databases/#crud-utils
Nhập môn FastAPI

Ayo berlatih!

Nhập môn FastAPI

Preparing Video For Download...