查詢參數處理
## FastAPI 查詢參數的觀念
查詢參數(Query Parameters)是放在 URL `?` 後面的參數,格式通常是:
```text
/path?參數1=值1&參數2=值2
```
例如:
```text
/items?skip=0&limit=10
```
在 FastAPI 中,只要把函式參數宣告在路徑函式中,且沒有出現在路徑模板中,FastAPI 就會將它視為查詢參數。
FastAPI 也會根據 Python 型別標註自動進行:
- 參數型別轉換
- 必填欄位檢查
- 輸入格式驗證
- 自動產生 Swagger API 文件
---
## 範例一:接受基本的查詢參數
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/items")
def get_items(skip: int = 0, limit: int = 10):
return {
"skip": skip,
"limit": limit
}
```
啟動伺服器:
```bash
uvicorn main:app --reload
```
呼叫方式:
```text
http://127.0.0.1:8000/items?skip=20&limit=5
```
回應:
```json
{
"skip": 20,
"limit": 5
}
```
其中:
```python
skip: int = 0
limit: int = 10
```
表示:
- `skip` 必須是整數,預設值為 `0`
- `limit` 必須是整數,預設值為 `10`
- 如果沒有提供查詢參數,也可以正常呼叫:
```text
http://127.0.0.1:8000/items
```
結果:
```json
{
"skip": 0,
"limit": 10
}
```
---
## 範例二:必填查詢參數與選填參數
```python
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/search")
def search_items(
keyword: str,
category: Optional[str] = None
):
return {
"keyword": keyword,
"category": category
}
```
呼叫方式:
```text
http://127.0.0.1:8000/search?keyword=book&category=tech
```
回應:
```json
{
"keyword": "book",
"category": "tech"
}
```
也可以只提供必填的 `keyword`:
```text
http://127.0.0.1:8000/search?keyword=book
```
回應:
```json
{
"keyword": "book",
"category": null
}
```
在這個例子中:
```python
keyword: str
```
沒有預設值,因此是必填查詢參數。如果沒有提供:
```text
http://127.0.0.1:8000/search
```
FastAPI 會回傳 HTTP `422 Unprocessable Entity`。
而:
```python
category: Optional[str] = None
```
表示 `category` 是選填參數,可以是字串,也可以沒有值。
---
FastAPI 會自動將查詢參數加入互動式文件,可以開啟:
```text
http://127.0.0.1:8000/docs
```
在 Swagger UI 中測試 API。
相關學習地圖、教學課程
Python 後端工程、資料庫