VOOZH about

URL: https://www.geeksforgeeks.org/python/database-integration-with-fastapi/

⇱ Database Integration with FastAPI - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Database Integration with FastAPI

Last Updated : 11 May, 2026

MongoDB is a flexible and scalable NoSQL database widely used by developers. It can be integrated with FastAPI using PyMongo, the official Python driver. Below are the steps to perform this integration.

Step By Step Implementation

Step 1: Setting Up MongoDB

Ensure MongoDB is installed and running locally, or use a cloud service like MongoDB Atlas. Also, verify that you have permissions to perform CRUD operations.

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.

Step 4: Connecting to MongoDB

Use PyMongo to connect to your MongoDB database. Specify the connection URL and database name to establish a connection.

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.

Step 6: Implementing CRUD Operations

Implement API endpoints for CRUD operations and use PyMongo methods like insert_one, find, update_one and delete_one to interact with the database.

Complete Code

Explanation:

  • Defines an Address model to structure nested address data.
  • Defines a Student model with name, age, and embedded address for validation.
  • POST /students: Inserts a new student into MongoDB and returns the generated ID.
  • GET /students/{id}: Fetches a student by ID and raises a 404 error if not found.
  • PATCH /students/{id}: Updates a student’s details and returns 404 if no record is modified.
  • DELETE /students/{id}: Deletes a student by ID and returns a success message or 404 if not found.

Run the Application

Run the FastAPI application using an ASGI server such as Uvicorn.

uvicorn main:app --reload

Output:

Related Articles

Comment
Article Tags: