에듀테크 프로젝트 대시보드
첫 번째 앱 — 경로 동작
경로(path)와 HTTP 메서드를 데코레이터로 함수에 연결합니다. 이 함수를 경로 동작 함수(path operation function)라 부릅니다.
from fastapi import FastAPI
app = FastAPI(title="My API", version="1.0.0")
@app.get("/items") # 조회
@app.post("/items") # 생성
@app.put("/items/{id}") # 전체 수정
@app.patch("/items/{id}") # 부분 수정
@app.delete("/items/{id}") # 삭제
def handler(): ...@app.get("/user")
def get_user():
return {"id": 1, "name": "김한양"} # dict -> JSON
@app.get("/ids")
def get_ids():
return [1, 2, 3] # list -> JSON 배열
@app.get("/ok")
def ok():
return "done" # str -> "done"dict, list, Pydantic 모델, dataclass, 기본 타입은 jsonable_encoder 를 거쳐 자동 직렬화됩니다.
@app.get("/sync")
def sync_handler():
return db_query() # 동기 라이브러리 — 그냥 def
@app.get("/async")
async def async_handler():
return await http_call() # await 가 필요하면 async defawait 를 써야 하면 async defdef (FastAPI 가 스레드풀에서 실행)async def 안에서 블로킹 함수를 직접 호출하면 이벤트 루프가 멈춤 → async vs sync 참고@app.get(
"/items",
summary="아이템 목록",
description="등록된 모든 아이템을 반환합니다.",
tags=["items"],
)
def list_items():
...
# 함수 docstring 도 description 으로 자동 사용됨