Building a FastAPI REST API with MongoDB using Python: CRUD Operations, Swagger, and PyMongo

Posted by


In this tutorial, we will learn how to create a REST API using FastAPI and MongoDB in Python. We will implement CRUD operations (Create, Read, Update, Delete) on a collection in MongoDB using PyMongo as our database driver. We will also use Swagger for API documentation.

Step 1: Setting up the Environment
First, we need to install the necessary libraries. You can do this using pip:

pip install fastapi uvicorn pymongo

Step 2: Create a new Python file, for example ‘main.py’, and import the required libraries:

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pymongo import MongoClient
from bson import ObjectId

Step 3: Connect to MongoDB
Next, establish a connection to your MongoDB database. Replace ‘mongodb://localhost:27017’ with your MongoDB URI:

client = MongoClient('mongodb://localhost:27017')
db = client['fastapi_mongodb']
collection = db['items']

Step 4: Create a FastAPI instance

app = FastAPI()

Step 5: Implement CRUD Operations
Now, let’s implement the CRUD operations. We will define endpoints for creating, reading, updating, and deleting items in our MongoDB collection.

# Create an item
@app.post('/items/')
async def create_item(item: dict):
    result = collection.insert_one(item)
    return JSONResponse(content={'id': str(result.inserted_id)}, status_code=201)

# Read an item
@app.get('/items/{item_id}')
async def read_item(item_id: str):
    item = collection.find_one({'_id': ObjectId(item_id)})
    if item:
        return JSONResponse(content=item, status_code=200)
    else:
        return JSONResponse(content={'message': 'Item not found'}, status_code=404)

# Update an item
@app.put('/items/{item_id}')
async def update_item(item_id: str, item: dict):
    result = collection.update_one({'_id': ObjectId(item_id)}, {'$set': item})
    if result.modified_count == 1:
        return JSONResponse(content={'message': 'Item updated successfully'}, status_code=200)
    else:
        return JSONResponse(content={'message': 'Item not found'}, status_code=404)

# Delete an item
@app.delete('/items/{item_id}')
async def delete_item(item_id: str):
    result = collection.delete_one({'_id': ObjectId(item_id)})
    if result.deleted_count == 1:
        return JSONResponse(content={'message': 'Item deleted successfully'}, status_code=200)
    else:
        return JSONResponse(content={'message': 'Item not found'}, status_code=404)

Step 6: Run the FastAPI Application
Finally, we can start the FastAPI application using Uvicorn:

uvicorn main:app --reload

Now, you can access the API at http://localhost:8000/docs to test the CRUD operations using Swagger.

That’s it! You have successfully created a FastAPI REST API with MongoDB and implemented CRUD operations. You can now build more complex APIs by adding authentication, validation, and other features to your API.

0 0 votes
Article Rating
36 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@maheshkariya
1 month ago

Please consider to subscribe if you enjoyed ok 👍

@mohitashliya8750
1 month ago

beautiful explaination of why we use shchema serializers, I was confused at first now not. Thanks greate value

@aminranjbar9397
1 month ago

why all user user user user you can us beteer name im think user and user and user and user for user delet f user name

@facundogomezgeneiro5559
1 month ago

Thank you Mahesh

@datascience4336
1 month ago

You didn't use opps concept nither use exceptional handling

@aitools24
1 month ago

00:06 Installation and setup of FastAPI and MongoDB for building a REST API in Python

05:14 Create a MongoDB REST API in Python using FastAPI

10:53 To get started with FastAPI MongoDB REST API, install the required dependencies and connect to the database.

14:42 Convert set users to a list or dictionary in Python

19:15 CRUD operations in FastAPI MongoDB REST API in Python

23:06 Using FastAPI and MongoDB to perform CRUD operations in Python

26:53 FastAPI MongoDB REST API in Python

31:14 Creating a REST API using FastAPI and MongoDB in Python.

Crafted by Merlin AI.

@malharsingh9687
1 month ago

Try adding a soft background music it will help you grow @maheshkariya
you work is simple and useful

@aymenlaribi3265
1 month ago

How can i link with mongodb compass ??

@dataking3830
1 month ago

Thank you Mahesh

@yeppi329
1 month ago

Your video was very helpful to me! Thank you!

@massmedia6516
1 month ago

I think you are confused with schemas and models
Models => means database table or collection structure
Schemas => means pydantic model for user input for endpoints

Please refer docs

@kanwaradnan4849
1 month ago

I'm a new person. My bad I have to ask a silly question. What if i wanted to make another collection 'entity' just like you created 'users'. Tell me the complete steps.

Like you created users file in almost Every directory do I have to do the same with every 'entity' I make?

@muhammedfayisc2022
1 month ago

Well explained, Thank you

@rameshwarcarpenter7962
1 month ago

please share how to store / update bulk data

@grnandoy
1 month ago

please how to use authentication to my API, sessionId, CSRF and Cors ??

@Toni-nw1dk
1 month ago

awesome tutorial, thank you!

@md.arifuzzamanbadhon1887
1 month ago

Any thought on how to use Patch operation in fastapi and mongodb using your method. Let me know Thanks.

@ahsanrossi4328
1 month ago

clean and clear tutorial

@vishvdesai9650
1 month ago

Use {new: true} after $set for return new updated record

@jankowal8623
1 month ago

so yeach so yeach so yeach so yeach so yeach so yeach so yeach so yeach so yeach