Create a lightning-fast REST API using FastAPI and MongoDB for a blogging website

Posted by


FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. In this tutorial, we will build a fast API using FastAPI and MongoDB for a blogging site.

Step 1: Set up the project

  1. Create a new directory for your project and navigate into it:

    mkdir fastapi-mongodb-blog
    cd fastapi-mongodb-blog
  2. Create a new Python virtual environment and activate it:

    python3 -m venv venv
    source venv/bin/activate
  3. Install FastAPI and Uvicorn (ASGI server) using pip:

    pip install fastapi uvicorn
  4. Install the required packages for interfacing with MongoDB:
    pip install pymongo

Step 2: Create the FastAPI app

  1. Create a new Python file called main.py and define your FastAPI app:
    
    from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
return {"Hello": "World"}


2. Run the FastAPI app using Uvicorn:

uvicorn main:app –reload


Open http://127.0.0.1:8000 in your web browser to see the running FastAPI app.

### Step 3: Set up MongoDB database

1. Install MongoDB on your local machine or use a MongoDB cloud service like MongoDB Atlas.

2. Connect to MongoDB using Python and retrieve the database instance:
```python
from pymongo import MongoClient

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

Step 4: Create CRUD operations for blog posts

  1. Define the model for a blog post in main.py:
    
    from pydantic import BaseModel

class Post(BaseModel):
title: str
content: str


2. Implement CRUD operations for the blog posts in `main.py`:
```python
from fastapi import HTTPException

@app.post("/posts/")
async def create_post(post: Post):
    post_id = db.posts.insert_one(post.dict()).inserted_id
    return {"id": str(post_id)}

@app.get("/posts/{post_id}/")
async def read_post(post_id: str):
    post = db.posts.find_one({"_id": ObjectId(post_id)})
    if post:
        return post
    raise HTTPException(status_code=404, detail="Post not found")

@app.put("/posts/{post_id}/")
async def update_post(post_id: str, post: Post):
    db.posts.update_one({"_id": ObjectId(post_id)}, {"$set": post.dict()})
    return {"message": "Post updated successfully"}

@app.delete("/posts/{post_id}/")
async def delete_post(post_id: str):
    db.posts.delete_one({"_id": ObjectId(post_id)})
    return {"message": "Post deleted successfully"}

Step 5: Run the FastAPI app with the MongoDB integration

  1. Make sure your MongoDB server is running.

  2. Run the FastAPI app using Uvicorn:
    uvicorn main:app --reload

Your FastAPI app with MongoDB integration is now ready to use. You can test the CRUD operations using tools like Postman or cURL.

This tutorial covered the basics of building a FastAPI app with MongoDB integration for a blogging site. You can extend the functionality by adding authentication, pagination, and more features to make it a full-fledged blogging platform. Happy coding!

0 0 votes
Article Rating

Leave a Reply

12 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@venkat.sairam
2 hours ago

🎯 Key points for quick navigation:

00:02 📝 Building a blogging backend system to create, retrieve, update, and delete blogs.
00:30 📡 An API allows software applications to communicate, defining methods and data formats for information exchange.
00:58 🔍 GET request retrieves all blogs from the server.
01:11 📝 POST request creates and saves a new blog on the server.
01:26 🔄 PATCH request updates an existing blog in the database.
01:39 🗑️ DELETE request removes a blog from the database.
01:55 🛠️ Setting up the environment and performing CRUD operations with FastAPI and MongoDB.
02:25 📁 Creating a project directory named "python_blog_backend".
03:02 🛠️ Installing virtual environment using pip.
03:45 ✅ Virtual environment created and ready for activation.
05:04 🔌 Activating the virtual environment.
05:30 📦 Installing FastAPI and Uvicorn.
06:04 🗂️ Creating folder structure for config, routes, models, and serializers.
07:09 🛠️ Setting up the MongoDB configuration file to connect to the database.
09:05 🌐 Creating a MongoDB cluster and user account.
11:14 🔑 Adding IP address for MongoDB access.
12:22 🐍 Checking Python version to ensure compatibility.
13:28 🔗 Connecting to MongoDB using the connection URI.
14:26 📋 Creating database and collection for the blogging application.
16:19 🚀 Running the server and opening the project in VS Code.
19:06 📝 Creating the main entry point for the application.
22:35 🔄 Including the router in the main application file.
24:10 🔧 Creating a GET request to test the FastAPI setup.
25:02 🛠️ Creating models for blog posts using Pydantic.
27:17 📄 Creating a route file for handling blog-related endpoints.
28:10 📩 Creating a POST request to add new blog data to the database.
29:00 🛠️ Setting the route for posting new blogs using `"/new/blog"` as the endpoint.
30:08 📥 Using Pydantic's `BlockModel` to validate and enforce the data structure for new blog entries.
31:41 📝 Converting the incoming blog data to a Python dictionary for processing.
32:23 🔄 Including the new POST route in the FastAPI application.
34:09 📅 Automatically adding the current date to new blog entries.
35:01 🗂️ Using MongoDB’s `insert_one` method to add new blog data to the database.
36:29 🆔 Retrieving and returning the automatically generated MongoDB ID for the new blog entry.
38:19 🛠️ Checking the new entry in MongoDB and verifying the data structure.
42:06 🏷️ Posting additional blog entries with meaningful titles and tags for testing.
43:10 🗃️ Creating serializers to decode the blog data before displaying it.
45:58 🧩 Serializing all blog entries to a Python list for easy retrieval.
47:04 🌐 Setting up a GET request route to retrieve all blog entries.
49:46 🛠️ Decoding and returning the serialized blog data in response to GET requests.
51:06 🔍 Creating a GET request route to retrieve a single blog entry by ID.
54:08 🔗 Verifying retrieval of a single blog entry by ID from MongoDB.
55:54 🌐 Testing the GET request with specific blog IDs through the API.
56:34 🔄 Introducing a PATCH request route to update existing blog entries.
57:00 🛠️ Setting up the PATCH request route to update a blog by its ID.
58:09 📝 Ensuring that only the provided attributes are updated while keeping others unchanged.
59:18 🔧 Creating a separate model for updating blogs to allow partial updates.
01:01:00 🗂️ Assigning `None` to attributes in the update model to make them optional.
01:02:06 🔄 Dumping attributes with `None` values to only include those with data.
01:04:26 ⚙️ Using `find_one_and_update` to locate and update the specific blog entry in the database.
01:06:08 ✅ Verifying the blog update by checking the updated data.
01:07:18 🗑️ Setting up the DELETE request route to remove a blog by its ID.
01:09:03 🚮 Using `find_one_and_delete` to find and delete the specific blog entry in the database.
01:09:59 🔍 Verifying the blog deletion by checking the removal of the specified entry.

Made with HARPA AI

@MaryLee-r2v
2 hours ago

Johnson John Davis Matthew White Shirley

@Yenna_Soluraa
2 hours ago

Thank you 🙏

@harshalmahajan4120
2 hours ago

can you please create videos for jwt authencation in fastapi using mongodb

@kartikswaroopdhiman5110
2 hours ago

very nice tutorial. Thanks a bunch.

@felix30ua
2 hours ago

негр для негров – сплошной антипаттерн, читайте лучше книги и документацию, этот уголек в Python случайный человек)))

@RamKiranYaram
2 hours ago

bro can you do Oauth with jwt token authorisaton please!!

@RamKiranYaram
2 hours ago

very usefull thanks paramaa !!!

@createwithfuntechs
2 hours ago

Get all my exclusive contents, source codes and weekly programming challenges by clicking this link: https://subscribetomyemaillist.netlify.app/createwithfuntechs

@huukhang0702
2 hours ago

Magnificent

@dogdev
2 hours ago

Awesome tutorial! Thank you!!

@mohammadmansouri9072
2 hours ago

thank you😍

12
0
Would love your thoughts, please comment.x
()
x