FastAPI로 첫 번째 REST API 만들기: 실용 가이드

발행: (2026년 1월 14일 오전 01:06 GMT+9)
5 min read
원문: Dev.to

Source: Dev.to

(번역을 진행하려면 번역하고자 하는 본문 텍스트를 제공해 주세요.)

왜 FastAPI인가?

FastAPI는 여러 이유로 돋보입니다:

  • Performance: 사용 가능한 가장 빠른 Python 프레임워크 중 하나로, Node.js 및 Go와 비교될 수 있습니다.
  • Type Safety: 더 나은 코드 품질과 편집기 지원을 위해 Python 타입 힌트를 기반으로 합니다.
  • Auto Documentation: Swagger UI와 ReDoc 문서가 자동으로 생성됩니다.
  • Modern Python: async/await를 사용하여 동시 요청을 효율적으로 처리합니다.

설정하기

먼저, FastAPI와 uvicorn(ASGI 서버)를 설치합니다:

pip install fastapi uvicorn

간단한 API 만들기

다음은 작업 목록을 관리하는 기본 FastAPI 애플리케이션입니다:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional

app = FastAPI()

# Pydantic model for data validation
class Task(BaseModel):
    id: int
    title: str
    description: Optional[str] = None
    completed: bool = False

# In-memory storage
tasks_db: List[Task] = []

@app.get("/")
def read_root():
    return {"message": "Welcome to the Task API"}

@app.get("/tasks", response_model=List[Task])
def get_tasks():
    return tasks_db

@app.get("/tasks/{task_id}", response_model=Task)
def get_task(task_id: int):
    task = next((t for t in tasks_db if t.id == task_id), None)
    if not task:
        raise HTTPException(status_code=404, detail="Task not found")
    return task

@app.post("/tasks", response_model=Task, status_code=201)
def create_task(task: Task):
    tasks_db.append(task)
    return task

@app.put("/tasks/{task_id}", response_model=Task)
def update_task(task_id: int, updated_task: Task):
    for index, task in enumerate(tasks_db):
        if task.id == task_id:
            tasks_db[index] = updated_task
            return updated_task
    raise HTTPException(status_code=404, detail="Task not found")

@app.delete("/tasks/{task_id}")
def delete_task(task_id: int):
    for index, task in enumerate(tasks_db):
        if task.id == task_id:
            tasks_db.pop(index)
            return {"message": "Task deleted successfully"}
    raise HTTPException(status_code=404, detail="Task not found")

API 실행하기

Start the development server:

uvicorn main:app --reload

Your API is now running at http://localhost:8000.

자동 문서화

FastAPI는 기본적으로 대화형 문서를 제공합니다:

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc

브라우저에서 직접 모든 엔드포인트를 테스트할 수 있습니다.

주요 기능 시연

  • Pydantic 모델: Task 클래스는 자동 데이터 검증을 위해 Pydantic을 사용합니다. 잘못된 데이터는 명확한 오류 응답을 트리거합니다.
  • 타입 힌트: 코드 전반에 걸친 파이썬 타입 힌트는 IDE 지원을 향상시키고 조기 오류 감지를 가능하게 합니다.
  • 경로 매개변수: 라우트의 {task_id} 구문은 URL 매개변수를 자동으로 추출하고 검증합니다.
  • HTTP 상태 코드: 적절한 상태 코드(예: 생성 시 201)는 REST 모범 사례를 따릅니다.
  • 예외 처리: HTTPException은 적절한 상태 코드를 포함한 깔끔한 오류 응답을 제공합니다.

Async 지원 추가

FastAPI는 async 작업에서 빛을 발합니다. 아래는 비동기 데이터베이스 호출을 시뮬레이션한 예시입니다:

import asyncio
from fastapi import HTTPException

@app.get("/tasks/async/{task_id}")
async def get_task_async(task_id: int):
    # Simulate async database call
    await asyncio.sleep(0.1)
    task = next((t for t in tasks_db if t.id == task_id), None)
    if not task:
        raise HTTPException(status_code=404, detail="Task not found")
    return task

다음 단계

Production‑ready API를 구축하려면 다음을 고려하세요:

  • 실제 데이터베이스 연결 (PostgreSQL, MongoDB)
  • 인증 및 권한 부여 추가
  • 포괄적인 요청 검증 및 오류 처리 구현
  • 프론트엔드 통합을 위한 CORS 설정
  • pytest를 사용한 테스트 작성
  • Docker로 컨테이너화

결론

FastAPI는 Python에서 API를 만드는 일을 직관적이고 즐겁게 만들어 줍니다. 자동 검증, 문서화, 그리고 최신 Python 기능들은 보일러플레이트 코드를 줄이고 비즈니스 로직에 집중할 수 있게 합니다. 성능과 개발자 경험 덕분에 소규모 프로젝트는 물론 대규모 애플리케이션에도 탁월한 선택입니다.

Back to Blog

관련 글

더 보기 »