Introduction
Recently, I built a simple, interactive shopping list web app that stores data persistently. I used FastAPI for the backend and MongoDB for database storage.
FastAPI is a modern, high-performance Python framework for building APIs, while MongoDB is a flexible NoSQL database. In this post, I’ll show you how I built it step by step, including backend, frontend, and styling.
Step 1: Setting Up the Project
I started by creating a project folder:
Copy
Copy
shopping_demo/
│
├─ main.py # FastAPI backend
├─ requirements.txt
├─ venv/ # Python virtual environment
└─ frontend/
├─ index.html
└─ style.css
Then, I created a virtual environment and installed the required packages:
Copy
Copy
python -m venv venv
.venvScriptsactivate # Windows
pip install fastapi uvicorn pymongo
Step 2: Connecting FastAPI to MongoDB
I used MongoDB Atlas for cloud storage:
Signed up at MongoDB Atlas
Created a free cluster
Added a database user and whitelisted my IP
Copied the connection string
Here’s how I connected FastAPI to MongoDB:
Copy
Copy
from pymongo import MongoClient
from fastapi import FastAPI
MONGO_URI = “mongodb+srv://:@cluster0.mongodb.net/shopping_db?retryWrites=true&w=majority”
client = MongoClient(MONGO_URI)
db = client[“shopping_db”]
collection = db[“items”]
app = FastAPI()
Step 3: Creating API Endpoints
I created endpoints for basic CRUD operations:
Copy
Copy
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)
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:
Copy
Copy
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();
Added a form to add new items.
Buttons to delete or mark items as bought are dynamically handled using JS.
Step 5: Styling with CSS
I styled the page for a clean look:
Copy
Copy
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);
}
Step 6: Running the App
Run the FastAPI server:
Copy
Copy
python -m uvicorn main:app –reload
Open index.html in your browser.
Interact with your shopping list.
All changes are persisted in MongoDB.
Screenshot Placeholder:
(Insert a screenshot of your shopping list frontend showing items.)
Step 7: How It Works (Flow Diagram)
Copy
Copy
User → Frontend (index.html + JS) → FastAPI → MongoDB → Frontend updates
The frontend fetches and displays items dynamically.
Any add, update, or delete action is sent to FastAPI API endpoints.
FastAPI updates MongoDB, which keeps data persistent.
Conclusion
This project taught me 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 persistently.
A simple JS frontend can interact dynamically with the backend.
Next steps:
Add user authentication
Deploy the app to cloud (Heroku / Railway)
Improve frontend with React or Tailwind CSS
References:
FastAPI Documentation
MongoDB Atlas
👋 Thanks for reading! If you enjoyed this guide, follow me on DEV for more projects, tutorials, and tips on Python, FastAPI, and web development.
Source: DEV Community.

Leave a Reply