Python/Django Ninja

[Django Ninja] Path Variable & Query Parameter 사용 방법

yubi5050 2023. 6. 3. 14:35

1. Path Variable - 기본

# Case 1. Path Variable
@api.get("/problem/{problem_id}", response=ProblemOut)
def get_problem(request, problem_id:int):
    return Problem.object.get(problem_id=problem_id)

 

2. Path Variable - 상위 Router

상위 Router(or api)에 Path Variable이 붙어 있는 경우, Path() 를 사용하여 받는다.

Path(...) 를 명시하지 않으면, Query Parameter로 인식된다.

# Case 2. Path Variable - Router
from ninja import NinjaAPI
api = NinjaAPI()
example_router = Router()
api.add_router("/example/{example_id}", example_router)

@example_router.get("/problem/{problem_id}", response=ProblemOut)
def get_problem(request, example_id:int = Path(...), problem_id:int):
    return Problem.object.get(problem_id=problem_id, example_id=example_id)

 

3. Query Parmeter

# Case 3. Query Parameter

# endpoint : http://127.0.0.1:8000/problem/3?name=수학&stage=5
@api.get("/problem/{problem_id}", response=ProblemOut)
def get_problem(request, problem_id:int, name:str, stage:int):
    return Problem.objects.get(problem_id=problem_id, name=name, stage=stage)

 

4. Query Parmeter (with. Schema)

Query Parameter를 params란 Schema 객체로 받는다.

parmas를 사용하는 이유는 들어온 값에 대한 validation, 값 변환 등.. 의 추가 작업을 거칠 수 있기 때문이다.

# Case 4. Query Parameter (with. Schema)
# endpoint : http://127.0.0.1:8000/problem/3?name=수학&stage=5

class ProblemIn(Schema):
    name:str
    stage: int

@api.get("/problem/{problem_id}", response=ProblemOut)
def get_problem(request, problem_id:int, params:ProblemIn):
    return Problem.objects.get(problem_id=problem_id, name=params.name, stage=params.stage)

 

5. Payload (Body)

payload 즉 body를 Schema로 받는 방법이다.

# Case 5. Payload (Body)

class ProblemIn(Schema):
    name:str
    stage: int
    
@api.post("/problem/create")
def create_problem(request, payload: ProblemIn):
    Problem.objects.create(**payload.dict())
    return {"success": True}