前言
- form-data 表單格式的請求數據其實也是挺常見的
- FastAPI 通過 Form 來聲明參數需要接收表單數據
安裝 python-multipart
要用 Form,需要先安裝這個庫
pip install python-multipart
Form
Form 是繼承自 Body,所以可以定義和 Body 相同的元數據以及額外的驗證

簡單的栗子
import uvicorn from fastapi import FastAPI, Form app = FastAPI() @app.post("/login/") async def login(username: str = Form(...), password: str = Form(...)): return {"username": username, "password": password} if __name__ == "__main__": uvicorn.run(app="10_Form:app", host="127.0.0.1", port=8080, reload=True, debug=True)
在 OAuth2 規范的一種使用方式(密碼流)中,需要將用戶名、密碼作為表單字段發送,而不是 JSON【后面會詳解 OAuth2】
重點
- 請求發送表單格式的數據,請求頭通常會包含 Content-Type: application/x-www-form-urlencoded
- 如果需要發送包含文件的表單數據, 會變成 Content-Type: multipart/form-data
正確傳參的請求結果

請求頭

查看 Swagger API 文檔

- 可以看到接口文檔中,接口的 Content-type 默認也是 application/x-www-form-urlencoded
- 注意:在 Swagger 上無法測試上傳文件,因為 Content-type 無法切換到 multipart/form-data ,如果需要測試,要用 FastAPI 提供的 File 哦
- File 詳細教程
