POST 操作

FastAPI 入门

Matt Eckerle

Software and Data Engineering Leader

GET 与 POST 对比

GET 操作

  • 传统用途:请求对象信息

  • 参数通过查询字符串发送

  • 可直接从浏览器发送

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

POST 操作

  • 传统用途:创建新对象

  • 参数可在查询字符串和请求体中发送

  • 需要应用或框架

    • cURLrequests
api = "http://moviereviews.co/reviews/"
body = {"text": "A great movie!"}
response = requests.post(api, json=body)
FastAPI 入门

HTTP 请求体

  • 数据位于 HTTP 请求头之后
  • 头信息指定请求体编码
  • 支持嵌套数据结构
  • API 最常用编码为 JSON 和 XML
  • FastAPI 的默认编码是 JSON

JSON 示例

# 为影评创建一条记录
{"movie": "The Neverending Story",
 "review": {"num_stars": 4,
            "text": "Great movie!",
            "public": true}}
FastAPI 入门

使用 pydantic 的 BaseModel

pydantic:用于定义请求与响应体模式的接口

注意

我们将 Review 嵌入到 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
FastAPI 入门

处理 POST 操作

用于创建新影评的 POST 端点:

  • 端点:/reviews
  • 输入:MovieReview(上一页)
  • 输出:db_review(在他处定义)
@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
FastAPI 入门

Passons à la pratique !

FastAPI 入门

Preparing Video For Download...