Python/FastAPI

FastAPI parameters: path, query, request body

thxxyj 2024. 3. 5. 15:50
728x90

1. Path Parameters

https://fastapi.tiangolo.com/tutorial/path-params/

from fastapi import FastAPI
from enum import Enum

class ModelName(str, Enum):
    alexnet = 'alexnet'
    resnet = 'resnet'
    lenet = 'lenet'

app = FastAPI()

@app.get('/models/{model_name}')
async def get_model(model_name: ModelName):
    if model_name is ModelName.alexnet:
        return {'model_name': model_name, 'message': 'Deep Leraning FTW!'}
    elif model_name == 'lenet':
        return {'model_name': model_name, 'message': 'LeCNN all the images'}
    return {'model_name': model_name, 'message': 'Have some residuals'}


# 실제 경로를 포함하는 경로 매개변수
# 실제 경로 ex) /home/johndoe/myfile.txt
# 매개변수가 가져야 하는 값이 /home/johndoe/myfile.txt와 같이 슬래시로 시작(/)해야 할 수 있습니다.
# 이 경우 URL은: /files//home/johndoe/myfile.txt이며 files과 home 사이에 이중 슬래시(//)가 생깁니다.
@app.get('/files/{file_path:path}')
async def get_file_path(file_path: str):
    return {'file_path': file_path}

 

 

2. Query Parameters

Query Parameters는 URL ? 뒤에 나오고, &으로 구분되는 key:value 쌍이다.

https://fastapi.tiangolo.com/tutorial/query-params/

from fastapi import FastAPI
from typing import Union

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 = 0):
    return fake_items_db[skip: skip+limit]
    
# http://127.0.0.1:8000/items/?skip=1&limit=2
# [{"item_name":"Bar"},{"item_name":"Baz"}]


# 기본값을 None으로 설정 가능, bool 형 선언 가능
# path + query parameters
@app.get('/users/{user_id}/items/{item_id}')
async def read_user_item(user_id: str, item_id: str, q: Union[str, None] = None, short: bool = False):
    item = {'user_id': user_id, '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


# 필수 쿼리 매개변수 (required)
@app.get('/items/{item_id}')
async def read_user_item(item_id: str, needy: str):
    item = {'item_id': item_id, 'needy': needy}
    return item
    
# 필수 매개변수 누락되면 아래와 같은 에러 발생
# INFO:     127.0.0.1:64478 - "GET /items/foo-item HTTP/1.1" 422 Unprocessable Entity
# {"detail":[{"type":"missing","loc":["query","needy"],"msg":"Field required","input":null,"url":"https://errors.pydantic.dev/2.6/v/missing"}]}

 

 

3. Request Body

https://fastapi.tiangolo.com/tutorial/body/

from fastapi import FastAPI
from typing import Union
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: Union[str, None] = None        # python 3.10+: description: str | None = None
    price: float
    tax: Union[float, None] = None

app = FastAPI()

@app.post('/items/')
async def create_item(item: Item):
    item_dict = item.dict()
    if item.tax:
        price_with_tax = item.price + item.tax
        item_dict.update({"price_with_tax": price_with_tax})
    return item_dict


# path + query + request body
@app.put('/items/{item_id}')
async def update_item(item_id: int, item: Item, q: Union[str, None] = None):
    new_item = {'item_id': item_id, **item.dict()}
    if q:
        new_item.update({'q': q})
    return new_item

 

 

728x90

'Python > FastAPI' 카테고리의 다른 글

FastAPI Docker로 배포하기  (0) 2024.03.15
FastAPI install  (0) 2024.03.04