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.
Please consider to subscribe if you enjoyed ok 👍
beautiful explaination of why we use shchema serializers, I was confused at first now not. Thanks greate value
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
Thank you Mahesh
You didn't use opps concept nither use exceptional handling
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.
Try adding a soft background music it will help you grow @maheshkariya
you work is simple and useful
How can i link with mongodb compass ??
Thank you Mahesh
Your video was very helpful to me! Thank you!
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
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?
Well explained, Thank you
please share how to store / update bulk data
please how to use authentication to my API, sessionId, CSRF and Cors ??
awesome tutorial, thank you!
Any thought on how to use Patch operation in fastapi and mongodb using your method. Let me know Thanks.
clean and clear tutorial
Use {new: true} after $set for return new updated record
so yeach so yeach so yeach so yeach so yeach so yeach so yeach so yeach so yeach