FastAPI와 MongoDB를 연동하여 데이터 CRUD 기능 구현하기

FastAPI는 Python으로 개발된 빠르고 현대적인 웹 프레임워크입니다. MongoDB는 유연하고 확장 가능한 NoSQL 데이터베이스입니다. 이 두 기술을 함께 사용하여 데이터의 생성(Create), 읽기(Read), 수정(Update), 삭제(Delete) 기능을 구현하는 방법을 알아보겠습니다.

1. FastAPI와 PyMongo 설치하기

FastAPI와 MongoDB를 연동하기 위해 다음과 같이 패키지를 설치해야 합니다.

pip install fastapi
pip install uvicorn
pip install pymongo

2. FastAPI 애플리케이션 생성하기

FastAPI에서 MongoDB를 다루기 위해 다음과 같이 FastAPI 애플리케이션을 생성합니다.

from fastapi import FastAPI

app = FastAPI()

3. MongoDB 연결하기

PyMongo를 사용하여 MongoDB와 연결합니다. 연결 정보는 MongoDB 서버의 IP 주소와 포트 번호, 사용자 이름 및 비밀번호 등이 포함됩니다.

from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]

4. 데이터 생성하기 (Create)

FastAPI에서 POST 메서드를 사용하여 데이터를 생성하는 엔드포인트를 만들어 보겠습니다.

from fastapi import HTTPException
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

@app.post("/items")
def create_item(item: Item):
    try:
        item_id = db["items"].insert_one(item.dict()).inserted_id
        return {"item_id": str(item_id)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

5. 데이터 읽기 (Read)

FastAPI에서 GET 메서드를 사용하여 데이터를 읽는 엔드포인트를 만들어 보겠습니다.

@app.get("/items/{item_id}")
def read_item(item_id: str):
    try:
        item = db["items"].find_one({"_id": ObjectId(item_id)})
        if item:
            return item
        else:
            raise HTTPException(status_code=404, detail="Item not found")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

6. 데이터 수정하기 (Update)

FastAPI에서 PUT 메서드를 사용하여 데이터를 수정하는 엔드포인트를 만들어 보겠습니다.

@app.put("/items/{item_id}")
def update_item(item_id: str, item: Item):
    try:
        updated_item = db["items"].update_one({"_id": ObjectId(item_id)}, {"$set": item.dict()})
        if updated_item.modified_count > 0:
            return {"message": "Item updated successfully"}
        else:
            raise HTTPException(status_code=404, detail="Item not found")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

7. 데이터 삭제하기 (Delete)

FastAPI에서 DELETE 메서드를 사용하여 데이터를 삭제하는 엔드포인트를 만들어 보겠습니다.

@app.delete("/items/{item_id}")
def delete_item(item_id: str):
    try:
        deleted_item = db["items"].delete_one({"_id": ObjectId(item_id)})
        if deleted_item.deleted_count > 0:
            return {"message": "Item deleted successfully"}
        else:
            raise HTTPException(status_code=404, detail="Item not found")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

마치며

이제 FastAPI와 MongoDB를 연동하여 데이터의 CRUD 기능을 구현하는 방법에 대해 알아보았습니다. 이를 통해 데이터를 생성, 읽기, 수정, 삭제하는 확장 가능하고 유연한 애플리케이션을 구축할 수 있습니다. FastAPI와 MongoDB의 강력한 조합으로 많은 기능을 개발해보세요!