fastapi 用户指南(路径参数、查询参数、请求体)
生活随笔
收集整理的這篇文章主要介紹了
fastapi 用户指南(路径参数、查询参数、请求体)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 第一步
- 1.1 小結
- 2. 路徑參數
- 2.1 順序很重要
- 2.2 預設值
- 2.3 包含路徑的路徑參數
- 3. 查詢參數
- 3.1 查詢參數類型轉換
- 4. 請求體
learn from https://fastapi.tiangolo.com/zh/tutorial/
1. 第一步
- pip install fastapi[all]
- http 操作:
POST:創建數據。
GET:讀取數據。
PUT:更新數據。
DELETE:刪除數據。
@my_app.get("/") 告訴 FastAPI 在它下方的函數負責處理如下訪問請求:
- 請求路徑為 /
- 使用 get 操作
函數可以返回一個 dict、list,像 str、int 一樣的單個值,等等。還可以返回 Pydantic 模型
1.1 小結
- 導入 FastAPI
- 創建一個 app 實例
- 編寫一個路徑操作裝飾器(如 @app.get("/"))
- 編寫一個路徑操作函數(如上面的 def root(): ...)
- 運行開發服務器(如 uvicorn main:app --reload)
2. 路徑參數
- 函數參數,與 { } 內的名字,保持一致
- 參數類型限制 : type,參數類型不匹配會報錯
- 文檔 http://127.0.0.1:8000/docs,http://127.0.0.1:8000/redoc
2.1 順序很重要
@my_app.get("/users/me") async def read_user_me():return {"user_id": "the current user"}@my_app.get("/users/{user_id}") async def read_user(user_id: str):return {"user_id": user_id}
如果上面,兩個函數順序反了,如下結果
2.2 預設值
- 使用 Enum
可以使用 model_name.value 或通常來說 your_enum_member.value 來獲取實際的值
2.3 包含路徑的路徑參數
- 參數 { } 內 參數名:path :前后均沒有空格,不加 :path 無法識別 帶有/ 的路徑參數
3. 查詢參數
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]@app.get("/items") async def read_item(skip: int = 0, limit: int = 10):return fake_items_db[skip:skip + limit]- 使用 ? 開始,參數間使用 & 分割
3.1 查詢參數類型轉換
from typing import Optional@app.get("/items/{item_id}") async def read_item(item_id: str, q: Optional[str] = None, short: bool = False):item = {"item_id" : item_id}if q:item.update({"q" : q})if not short:item.update({"description": "This is an amazing item that has a long description"})return item輸入 short=,后面是 1,True, true, yes, on, On, YES 任意變形體都是一樣的效果,都是 true
- 多個參數的順序沒影響,通過名字查找的
- item_id: str, user_id: int, 更換兩個變量的位置,沒有關系
4. 請求體
請求體是客戶端發送給 API 的數據
響應體是 API 發送給客戶端的數據
使用 Pydantic 模型來聲明請求體
from typing import Optionalfrom Pinyin2Hanzi import Item from fastapi import FastAPI from pydantic import BaseModelclass Item(BaseModel):name: strdescription: Optional[str]=Noneprice:floattax:Optional[float] = Noneapp = FastAPI()@app.put("/items/{item_id}") async def create_item(item_id: int, item: Item, q: Optional[str] = None):result = {"item_id": item_id, **item.dict()}if q:result.update({"q": q})return result- 還可以同時聲明請求體、路徑參數和查詢參數。
函數參數將依次按如下規則進行識別:
1.如果在路徑中也聲明了該參數,它將被用作路徑參數
2.如果參數屬于單一類型(比如 int、float、str、bool 等)它將被解釋為查詢參數
3.如果參數的類型被聲明為一個 Pydantic 模型,它將被解釋為請求體
總結
以上是生活随笔為你收集整理的fastapi 用户指南(路径参数、查询参数、请求体)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 1864. 构成交替字
- 下一篇: LeetCode MySQL 1777.