Nhập môn FastAPI
Matt Eckerle
Software and Data Engineering Leader
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)
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
cURL, requestsapi = "http://moviereviews.co/reviews/"
body = {"text": "A great movie!"}
response = requests.post(api, json=body)
Ví dụ JSON
# Tạo bản ghi đánh giá phim
{"movie": "The Neverending Story",
"review": {"num_stars": 4,
"text": "Great movie!",
"public": true}}
pydantic: giao diện để định nghĩa schema cho request và response body
Lưu ý
Ta lồng
Reviewbên trongMovieReview
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
Endpoint POST để tạo đánh giá phim mới:
/reviewsMovieReview (từ slide trước)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
Nhập môn FastAPI