Database Integration with FastAPI
Last Updated :
11 May, 2024
FastAPI, a modern web framework for building APIs with Python, provides support for integrating with databases, allowing developers to create powerful and efficient applications. In this article, we'll explore how to integrate databases with FastAPI, focusing specifically on MongoDB integration using PyMongo.
Integrating MongoDB with FastAPI
MongoDB, a NoSQL database, is a popular choice for many developers due to its flexibility and scalability. Integrating MongoDB with FastAPI can be done using PyMongo, the official Python driver for MongoDB. Below is the step-by-step procedure by which we can integrate MongoDB with FastAPI using Python:
Step 1: Setting Up MongoDB
Before integrating MongoDB with FastAPI, you need to have MongoDB installed and running on your system or use a cloud-based solution like MongoDB Atlas. Ensure that you have the necessary permissions to create, read, update, and delete documents in your MongoDB database. For more information, refer to this: Install MongoDB
Step 2: Installing Dependencies
You'll need to install the necessary Python packages for FastAPI, Pydantic, PyMongo, and any other dependencies required for your project. You can install these packages using pip:
pip install fastapi uvicorn pymongo
Step 3: Creating Models
Define Pydantic models to represent the data structures that will be stored in MongoDB. These models will also handle data validation and serialization/deserialization.
Python
from pydantic import BaseModel
class Address(BaseModel):
city: str
country: str
class Student(BaseModel):
name: str
age: int
address: Address
Step 4: Connecting to MongoDB
Use PyMongo to connect to your MongoDB database. Specify the connection URL and database name to establish a connection.
Python
from pymongo import MongoClient
# Connect to MongoDB
client = MongoClient("mongodb://localhost:27017")
db = client["library_management"]
students_collection = db["students"]
Step 5: Defining API Endpoints
Now, define the API endpoints using FastAPI decorators. These endpoints will handle CRUD (Create, Read, Update, Delete) operations on the MongoDB database.
Python
from fastapi import FastAPI, HTTPException
app = FastAPI()
Step 6: Implementing CRUD Operations
Implement the API endpoints to perform CRUD operations on the MongoDB database. Use PyMongo's methods (insert_one, find, update_one, delete_one, etc.) to interact with the database.
Python
@app.post("/students", status_code=201)
async def create_student(student: Student):
result = students_collection.insert_one(student.dict())
return {"id": str(result.inserted_id)}
@app.get("/students", response_model=list[Student])
async def list_students(country: str = None, age: int = None):
query = {}
if country:
query["address.country"] = country
if age:
query["age"] = {"$gte": age}
students = list(students_collection.find(query, {"_id": 0}))
return students
@app.get("/students/{id}", response_model=Student)
async def get_student(id: str):
student = students_collection.find_one({"_id": ObjectId(id)}, {"_id": 0})
if student:
return student
else:
raise HTTPException(status_code=404, detail="Student not found")
@app.patch("/students/{id}", status_code=204)
async def update_student(id: str, student: Student):
updated_student = student.dict(exclude_unset=True)
result = students_collection.update_one(
{"_id": ObjectId(id)}, {"$set": updated_student})
if result.modified_count == 0:
raise HTTPException(status_code=404, detail="Student not found")
else:
return
@app.delete("/students/{id}", status_code=200)
async def delete_student(id: str):
result = students_collection.delete_one({"_id": ObjectId(id)})
if result.deleted_count == 0:
raise HTTPException(status_code=404, detail="Student not found")
else:
return {"message": "Student deleted successfully"}
Complete Code Implementation
Python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from pymongo import MongoClient
from bson import ObjectId
app = FastAPI()
# Connect to MongoDB Atlas
client = MongoClient("mongodb://localhost:27017")
db = client["library_management"]
students_collection = db["students"]
class Address(BaseModel):
city: str
country: str
class Student(BaseModel):
name: str
age: int
address: Address
@app.post("/students", status_code=201)
async def create_student(student: Student):
result = students_collection.insert_one(student.dict())
return {"id": str(result.inserted_id)}
@app.get("/students", response_model=list[Student])
async def list_students(country: str = None, age: int = None):
query = {}
if country:
query["address.country"] = country
if age:
query["age"] = {"$gte": age}
students = list(students_collection.find(query, {"_id": 0}))
return students
@app.get("/students/{id}", response_model=Student)
async def get_student(id: str):
student = students_collection.find_one({"_id": ObjectId(id)}, {"_id": 0})
if student:
return student
else:
raise HTTPException(status_code=404, detail="Student not found")
@app.patch("/students/{id}", status_code=204)
async def update_student(id: str, student: Student):
updated_student = student.dict(exclude_unset=True)
result = students_collection.update_one(
{"_id": ObjectId(id)}, {"$set": updated_student})
if result.modified_count == 0:
raise HTTPException(status_code=404, detail="Student not found")
else:
return
@app.delete("/students/{id}", status_code=200)
async def delete_student(id: str):
result = students_collection.delete_one({"_id": ObjectId(id)})
if result.deleted_count == 0:
raise HTTPException(status_code=404, detail="Student not found")
else:
return {"message": "Student deleted successfully"}
Running the Application
Finally, run the FastAPI application using an ASGI server like Uvicorn.
uvicorn main:app --reload
Output
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
SQL Interview Questions
Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970s, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
SQL Tutorial
SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.In this S
11 min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
SQL Joins (Inner, Left, Right and Full Join)
SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
6 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Normal Forms in DBMS
In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
8 min read