Programming Language/Python

[FastAPI] 7. Body Parameter

LeeJaeJun 2024. 6. 19. 19:34
728x90
반응형

Body Parameter

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None


class User(BaseModel):
    username: str
    full_name: str | None = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: User):
    results = {"item_id": item_id, "item": item, "user": user}
    return results
# body example
{
    "item": {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2
    },
    "user": {
        "username": "dave",
        "full_name": "Dave Grohl"
    }
}
  • HTTP 요청 본문을 읽고 싶을 때는 Item, User와 같이 데이터 형식을 정하고 이에 맞추어 읽어들일 수 있었음
  • 이는 주소에 포함되어있는 내용이 아님 
    • 주소에 포함된 변수를 받을 때는 path parameter
    • 주소 바깥 ? 이후의 변수를 담을 때는 query parameter
  • Item, User와 같이 여러 값들로 이루어진 클래스가 아니라 단일 값으로 값을 읽어들이고 싶다면 Body함수 사용
from typing import Annotated

from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None


class User(BaseModel):
    username: str
    full_name: str | None = None


@app.put("/items/{item_id}")
async def update_item(
    item_id: int, item: Item, user: User, importance: Annotated[int, Body()]
):
    results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
    return results
# Body함수로 지정한 importance는 단일 값으로 값을 읽어올 수 있다.
# body example
{
    "item": {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2
    },
    "user": {
        "username": "dave",
        "full_name": "Dave Grohl"
    },
    "importance": 5
}

 

  • Body도 Query, Path와 마찬가지로 여러 매개변수를 안에 사용할 수 있고, Annotated와 같이 사용할 수 있음
    • ex) importance: Annotated[int, Body(gt=0)]
  • 단일 Pydantic 모델 parameter를 본문으로 받을 때는 키 없이 직접 데이터를 받을 때는 다음과 같이 직접적으로 본문 내용만 포함
{
 	"name": "Foo",
	"description": "The pretender",
	"price": 42.0,
	"tax": 3.2
}

# 맨 처음 예시에서는 Item, User라는 두 개의 Pydantic 모델 파라미터를 사용했기에 
# "Item", "User"라는 키가 같이 명시되어 있었음
  • 단인 Pydantic 모델 paramter 또한 키를 받게 하고싶다면 embed라는 Body 함수의 parameter 사용
from typing import Annotated
from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
    results = {"item_id": item_id, "item": item}
    return results
{
    "item": {
        "name": "Foo",
        "description": "The pretender",
        "price": 42.0,
        "tax": 3.2
    }
}

# 단일 Pydantic model parameter를 사용해도 item이라는 key가 같이 명시된다!

 

https://fastapi.tiangolo.com/tutorial/body-multiple-params/

 

Body - Multiple Parameters - FastAPI

FastAPI framework, high performance, easy to learn, fast to code, ready for production

fastapi.tiangolo.com

 

728x90
반응형