A simple REST API to create and retrieve blog posts using FastAPI and MongoDB.
This project is a beginner-friendly example showing how to use FastAPI with Pydantic models and MongoDB.
| Feature | Description |
|---|---|
| 🏠 Home Route | Health check for API status |
| ✍️ Create Blog | Add new blog post with title, body, and author |
| 📜 Read Blogs | Fetch all blogs from MongoDB |
| 📂 MongoDB Backend | Stores blogs in blogDB.myblog collection |
git clone https://github.com/yourusername/blog-api-fastapi.git
cd blog-api-fastapipython -m venv venv
source venv/bin/activate # (Linux/macOS)
venv\Scripts\activate # (Windows)pip install -r requirements.txtCreate a .env file in the root directory:
MONGO_URI=mongodb+srv://your_mongo_user:password@cluster-url/uvicorn main:app --reloadVisit: 👉 http://127.0.0.1:8000/docs
| Method | Route | Description |
|---|---|---|
GET |
/ |
Check if API is running |
POST |
/post |
Create a new blog post |
GET |
/blog |
Retrieve all blog posts |
POST /post
{
"title": "My First Blog",
"body": "This is a simple blog created with FastAPI.",
"author": "Rakesh"
}Response:
{
"status": "66bc8f...12",
"message": "Data inserted"
}{
"status": "ok",
"data": [
{
"title": "My First Blog",
"body": "This is a simple blog created with FastAPI.",
"author": "Rakesh"
}
]
}fastapi==0.117.1
uvicorn==0.37.0
pymongo==4.15.1
python-dotenv==1.0.1
pydantic==2.11.9
- Using Pydantic models for request validation
- Connecting FastAPI to MongoDB Atlas
- Designing basic REST API endpoints
- Managing environment variables securely
- Add update & delete routes
- Add authentication for admin users
- Integrate front-end or mobile app