fastapi 用户指南(路径参数、查询参数、请求体)
生活随笔
收集整理的這篇文章主要介紹了
fastapi 用户指南(路径参数、查询参数、请求体)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 1. 第一步
- 1.1 小結(jié)
- 2. 路徑參數(shù)
- 2.1 順序很重要
- 2.2 預(yù)設(shè)值
- 2.3 包含路徑的路徑參數(shù)
- 3. 查詢參數(shù)
- 3.1 查詢參數(shù)類型轉(zhuǎn)換
- 4. 請(qǐng)求體
learn from https://fastapi.tiangolo.com/zh/tutorial/
1. 第一步
- pip install fastapi[all]
- http 操作:
POST:創(chuàng)建數(shù)據(jù)。
GET:讀取數(shù)據(jù)。
PUT:更新數(shù)據(jù)。
DELETE:刪除數(shù)據(jù)。
@my_app.get("/") 告訴 FastAPI 在它下方的函數(shù)負(fù)責(zé)處理如下訪問請(qǐng)求:
- 請(qǐng)求路徑為 /
- 使用 get 操作
函數(shù)可以返回一個(gè) dict、list,像 str、int 一樣的單個(gè)值,等等。還可以返回 Pydantic 模型
1.1 小結(jié)
- 導(dǎo)入 FastAPI
- 創(chuàng)建一個(gè) app 實(shí)例
- 編寫一個(gè)路徑操作裝飾器(如 @app.get("/"))
- 編寫一個(gè)路徑操作函數(shù)(如上面的 def root(): ...)
- 運(yùn)行開發(fā)服務(wù)器(如 uvicorn main:app --reload)
2. 路徑參數(shù)
- 函數(shù)參數(shù),與 { } 內(nèi)的名字,保持一致
- 參數(shù)類型限制 : type,參數(shù)類型不匹配會(huì)報(bào)錯(cuò)
- 文檔 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}
如果上面,兩個(gè)函數(shù)順序反了,如下結(jié)果
2.2 預(yù)設(shè)值
- 使用 Enum
可以使用 model_name.value 或通常來說 your_enum_member.value 來獲取實(shí)際的值
2.3 包含路徑的路徑參數(shù)
- 參數(shù) { } 內(nèi) 參數(shù)名:path :前后均沒有空格,不加 :path 無法識(shí)別 帶有/ 的路徑參數(shù)
3. 查詢參數(shù)
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]- 使用 ? 開始,參數(shù)間使用 & 分割
3.1 查詢參數(shù)類型轉(zhuǎn)換
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
- 多個(gè)參數(shù)的順序沒影響,通過名字查找的
- item_id: str, user_id: int, 更換兩個(gè)變量的位置,沒有關(guān)系
4. 請(qǐng)求體
請(qǐng)求體是客戶端發(fā)送給 API 的數(shù)據(jù)
響應(yīng)體是 API 發(fā)送給客戶端的數(shù)據(jù)
使用 Pydantic 模型來聲明請(qǐng)求體
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- 還可以同時(shí)聲明請(qǐng)求體、路徑參數(shù)和查詢參數(shù)。
函數(shù)參數(shù)將依次按如下規(guī)則進(jìn)行識(shí)別:
1.如果在路徑中也聲明了該參數(shù),它將被用作路徑參數(shù)
2.如果參數(shù)屬于單一類型(比如 int、float、str、bool 等)它將被解釋為查詢參數(shù)
3.如果參數(shù)的類型被聲明為一個(gè) Pydantic 模型,它將被解釋為請(qǐng)求體
總結(jié)
以上是生活随笔為你收集整理的fastapi 用户指南(路径参数、查询参数、请求体)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 1864. 构成交替字
- 下一篇: LeetCode MySQL 1777.