1. 간단한 CRUD
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
items = {
0: {"name" : "라면",
"price" : 1000},
1: {"name" : "콜라",
"price" : 2000},
2: {"name" : "사이다",
"price" : 3000}
}
# Path parameter
@app.get("/")
def read_root():
return "Hello World"
@app.get("/items/{item_id}")
def read_item(item_id: int):
item = items[item_id]
return item
@app.get("/items/{item_id}/{key}")
def read_item_and_key(item_id: int, key : str):
key = items[item_id][key]
item = items[item_id]
return item, key
# Query parameter
@app.get("/item-by-name")
def read_item_by_name(name: str):
for item_id, item in items.items():
if item['name'] == name:
return item
return {"error": "data not found"}
class Item(BaseModel):
name: str
price: int
@app.post("/items/{item_id}")
def create_item(item_id:int,item: Item):
if item_id in items:
return {"error" : "there is already existing key"}
items[item_id] = item.dict()
return {"success" : "OK"}
# 변수에 값이 필수가 아니다
class ItemForUpdate(BaseModel):
name: Optional[str] = None
price: Optional[int] = None
@app.put("/items/{item_id}")
def update_item(item_id:int, item : ItemForUpdate):
if item_id not in items:
return {"error": f"there is no item id:{item_id}"}
if item.name:
items[item_id]['name'] = item.name
if item.price:
items[item_id]['price'] = item.price
return {"success" : "OK"}
@app.delete("/items/{item_id}")
def delete_item(item_id:int):
items.pop(item_id)
return {"success" : "OK"}
INFO: Will watch for changes in these directories: ['C:\\Users\\gkwks\\IdeaProjects\\python-test']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [17548] using StatReload
INFO: Started server process [23156]
INFO: Waiting for application startup.
INFO: Application startup complete.
- Uvicorn이 지정해준 URL로 접속하면 만들어진 html을 볼수 있고 URL뒤에 /doc를 붙이면 Swagger로 이동가능
http://127.0.0.1:8000/docs

- Try it out 버튼을 눌러서 값을 넣어 볼 수 있다.
