from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
class BaseUser(BaseModel):
user_id: int
username: str
email: EmailStr
full_name: Union[str, None] = None
# Type hint를 통해 스키마를 설정할 수 있다.
class UserIn(BaseUser): # 상속을 받을 수 있어 코드를 줄일 수 있다.
password: str
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: BaseUser):
results = {"item_id": item_id, "item": item, "user": user}
return results
@app.post("/user/")
async def create_user(user: UserIn) -> BaseUser: # 결과값에 대한 정의 이다.
# user: UserIn => 사용자를 생성할 때 받아야하는 request body 값을 정의한다.
return user
from typing import Union
from pydantic import BaseModel
...
class Item(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
...
@app.put("/items/{item_id}")
async def update_item(
item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
q: Union[str, None] = None,
item: Union[Item, None] = None,
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
if item:
results.update({"item": item})
return results
// request body
{
"name": "string",
"description": "string",
"price": 1,
"tax": 0
}
// response body
**{
"item_id": 1,
"q": "test",
"item": {
"name": "string",
"description": "string",
"price": 1,
"tax": 0
}
}
// log**
>>> INFO: 127.0.0.1:8630 - "PUT /items/1?q=test HTTP/1.1" 200 OK
// request body
{
"name": "string",
"description": "string",
"price": "ff1", # float 값이 아닌 string 값인 경우
"tax": 0
}
// response body
{
"detail": [
{
"type": "float_parsing",
"loc": [
"body",
"price"
],
"msg": "Input should be a valid number, unable to parse string as a number",
"input": "ff1",
"url": "https://errors.pydantic.dev/2.5/v/float_parsing"
}
]
}
// log
>>> INFO: 127.0.0.1:8693 - "PUT /items/1?q=test HTTP/1.1" 422 Unprocessable Entity