null
vuild_
Nodes
Flows
Hubs
Login
MENU
GO
Notifications
Login
⌂
Python 웹 개발 입문 — FastAPI로 배우는 백엔드
Structure
intro
•
왜 Python으로 웹 백엔드를 만드는가?
•
FastAPI 개요 — 핵심 개념 정리
setup
•
FastAPI 개발 환경 구축
routing
•
FastAPI 라우팅과 경로 파라미터
project
•
FastAPI 미니 프로젝트 — Todo API
Flow Structure
FastAPI 개발 환경 구축
4 / 5
FastAPI 미니 프로젝트 — Todo API
☆ Star
↗ Full
FastAPI 라우팅과 경로 파라미터
#fastapi
#routing
#path
#query
#params
@devpc
|
2026-04-27 06:24:27
|
GET /api/v1/flows/16/nodes/278?fv=1&nv=1
Context:
Flow v1
→
Node v1
0
Views
1
Calls
# FastAPI 라우팅과 경로 파라미터 ## 기본 라우트 선언 ```python from fastapi import FastAPI app = FastAPI() # HTTP 메서드별 데코레이터 @app.get("/") # GET @app.post("/items") # POST @app.put("/items/{id}") # PUT @app.delete("/items/{id}") # DELETE @app.patch("/items/{id}") # PATCH ``` --- ## 경로 파라미터 (Path Parameters) ```python @app.get("/users/{user_id}") async def get_user(user_id: int): # 자동으로 int 변환 & 검증 return {"user_id": user_id} # GET /users/42 → {"user_id": 42} # GET /users/abc → 422 Validation Error (자동) ``` ### 열거형(Enum) 경로 파라미터 ```python from enum import Enum class Category(str, Enum): tech = "tech" science = "science" culture = "culture" @app.get("/posts/{category}") async def get_posts(category: Category): return {"category": category.value} # GET /posts/tech → {"category": "tech"} # GET /posts/invalid → 422 Validation Error ``` --- ## 쿼리 파라미터 (Query Parameters) 경로에 없는 파라미터는 자동으로 쿼리 파라미터로 처리됩니다. ```python @app.get("/items") async def list_items( skip: int = 0, # 기본값 0 limit: int = 20, # 기본값 20 search: str | None = None # 선택 파라미터 ): return {"skip": skip, "limit": limit, "search": search} # GET /items?skip=10&limit=5&search=python ``` ### Query 메타데이터 추가 ```python from fastapi import Query @app.get("/items") async def list_items( q: str | None = Query( default=None, min_length=3, max_length=50, description="검색 키워드 (3자 이상)" ) ): return {"q": q} ``` --- ## 요청 바디 (Request Body) ```python from pydantic import BaseModel class ItemCreate(BaseModel): name: str price: float description: str | None = None @app.post("/items", status_code=201) async def create_item(item: ItemCreate): # item은 자동으로 파싱·검증됨 saved = db_save(item.model_dump()) return saved ``` --- ## 경로 + 쿼리 + 바디 조합 ```python @app.put("/users/{user_id}/items/{item_id}") async def update_item( user_id: int, # 경로 파라미터 item_id: int, # 경로 파라미터 notify: bool = False, # 쿼리 파라미터 item: ItemCreate = None, # 요청 바디 ): return { "user_id": user_id, "item_id": item_id, "notify": notify, "item": item, } ``` FastAPI는 **변수 이름과 위치**를 기반으로 경로/쿼리/바디를 자동 구분합니다. --- ## 응답 모델 정의 ```python class ItemResponse(BaseModel): id: int name: str price: float # password 같은 민감 필드 제외 가능 @app.get("/items/{item_id}", response_model=ItemResponse) async def get_item(item_id: int): item = db.get(item_id) # 내부 모델 (password 등 포함) return item # response_model이 필터링해줌 ```
FastAPI 개발 환경 구축
FastAPI 미니 프로젝트 — Todo API
// COMMENTS
Newest First
ON THIS PAGE
No content selected.