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
FastAPI - SQLite Databases Python FastAPI is a modern and fast, web framework for building APIs with Python. FastAPI gained good popularity for its performance and ease of use. When it comes to integrating SQL databases with FastAPI, the framework provides seamless support, making it a good choice for developers for efficient
7 min read
Interface Python with an SQL Database Python is an easy-to-learn language and connectivity of python with any SQL database is a much-desired option to have the persistence feature. Python is an object-oriented programming language and it is open source. Newcomers to the software industry including school children too can learn Python ea
8 min read
Spring Boot with H2 Database H2 Database in Spring Boot is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It stores data in memory, not persist the data on disk. Here we will be discussing how can we configure and perform some b
6 min read
FastAPI - Crud Operations We will explore how to implement CRUD operations with FastAPI. CRUD operations are essential in any web application, including creating new records, retrieving existing records, updating existing records, and deleting records from a database. What is CRUD in FastAPI?CRUD refers to the basic operatio
5 min read
FastAPI - Introduction Developers are continuously on the lookout for technologies that allow them to rapidly and efficiently construct sophisticated APIs and online applications. FastAPI, a relatively new addition to the Python web framework landscape, has quickly garnered traction due to its speed, simplicity, and devel
5 min read
How to Create Microservices with FastAPI Creating microservices with FastAPI involves setting up small, independent services that can communicate with each other, usually over HTTP. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. Here's a step-by-step guide
3 min read
Introduction to FastAPI And Installation Introduction to FastAPIFastAPI is a modern, fast (as the name suggests), and highly performant Python web framework used for building APIs. It is built on top of standard Python-type hints and is powered by asynchronous programming using Python's "asyncio". FastAPI is known for its speed, simplicity
4 min read
Creating First REST API with FastAPI FastAPI is a cutting-edge Python web framework that simplifies the process of building robust REST APIs. In this beginner-friendly guide, we'll walk you through the steps to create your very first REST API using FastAPI. By the end, you'll have a solid foundation for building and deploying APIs with
5 min read
Spring Boot - Database Integration (JPA, Hibernate, MySQL, H2) In modern application development, integrating a database is crucial for persisting and managing data. Spring Boot simplifies this process by providing seamless integration with various databases through JPA (Java Persistence API) and Hibernate ORM (Object-Relational Mapping). This article will guid
7 min read
How to Generating a Database-Backed API APIs (Application Programming Interfaces) are Important for seamless communication between different software systems. A Database-Backed API uses a database to store and retrieve data, providing a dynamic and efficient means of interacting with information. In this article, we will explore the proce
4 min read