Member-only story

[Tutorial] FastAPI, Beanie and MongoDB Fully Async

Ahmed Nafies
4 min readApr 16, 2023

--

FastAPI and Beanie: A Simple Guide to Building RESTful APIs with MongoDB fully async

Photo by Iamninoslav on Unsplash

Introduction

FastAPI is a modern web framework for building APIs with Python, which is fast, easy to use, and comes with automatic validation and documentation. Beanie is an asynchronous Python object-document mapper (ODM) for MongoDB that makes it simple to work with your database using Python data models.

In this tutorial, we will build a simple RESTful API using FastAPI and Beanie to interact with a MongoDB database. We’ll cover installation, configuration, and basic CRUD operations. By the end, you’ll have a working API connected to MongoDB and ready for further expansion.

Prerequisites

  • Python 3.7 or higher
  • Poetry
  • Basic knowledge of FastAPI and MongoDB

Let’s get started!

1. Setting up the environment

First, install and run MongoDB:
https://www.mongodb.com/docs/manual/installation/

# linux
sudo systemctl start mongod

# osx
brew services start mongodb-community

I also would recommend mongosh a simple mongo database client.

https://github.com/mongodb-js/mongosh

Second, create a new project directory and navigate to it:

mkdir fastapi_beanie
cd fastapi_beanie

Now, initialise a new Poetry project and create a virtual environment:

poetry init -n
poetry install
poetry add fastapi uvicorn beanie

In the next steps, we will create files as follows in the fastapi_beanie directory as follows

 .
├──  config.py
├──  database.py
├──  main.py
├──  models.py
├──  poetry.lock
├──  pyproject.toml
└──  README.md

2. Configuring the database

Create a new Python file, config.py, to store the MongoDB connection string:

import os

MONGO_URI: str = os.getenv(
"MONGO_URI",
"mongodb://localhost:27017",
)

MONGO_DB_NAME: str = os.getenv(…

--

--

Ahmed Nafies
Ahmed Nafies

No responses yet

Write a response