Let’s build a ToDo application using FastAPI and MongoDB

Anozie Baron Chibuikem
3 min readOct 30, 2022

In this article, we will be building a simple Todo API application using FastAPI and MongoDB as our database, I know there are a lot of Todo API articles out there but hopefully, you learn a few tricks while building out this simple Todo API project with me. With that said, let’s dive right in.

First, go ahead and create a folder you will want your project to be in (Let’s call it ToDo). Inside the ToDo folder, create the following python files
config.py, main.py, model.py, openapi.py, requirements.txt, routers.py, .gitignore, and .env.

Inside your root directory, create a virtual environment and activate it using this command in your terminal

`python -m venv myenv`
`source myenv/bin/activate`

With that done, this is what your project folder structure should look like

Image of vscode showing the project folder structure

Inside your requirements.txt file, add the following

fastapi==0.65.1
uvicorn==0.14.0
pymongo==4.3.2
loguru==0.6.0
aioredis==2.0.1
motor==3.1.1
python-dotenv==0.21.0

Inside your .env file, add the following

MONGODB_URL='mongodb://localhost:27017/'
MONGODB_NAME='todoDB'
REDIS_DB='redis://127.0.0.1:6379/0'
ROOT_URL='http://127.0.0.1:8000'
DEBUG_MODE=True

Run the command below to install all the necessary packages

pip install -r requirements.txt

Add the following inside config.py

Let's setup our swagger doc for API documentation. Add the following inside openapi.py

Inside the main.py, add the following

Lets add our Task schema/model, inside model.py, add the following code

Lastly, let’s add our routes which will cover the CRUD workflow of Tasks

With all that done, go ahead and start up your development server using

uvicorn main:app --reload

When you run the command above, you should see this

Now navigate to ‘http://127.0.0.1:8000’ on your browser and test out the endpoints listed on the page

Chrome Page showing swagger-UI

Please don’t forget you have to have MongoDB installed on your local development machine.

To Install MongoDB on Linux https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/

To Install MongoDB on Mac https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/
Install MongoDB on window

To Install MongoDB on window https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-windows/

I hope this article has shown you how easy it is to create APIs with FastAPI and motivated you to keep building and learning FastAPI. If you found the article helpful, kindly leave a clap.

I will see you on another cool topic next time. Till then,

Stay Safe..! Keep Learning..!

Thank you for reading!

Follow me on Medium for the latest updates. 😃

--

--

Anozie Baron Chibuikem

A backend engineer constantly building a shit ton of things with python and javascript and occasionally writes on technical topics.