5.3 실습 프로젝트: 기본적인 CRUD API 구현

약 7분

본문 듣기
읽기 설정

글자 크기

줄 간격

글꼴

5.3 실습 프로젝트: 기본적인 CRUD API 구현

이번 장에서는 FastAPI를 사용하여 기본적인 CRUD(AjCreate, Read, Update, Delete) API를 구현해보겠습니다. 각 HTTP 메소드(GET, POST, PUT, DELETE)를 활용하여 데이터베이스와 상호작용하는 방법을 익힐 것입니다.

먼저, FastAPI와 SQLAlchemy 패키지를 설치해야 합니다. 아래의 명령어를 사용하여 설치할 수 있습니다.

코드 bash
pip install fastapi[all] sqlalchemy sqlite3

이제 기본적인 FastAPI 애플리케이션을 설정해보겠습니다. 아래 코드를 main.py 파일에 작성하세요.

코드 python
from fastapi import FastAPI, HTTPException
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session

DATABASE_URL = "sqlite:///./test.db"

Base = declarative_base()

class Item(Base):
    __tablename__ = 'items'

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)
    description = Column(String)

engine = create_engine(DATABASE_URL)
Base.metadata.create_all(bind=engine)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

app = FastAPI()

@app.post("/items/")
async def create_item(item: Item):
    db: Session = SessionLocal()
    db.add(item)
    db.commit()
    db.refresh(item)
    return item

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    db: Session = SessionLocal()
    item = db.query(Item).filter(Item.id == item_id).first()
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    db: Session = SessionLocal()
    db_item = db.query(Item).filter(Item.id == item_id).first()
    if db_item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    db_item.name = item.name
    db_item.description = item.description
    db.commit()
    return db_item

@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
    db: Session = SessionLocal()
    db_item = db.query(Item).filter(Item.id == item_id).first()
    if db_item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    db.delete(db_item)
    db.commit()
    return {"message": "Item deleted successfully"}

위의 코드를 작성한 후 FastAPI 서버를 실행시키려면 아래 명령어를 사용하세요.

코드 bash
uvicorn main:app --reload

서버가 실행되면 http://127.0.0.1:8000/docs 에 접속하여 Swagger UI를 통해 API를 테스트 할 수 있습니다. 여기서 제공되는 각 메소드(GET, POST, PUT, DELETE)를 클릭하여 CRUD 기능을 체험해보세요.

이번 실습을 통해 FastAPI를 사용하여 CRUD API를 구현하는 방법을 배웠습니다. 각 메소드의 역할을 이해하고, Swagger UI를 통해 API 테스트를 할 수 있는 능력을 기르는 것이 중요합니다. 앞으로의 수업에서는 데이터베이스를 MySQL로 변경하고 JWT를 사용한 인증 방법에 대해서도 다뤄볼 예정입니다.

퀴즈 및 실습 과제

  1. 각 HTTP 메소드의 역할을 설명하세요.
  2. 위의 코드를 수정하여 Item 모델에 가격(price) 필드를 추가하고, 이를 처리할 수 있는 API를 구현하세요.

댓글 0

댓글을 남기려면 로그인하세요.

아직 댓글이 없습니다. 첫 댓글을 남겨보세요.