- Request Body(Not Necessarily) : send data from a Client(a browser) → API
- Response Body(Necessarily) : data from API → a Client(a browser)
- Step
1. Declare a request body using Pydantic.
from pydantic import BaseModel
2. Declare the data model as a class that inherits from BaseModel.
class Item(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
3. Declare path operation, query parameters.
@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
4. Check responses.
# http://127.0.0.1:8000/docs
# Request body
>>>
{
"name": "abc",
"description": "abc market",
"price": 100,
"tax": 10
}
# Responses
>>>
curl -X 'POST' \
'http://127.0.0.1:8000/items/' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"name": "abc",
"description": "abc market",
"price": 100,
"tax": 10
}'
# Request URL
>>>
http://127.0.0.1:8000/items/
# Response body
>>>
{
"name": "abc",
"description": "abc market",
"price": 100,
"tax": 10,
"price_with_tax": 110
}
'Basic Python > FastAPI' 카테고리의 다른 글
FastAPI-GET and POST (0) | 2022.07.21 |
---|---|
FastAPI (0) | 2022.07.14 |