FastAPI로 REST API 만들기 – 초보자도 쉽게 따라하는 완벽 가이드
1. 도입 – 학습 목표 및 필요성
🔗 관련 에러 해결 가이드
FastAPI로 REST API 만들기는 현대 웹 개발에서 필수적인 기술입니다. FastAPI는 Python으로 작성된 현대적이고 빠른 웹 프레임워크로, 간결한 문법과 뛰어난 성능으로 개발자들 사이에서 큰 인기를 얻고 있습니다. 이 튜토리얼을 통해 FastAPI의 기본 개념부터 실전 활용까지 단계별로 학습하여, 여러분만의 REST API를 구축할 수 있게 됩니다. API 개발 경험이 없는 초보자도 쉽게 따라할 수 있도록 구성했으며, 실무에서 바로 활용 가능한 코드 예제를 제공합니다. Python의 기본 문법만 알고 있다면 누구나 FastAPI를 사용하여 고성능 웹 서비스를 만들 수 있습니다.
2. 기본 개념 설명
FastAPI란? FastAPI는 Python 3.7 이상에서 사용할 수 있는 현대적인 웹 프레임워크입니다. Starlette와 Pydantic을 기반으로 구축되어 있으며, 자동 API 문서화, 타입 힌팅, 비동기 처리 등의 강력한 기능을 제공합니다.
REST API란? REST(Representational State Transfer)는 웹 서비스 설계 아키텍처의 한 형태입니다. HTTP 메서드(GET, POST, PUT, DELETE 등)를 사용하여 자원을 처리하며, JSON 형식으로 데이터를 주고받습니다.
FastAPI의 주요 장점:
- 빠른 성능: Node.js 및 Go와 비슷한 수준의 고성능을 제공합니다.
- 자동 문서화: Swagger UI와 ReDoc을 통해 자동으로 API 문서가 생성됩니다.
- 타입 안정성: Python 타입 힌트를 사용하여 런타임 에러를 줄입니다.
- 비동기 지원: async/await를 통한 비동기 프로그래밍이 가능합니다.
- 간결한 코드: 적은 코드로 많은 기능을 구현할 수 있습니다.
3. 단계별 구현 가이드
3.1 환경 설정
먼저 개발 환경을 준비합니다. Python이 설치되어 있다고 가정하고 시작합니다.
Step 1: 가상환경 생성
# 가상환경 생성
python -m venv venv
# 가상환경 활성화 (Windows)
venv\Scripts\activate
# 가상환경 활성화 (Mac/Linux)
source venv/bin/activate
Step 2: FastAPI 및 Uvicorn 설치
# FastAPI와 ASGI 서버인 Uvicorn 설치
pip install fastapi uvicorn[standard]
# 추가 라이브러리 설치
pip install pydantic python-multipart
3.2 첫 번째 API 만들기
프로젝트 디렉토리에 main.py 파일을 생성하고 기본 API를 작성합니다.
Step 3: 기본 애플리케이션 구조
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
Step 4: 서버 실행
# 터미널에서 실행
uvicorn main:app --reload
# --reload 옵션은 코드 변경 시 자동으로 서버를 재시작합니다
브라우저에서 http://localhost:8000로 접속하면 API가 정상적으로 작동하는 것을 확인할 수 있습니다. http://localhost:8000/docs에서 자동 생성된 Swagger 문서를 볼 수 있습니다.
3.3 데이터 모델 정의
Pydantic을 사용하여 데이터 검증과 직렬화를 처리합니다.
Step 5: Pydantic 모델 생성
from pydantic import BaseModel
from typing import Optional
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
class User(BaseModel):
username: str
email: str
full_name: Optional[str] = None
3.4 CRUD 작업 구현
Create, Read, Update, Delete 기본 작업을 구현합니다.
Step 6: 전체 CRUD API
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI()
# 임시 데이터베이스
fake_items_db = {}
item_id_counter = 1
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
# CREATE - 아이템 생성
@app.post("/items/", response_model=Item)
def create_item(item: Item):
global item_id_counter
fake_items_db[item_id_counter] = item
item_id_counter += 1
return item
# READ - 모든 아이템 조회
@app.get("/items/", response_model=List[Item])
def read_items(skip: int = 0, limit: int = 10):
items = list(fake_items_db.values())[skip : skip + limit]
return items
# READ - 특정 아이템 조회
@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: int):
if item_id not in fake_items_db:
raise HTTPException(status_code=404, detail="Item not found")
return fake_items_db[item_id]
# UPDATE - 아이템 수정
@app.put("/items/{item_id}", response_model=Item)
def update_item(item_id: int, item: Item):
if item_id not in fake_items_db:
raise HTTPException(status_code=404, detail="Item not found")
fake_items_db[item_id] = item
return item
# DELETE - 아이템 삭제
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
if item_id not in fake_items_db:
raise HTTPException(status_code=404, detail="Item not found")
del fake_items_db[item_id]
return {"message": "Item deleted successfully"}
4. 실제 코드 예제와 설명
4.1 데이터베이스 연동 예제
FastAPI로 REST API 만들기에서 실무적으로 가장 중요한 부분은 데이터베이스 연동입니다. SQLAlchemy를 사용한 예제를 살펴보겠습니다.
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from fastapi import Depends
# 데이터베이스 설정
DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# 모델 정의
class ItemDB(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
description = Column(String)
price = Column(Integer)
# 테이블 생성
Base.metadata.create_all(bind=engine)
# 의존성 주입
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# API 엔드포인트
@app.post("/db-items/")
def create_db_item(item: Item, db: Session = Depends(get_db)):
db_item = ItemDB(**item.dict())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@app.get("/db-items/")
def read_db_items(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
items = db.query(ItemDB).offset(skip).limit(limit).all()
return items
4.2 인증 및 보안
JWT 토큰을 사용한 인증 시스템 구현 예제입니다.
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from datetime import datetime, timedelta
SECRET_KEY = "your-secret-key-here"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def create_access_token(data: dict):
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
# 사용자 인증 로직
user = authenticate_user(form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password"
)
access_token = create_access_token(data={"sub": user.username})
return {"access_token": access_token, "token_type": "bearer"}
5. 고급 활용 방법
5.1 비동기 처리
FastAPI의 강력한 기능 중 하나는 비동기 처리입니다. 데이터베이스 쿼리나 외부 API 호출 시 성능을 크게 향상시킬 수 있습니다.
import asyncio
import httpx
@app.get("/async-data")
async def get_async_data():
async with httpx.AsyncClient() as client:
response = await client.get("https://api.example.com/data")
return response.json()
@app.get("/multiple-requests")
async def multiple_requests():
async with httpx.AsyncClient() as client:
responses = await asyncio.gather(
client.get("https://api.example.com/data1"),
client.get("https://api.example.com/data2"),
client.get("https://api.example.com/data3")
)
return [r.json() for r in responses]
5.2 미들웨어와 CORS
CORS 설정과 커스텀 미들웨어를 추가하여 보안과 기능을 강화할 수 있습니다.
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(GZipMiddleware, minimum_size=1000)
5.3 백그라운드 태스크
from fastapi import BackgroundTasks
def send_email(email: str, message: str):
# 이메일 발송 로직
print(f"Sending email to {email}: {message}")
@app.post("/send-notification/")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_email, email, "Welcome!")
return {"message": "Notification sent in the background"}
6. 마무리 및 추가 학습 자료
이 튜토리얼을 통해 FastAPI로 REST API 만들기의 기초부터 실전 활용까지 배웠습니다. FastAPI는 강력한 기능과 간결한 문법으로 빠르게 API를 개발할 수 있는 훌륭한 프레임워크입니다.
다음 단계로 학습할 내용:
- FastAPI 공식 문서: https://fastapi.tiangolo.com/
- 테스트 작성: pytest를 사용한 API 테스트
- Docker 배포: 컨테이너화 및 배포 전략
- PostgreSQL/MongoDB 연동
- WebSocket 구현
- GraphQL 통합
FastAPI로 REST API 만들기를 마스터하면 현대적인 웹 서비스를 빠르고 효율적으로 개발할 수 있습니다. 실습을 통해 직접 코드를 작성하고, 에러를 해결하면서 실력을 향상시켜 보세요. 궁금한 점이 있다면 공식 문서와 커뮤니티를 적극 활용하시기 바랍니다.
📚 함께 읽으면 좋은 글
FastAPI로 REST API 만들기 – 초보자도 쉽게 따라하는 완벽 가이드
📅 2025. 10. 21.
🎯 FastAPI로 REST API 만들기
FastAPI로 REST API 만들기 – 초보자도 쉽게 따라하는 완벽 가이드
📅 2025. 10. 19.
🎯 FastAPI로 REST API 만들기
FastAPI로 REST API 만들기 – 초보자도 쉽게 따라하는 완벽 가이드
📅 2025. 10. 19.
🎯 FastAPI로 REST API 만들기
FastAPI로 REST API 만들기 – 초보자도 쉽게 따라하는 완벽 가이드
📅 2025. 10. 1.
🎯 FastAPI로 REST API 만들기
FastAPI로 REST API 만들기 – 초보자도 쉽게 따라하는 완벽 가이드
📅 2025. 9. 30.
🎯 FastAPI로 REST API 만들기
💡 위 글들을 통해 더 깊이 있는 정보를 얻어보세요!
📢 이 글이 도움되셨나요? 공유해주세요!
여러분의 공유 한 번이 더 많은 사람들에게 도움이 됩니다 ✨
🔥 공유할 때마다 블로그 성장에 큰 힘이 됩니다! 감사합니다 🙏
💬 여러분의 소중한 의견을 들려주세요!
FastAPI로 REST API 만들기에 대한 여러분만의 경험이나 노하우가 있으시나요?
⭐ 모든 댓글은 24시간 내에 답변드리며, 여러분의 의견이 다른 독자들에게 큰 도움이 됩니다!
🎯 건설적인 의견과 경험 공유를 환영합니다 ✨
🔔 블로그 구독하고 최신 글을 받아보세요!
🌟 Python 튜토리얼부터 다양한 실생활 정보까지!
매일 새로운 유용한 콘텐츠를 만나보세요 ✨
📧 RSS 구독 | 🔖 북마크 추가 | 📱 모바일 앱 알림 설정
지금 구독하고 놓치는 정보 없이 업데이트 받아보세요!