FastAPI and Beanie: A Simple Guide to Building RESTful APIs with MongoDB fully async
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.
- Python 3.7 or higher
- Basic knowledge of FastAPI and MongoDB
Let’s get started!
1. Setting up the environment
First, install and run MongoDB:
sudo systemctl start mongod
brew services start mongodb-community
I also would recommend
mongosh a simple mongo database client.
Second, create a new project directory and navigate to it:
Now, initialise a new Poetry project and create a virtual environment:
poetry init -n
poetry add fastapi uvicorn beanie
In the next steps, we will create files as follows in the
fastapi_beanie directory as follows
2. Configuring the database
Create a new Python file,
config.py, to store the MongoDB connection string:
MONGO_URI: str = os.getenv(
MONGO_DB_NAME: str = os.getenv(…