Backend Framework/FastAPI

02. FastAPI - Request Parameter

Python Developer 2025. 4. 22. 17:12

FastAPI에서 Path Parameter와 Query Parameter 사용법

FastAPI에서는 경로 매개변수(Path Parameters)와 쿼리 매개변수(Query Parameters)를 선언적으로 정의할 수 있으며, 이를 통해 요청값을 유효성 검사하고 문서화할 수 있다


1. Path Parameter

경로 매개변수는 URL 경로의 일부로, 중괄호 {}를 사용하여 정의한다

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

요청 예시:

  • http://localhost:8000/items/3 → 정상
  • http://localhost:8000/items/abc → 422 Unprocessable Entity (item_id는 int형이므로 문자열은 오류 발생)

2. 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_items(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]

요청 예시:

  • http://localhost:8000/items/?skip=1&limit=2[{"item_name": "Bar"}, {"item_name": "Baz"}]
  • http://localhost:8000/items/ → 기본값 적용

3. 필수 Query Parameter

기본값이 없는 쿼리 매개변수는 필수로 간주되어 반드시 값을 전달해야 한다.

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/")
async def read_items(q: str):
    return {"q": q}

요청 예시:

  • http://localhost:8000/items/?q=hello → 정상
  • http://localhost:8000/items/ → 422 오류 발생

4. 선택적 Query Parameter

선택적 매개변수는 기본값을 None으로 설정하거나, Optional을 사용할 수 있다.

from typing import Optional
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/")
async def read_items(q: Optional[str] = None):
    if q:
        return {"q": q}
    return {"q": "No query provided"}

요청 예시:

  • http://localhost:8000/items/{ "q": "No query provided" }
  • http://localhost:8000/items/?q=search{ "q": "search" }

5. Path + Query Parameter 함께 사용

경로 매개변수와 쿼리 매개변수를 동시에 사용할 수 있다.

from typing import Optional
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: Optional[str] = None):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}

요청 예시:

  • http://localhost:8000/items/3{ "item_id": 3 }
  • http://localhost:8000/items/3?q=detail{ "item_id": 3, "q": "detail" }

'Backend Framework > FastAPI' 카테고리의 다른 글

03. FastAPI - Request Body(JSON), Form(HTML) 처리  (0) 2025.04.22
01. FastAPI - 시작하기  (0) 2025.04.21