https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/
Path Parameters and Numeric Validations - FastAPI
Path Parameters and Numeric Validations In the same way that you can declare more validations and metadata for query parameters with Query, you can declare the same type of validations and metadata for path parameters with Path. Import Path First, import P
fastapi.tiangolo.com
* 이전 포스팅에서 Query를 이용해 쿼리 매개변수에 더 많은 검증과 메타데이터를 선언하는 방법을 알아보았다.
동일하게, 이번엔 Path 를 사용해 Path Parameters에 검증과 메타데이터를 선언해보자.
1. Import Path
먼저 fastapi에서 Path를 import한다(Annotaed도 import).
from typing import Annotated
from fastapi import FastAPI, Path, Query
2. Declare metadata
Path parameter는, Query에서 선언할 때 썼던 모든 파라미터와 동일한 방법으로 선언할 수 있다.
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get")],
q: Annotated[str | None, Query(alias="item-query")] = None,
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
Path에 title이라는 metadata를 주었다.
Path는 항상 required하기 때문에(경로의 일부분이라) 아래와 같이 항상 ... 를 표시해 주어야 한다.
item_id: Annotated[int, Path(title="The ID of the item to get")] = ...
None이나 default value로 선언했다고 하더라도, 어떤 것에도 효과를 미치지 않을 것이다. 여전히 필수이다.
3. Order the parameters as i need
*Annotated 라이브러리를 사용한다면 그렇게 중요하지 않을 수 있다.
str형인 q를 필수매개변수로 선언하자고 해보자. 그리고 파라미터에 관해 다른 아무것도 선언할 필요가 없다고 해 보자(Query를 사용할 필요가 없다)
그러나 Path는 item_id 경로매개변수를 위해 여전히 필요하다. 그리고 어떤 다른 이유때문에 Annotated를 사용하고 싶지 않다고 해보자.
내가 기본값이 없는 value에 값을 전달하기 전 다른 value에 먼저 기본값을 넣는다고 하면 파이썬은 불평한다.
여기서 나는 이들의 순서를 기본값이 없는 매개변수가 먼저 값을 가지게 재정렬할 수 있다(그래야 될 것이다).
(순서 재정렬은 FastAPI에서는 큰 상관이 없다. 알아서 탐지하고 매칭해줄거라 순서를 크게 신경쓰지 않는다.)
따라서 함수를 다음과 같이 선언하자:
(*아래는 Annotated를 사용하지 않은 예제이다. 가능하다면 Annotated를 사용하는 것을 권장)
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(q: str, item_id: int = Path(title="The ID of the item to get")):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
아래처럼 Annotated를 사용하면 위에 기술한 문제가 발생하지 않는다. 내가 Query()나 Path()에 기본값을 쓰는 것에 신경쓰지 않기 때문.
from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
q: str, item_id: Annotated[int, Path(title="The ID of the item to get")]
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
3-1. tricks for Ordering the parameters
*이 역시 Annotated를 사용하면 아마도 중요하지 않다.
- q query를 Query()혹은 다른 기본값 없이 선언하고 싶을 때
- Path()를 이용하여 path 매개변수 item_id를 사용하고 싶을 때
- 이들을 다른 순서를 가지게 하고 싶을 때
- 그리고 Annotated를 사용하지 않을 때...
파이썬에서는 ' * ' 키워드를 통해 해결할 수 있다. 이를 따르는 매개변수들은 kwargs로 알려진 keywords - arguments(키-값 쌍)이라는 제약을 걸어준다. defaults value가 없어도 동일하다.
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(*, item_id: int = Path(title="The ID of the item to get"), q: str):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
물론 아래와 같이 Annotated를 사용한다면 *같은건 사용하지 않아도 된다.
이쯤되면 Python 3.9+에선 Annotated를 무조건 사용하라 권장하는 것 같다.
from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get")], q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
4. Number validations: greater than or equal
Query와 Path(다른것도 있는데 나중에 볼 수 있다)를 가지고 number constraints를 선언할 수 있다.
ge=1을 보면, item_id는 정수 수여야 하고 " g reater than or e qual" to 1 .임을 명시한다.
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get", ge=1)], q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
* ge가 크거나 같음을 의미하듯, le는 작거나 같음을 의미한다.
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get", gt=0, le=1000)],
q: str,
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
이렇게 item_id 가 [0, 1000]에 속하는 int 형이어야 함을 검증할 수 있다.
* gt : g reater than; 큰
* lt : l ess than; 작은
float(실수형)도 검증할 수 있다.
5. Reference
https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations
'프레임워크 > FastAPI' 카테고리의 다른 글
[FastAPI] FastAPI [7] Body - Fields (0) | 2023.03.27 |
---|---|
[FastAPI] FastAPI [6] Body - Multiple Parameters (0) | 2023.03.27 |
[FastAPI] FastAPI [4] Query Parameters and String Validations (0) | 2023.03.19 |
[FastAPI] FastAPI [3] - Request Body (0) | 2023.03.13 |
[FastAPI] FastAPI [2] Tutorial (1) | 2023.03.12 |