FASTAPI 시작하기 (3) - Response 다루기

code_able·2023년 3월 12일
0
post-custom-banner

form

from fastapi import FastAPI, Form

app = FastAPI()


@app.post("/login/")
async def login(username: str = Form(), password: str = Form()):
    return {"username": username}

respose body

from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

class Items(BaseModel):
		""" requests model"""
    name: str
    price: float = Field(..., title='item price', example=30)

class ItemsOutput(BaseModel):
		"""response model"""
    description: str = Field('', title='Item description', example='good')
    tax: float = Field(..., title='item tax', example=30)

@app.post('/items/', response_model=ItemsOutput, status_code=201)
async def read_items(item: Items):
    return {'description' : 'item', 'tax' : 30}

json serealizer

from datetime import datetime
from typing import Optional
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    title: str
    timestamp: datetime
    description: Optional[str]

class OutItem(Item):
    pass

@app.put("/item/{item_id}", response_model=OutItem)
def update_item(id: str, item: Item):
    json_compatible_item_data = jsonable_encoder(item)
    print(json_compatible_item_data)
profile
할수 있다! code able
post-custom-banner

0개의 댓글