DEV Community

Cover image for How I Built a FastAPI App with MongoDB: A Step-by-Step Guide
sarbajitacharjee
sarbajitacharjee

Posted on

How I Built a FastAPI App with MongoDB: A Step-by-Step Guide

Introduction

Recently, I built a simple, interactive shopping list web app that stores data persistently.
I used FastAPI for the backend and MongoDB for the database.

FastAPI is a modern, high-performance Python framework for building APIs, and MongoDB is a flexible NoSQL database perfect for storing JSON-like documents.


Step 1: Setting Up the Project

I started by creating a project folder:

shopping_demo/
│
├─ main.py         # FastAPI backend
├─ requirements.txt
├─ venv/           # Python virtual environment
└─ frontend/
    ├─ index.html
    └─ style.css
Enter fullscreen mode Exit fullscreen mode

Created a virtual environment and installed the required packages:

python -m venv venv
.\venv\Scripts\activate      # Windows
pip install fastapi uvicorn pymongo
Enter fullscreen mode Exit fullscreen mode

Step 2: Connecting FastAPI to MongoDB

I used MongoDB Atlas for cloud storage:

  1. Signed up at MongoDB Atlas
  2. Created a free cluster
  3. Added a database user and whitelisted my IP
  4. Copied the connection string

Here’s the code to connect FastAPI to MongoDB:

from pymongo import MongoClient
from fastapi import FastAPI

MONGO_URI = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/shopping_db?retryWrites=true&w=majority"
client = MongoClient(MONGO_URI)
db = client["shopping_db"]
collection = db["items"]

app = FastAPI()
Enter fullscreen mode Exit fullscreen mode

Step 3: Creating API Endpoints

I needed endpoints for basic CRUD operations:

from pydantic import BaseModel
from typing import List
from bson import ObjectId
from fastapi import HTTPException

class ItemBase(BaseModel):
    name: str
    quantity: int
    bought: bool = False

def item_helper(item) -> dict:
    return {
        "id": str(item["_id"]),
        "name": item["name"],
        "quantity": item["quantity"],
        "bought": item["bought"]
    }

@app.get("/items", response_model=List[ItemBase])
def list_items():
    items = collection.find()
    return [item_helper(i) for i in items]

@app.post("/items", response_model=ItemBase)
def create_item(item: ItemBase):
    result = collection.insert_one(item.dict())
    new_item = collection.find_one({"_id": result.inserted_id})
    return item_helper(new_item)
Enter fullscreen mode Exit fullscreen mode

I also added PUT and DELETE endpoints to update and remove items.


Step 4: Building the Frontend

The frontend is a simple HTML page with JavaScript that fetches data from the API:

<ul id="itemList"></ul>

<script>
async function fetchItems() {
    const res = await fetch("http://127.0.0.1:8000/items");
    const items = await res.json();
    const list = document.getElementById("itemList");
    list.innerHTML = "";
    items.forEach(item => {
        const li = document.createElement("li");
        li.textContent = `${item.name} - ${item.quantity}`;
        list.appendChild(li);
    });
}
fetchItems();
</script>
Enter fullscreen mode Exit fullscreen mode
  • Added a form to add new items.
  • Buttons to delete or mark items as bought dynamically.

Step 5: Styling with CSS

body { 
  font-family: Arial; 
  background: #f7f7f7; 
  padding: 20px; 
}

ul { 
  list-style: none; 
  padding: 0; 
}

li { 
  background: white; 
  margin: 8px 0; 
  padding: 10px; 
  border-radius: 6px; 
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
Enter fullscreen mode Exit fullscreen mode

Screenshot placeholder:
![Shopping List Frontend](https://your-image-link.com)


Step 6: Running the App

Run the FastAPI server:

python -m uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode
  • Open index.html in your browser
  • Interact with your shopping list
  • Changes are persisted in MongoDB

How It Works

User → Frontend (HTML + JS) → FastAPI → MongoDB → Frontend updates
Enter fullscreen mode Exit fullscreen mode
  • Frontend fetches and displays items dynamically
  • Add, update, or delete actions are sent to FastAPI endpoints
  • FastAPI updates MongoDB, keeping data persistent

Conclusion

This project helped me learn how to integrate FastAPI with MongoDB for a real-world web app. Key takeaways:

  • FastAPI is fast, intuitive, and easy to use for APIs
  • MongoDB makes it easy to store JSON-like data
  • A simple JS frontend can interact dynamically with the backend

Next Steps:

  • Add user authentication
  • Deploy the app to the cloud (Heroku / Railway)
  • Improve frontend with React or Tailwind CSS

Bottom Line:
👋 Thanks for reading! If you enjoyed this guide, follow me on DEV for more projects, tutorials, and tips on Python, FastAPI, and web development.


References:


Top comments (0)