경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언할 때, "query" parameter로 자동 해석한다.
쿼리는 URL에서 ? 후에 나오고 &으로 구분되는 key-value 쌍의 집합
from fastapi import FastAPI
app = FastAPI()
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]
위와 같이 적으면, skip = 0, limit = 10은 기본값이다.
선택적 매개변수
from typing import Union
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Union[str, None] = None):
if q:
return {"item_id": item_id, "q": q}
return {"item_id": item_id}
q는 선택적이며, 기본값으로 None값이 된다.
from typing import Union
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Union[str, None] = 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
위와 같이 형변환도 알아서 된다.
특정 순서로 선언할 필요 없다.
from typing import Union
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
user_id: int, item_id: str, q: Union[str, None] = None, short: bool = False
):
item = {"item_id": item_id, "owner_id": user_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
필수 쿼리 매개변수
경로가 아닌 매개변수에 대한 기본값을 선언할 때, None으로 기본값을 설정하지 않은 경우, 필수 쿼리 매개변수가 된다.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_user_item(item_id: str, needy: str):
item = {"item_id": item_id, "needy": needy}
return item
섞어서 써도 무방하다.
'Framework, Library > Fast api' 카테고리의 다른 글
| [Fast api] Query Parameters and String Validations (0) | 2023.04.27 |
|---|---|
| [Fast_api] Request Body (0) | 2023.04.27 |
| [Fast_api] 경로 매개변수 (0) | 2023.04.27 |
| [Fast_api] start (0) | 2023.04.27 |
| [Fast_api] fast_api란? (0) | 2023.04.24 |