Introduction
In this tutorial, we will dive into the process of building a powerful API using FastAPI and Motor, an asynchronous MongoDB driver.
FastAPI provides a straightforward way to create web APIs with incredible performance, while Motor enables seamless integration with MongoDB.
By the end of this tutorial, you will have a solid understanding of how to set up the environment, integrate MongoDB with FastAPI, create complex models, and perform CRUD operations efficiently.
I will walk you through creating a API using FastAPI and Motor(Async PyMongo)
Table of Contents
📍Setting up the Environment
📍Integrate MongoDB with FastAPI
📍Creating Complex Student Model
📍Performing CRUD Operations
Installation
Before we begin, make sure to install FastAPI and Motor by running the following commands in your terminal✅:
pip install fastapi pip install motor
Setting up the Environment
To get started, make sure to spin up a MongoDB M0 cluster, which is completely free and doesn’t require a credit card.
To integrate FastAPI with MongoDB, we need to establish a connection between the two. Use the following code:
import motor.motor_asyncio from fastapi import FastAPI app = FastAPI() uri = "mongodb+srv://<username>:<password>@task3.lnfrkc5.mongodb.net/? retryWrites=true&w=majority" # Create a new client and connect to the server client = motor.motor_asyncio.AsyncIOMotorClient(uri) # Send a ping to confirm a successful connection try: client.admin.command('ping') print("Pinged your deployment. You have successfully connected to MongoDB!") except Exception as e: print(e)
⚠️ Remember to replace <username> and <password> with your actual MongoDB credentials. Ensure that the ping to the database is successful, as this confirms the integration between the backend and the database.
Creating the Pydantic Standard Schema
Next, we will define the Pydantic standard schema, which represents the structure of our data. Here’s an example of how the JSON representation of the schema should look:
{ "_id": "", "name": "Suraj", "age": 21, "address": { "city": "Maihar", "country": "India" }, "phoneNum": ["9898989989", "8989898989"], "socials": [ { "social_type": "Github", "link": "https://github.com/suraj7879" }, { "social_type": "LinkedIn", "link": "https://linkedin.com/in/suraj7879" } ] }
* Please note that the _id field will be automatically generated by MongoDB.
Many people think of MongoDB as being schema-less, which is wrong❌MongoDB has a flexible schema✅
To ensure the validity of the data, we will make use of Pydantic. Define the following models:
from pydantic import BaseModel, Field from typing import List class Address(BaseModel): city: str country: str class Socials(BaseModel): type: str link: str class Student(BaseModel): name: str = Field(..., min_length=3, max_length=40) age: int = Field(..., gt=0) address: Address phoneNum: List[str] socials: List[Socials]
‼️ Will it be able to process if there are n number of social profiles ?
CRUD Operations:
Create a Student
@app.post('/student/') async def create_student(student: Student): try: student = student.dict() result = await collection.insert_one(student) print(result) except Exception as e: print(e) return {"message": "Success"}
⚠️ Remember to convert the Student object into a dictionary before passing it to the MongoDB functions(i.e. insert_one)
Read a Student
from bson import ObjectId ... ... @app.get('/student/{id}') async def read_student(id: str): student = await collection.find_one({"_id": ObjectId(id)}) if student: student['_id'] = str(student['_id']) return student else: return {"message": "Student not found"}
⚠️ Make sure to convert id parameter into ObjectId before before querying the MongoDB collection
Update a Student
@app.put('/student/{id}') async def update_student(id: str, updated_fields: dict): await collection.update_one({"_id": ObjectId(id)}, {"$set": updated_fields}) return {"message": "Student updated"}
⚠️ Instead of object, our function is accepting a dictionary called updated_fields. The updated_fields dictionary should contain the specific fields you want to update and their new values.
Delete a Student
@app.delete('/student/{id}') async def delete_student(id: str): student = await collection.find_one({"_id": ObjectId(id)}) if student: await collection.delete_one({"_id": ObjectId(id)}) return {"message": "Student deleted"} else: return {"message": "Student not found"}
‼️Think, what will happen if we wont write await when calling async functions?
Running the Backend:
To run the backend, use the following command in your terminal:
uvicorn main:app --reload
FastAPI provides built-in documentation, which includes interactive API documentation and the ability to test your API’s operations using a user-friendly GUI. Access it through the following URL:
http://127.0.0.1:8000/docs
Wrapping Up:
Congratulations! You have learned the basics of FastAPI, integration with MongoDB, and some of the great features FastAPI provides. You can now build robust APIs with ease, ensuring high performance and efficiency.
If you like this short introduction, do ❤️ and Repost 🔃 with your network! 🍀
Disclaimer: This post was originally written over linkedin by Me, sharing it in NamasteDev Community, if this get good amount of support, will come up with more exclusive content for this community
27 Comments
1
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
The intravenous administration of Uremide is indicated when a rapid onset of diuresis is desired, e priligy 30mg tablets
Кто ты есть на самом деле?
В чем твое предназначение?
В каком направлении лежит твой путь
и как тебе по нему идти?
Дизайн Человека расскажет об этом!
– Позволяет выстроить эффективную стратегию жизни и карьеры
– Снимает давление социальных стереотипов – Снимает чувство вины за “неправильность” –
Позволяет выстроить эффективную стратегию жизни и карьеры – Даёт
право быть собой – Даёт ощущение уникальности – Даёт
конкретные рекомендации по принятию решений – Снимает чувство вины за
“неправильность” – Позволяет выстроить эффективную стратегию жизни и карьеры
Узнать свое предназначение
и таланты. Эта методика предлагает человеку глубоко познать себя — дизайн человека
делит все личности на типы.
Кто ты есть на самом деле?
В чем твое предназначение? В каком направлении лежит твой
путь и как тебе по нему идти?
Дизайн Человека расскажет об этом!
– Снижает тревожность при выборе
– Даёт ощущение целостности
– Даёт конкретные рекомендации по принятию решений
– Позволяет жить в согласии со своей природой
– Снимает чувство вины за “неправильность” – Даёт право быть собой – Даёт ощущение целостности
– Укрепляет доверие к себе
– Позволяет выстроить эффективную стратегию жизни и карьеры
Дизайн Человека позволяет принимать решения в условиях неопределённости, опираться на себя и свой внутренний
компас.
Confused about how to go about the recovery of your QIWI wallet
funds? Our customer support are on standby around the clock to guide you through the steps and answer any queries you have.
Choosing our company, you’re choosing a dependable helper in getting your money back.
QIWI wallet balance not adding up?
Let us take the lead in recovering what isrightfully
yours. Get in touch now and begin reclaiming your funds.
Unsure of how to proceed with recovery of your QIWI wallet funds?
Our customer support are available to help to guide you through the steps
and respond to any concerns you have.
Working with our team, you’re opting for a reliable
helper in getting your money back.
Unexpectedly lost your balance on your QIWI wallet?
We understand how stressful that can be.
Stay calm—our company specializes in recovering missing money from QIWI wallets.
With expert knowledge, we’re sure we can help
out.
Reach out to us and let’s start the process of restoring your balance.
Worried about your QIWI wallet transactions?
Let us be your guide in recovering what isrightfully yours.
Get in touch now and begin reclaiming your funds.
Have funds disappeared on your QIWI wallet?
We know how frustrating that can be.
Stay calm—our team specializes in recovering your balance from QIWI wallets.
With expert knowledge, we’re positive we can assist you.
Get in touch and let’s start the process of getting your money back.
Our skillset in e-wallets and online transactions means
we’re perfectly equipped to tackle your QIWI wallet issues.
Be assured, we employ advanced techniques and stay updated with
the newest recovery methods.
If you’ve been hit with unauthorized transactions or errors
that resulted in a loss of funds, our team is ready to assist.
QIWI wallet balance not adding up?
Let us be your guide in getting back what isrightfully yours.
Reach out now and begin reclaiming your funds.
Recovering your money shouldn’t be a hassle. That’s why our service is straightforward and transparent.
Just provide us with some basic information, and we’ll take care of the rest.
Don’t allow fraudsters prevent you from your hard-earned
money. We’re committed to assist you in reclaiming
every penny.
Our expertise in e-wallets and online transactions means we’re perfectly equipped to tackle your QIWI wallet issues.
Have peace of mind, we employ the latest techniques and stay updated with the
current security protocols.
If you’ve been hit with unauthorized transactions or technical glitches that led to a loss of funds, our team is ready to assist.
Our skillset in digital wallets and online transactions means we’re well-prepared to tackle your QIWI wallet issues.
Rest assured, we use advanced techniques and are well-versed
in the latest recovery methods.
For those who’ve been hit with unauthorized transactions
or errors that resulted in a loss of funds, we’re here to help.
Unsure of how to start the recovery of your QIWI wallet funds?
Our professional advisors are ready to help to guide you through the procedure and respond to any queries you may encounter.
Choosing our company, you’re choosing a trusted ally
in getting your money back.
Confused about how to go about the recovery of your QIWI wallet funds?
Our professional advisors are on standby 24/7 to guide you through the steps and respond to any questions you may encounter.
With us, you’re choosing a trusted ally in financial recovery.
Have funds disappeared on your QIWI wallet?
We understand how stressful that can be.
Stay calm—our team specializes in retrieving missing money from
QIWI wallets.
Having a high success rate, we’re positive we can help
out.
Get in touch and let’s begin of getting your money back.
Our skillset in digital wallets and electronic payments means we’re well-prepared to tackle your QIWI wallet issues.
Rest assured, we utilize state-of-the-art techniques and are well-versed in the current security protocols.
If you’ve been affected by unauthorized transactions or technical
glitches that led to a loss of funds, our team is ready to assist.
Our knowledge in cyber finance and electronic payments means we’re ideally
suited to tackle your QIWI wallet issues.
Rest assured, we employ state-of-the-art techniques and keep up with the current recovery
methods.
For those who’ve been victimized by unauthorized transactions or technical glitches that resulted in a loss
of funds, we’re here to help.
Overwhelmed by how to start the recovery of your QIWI wallet funds?
Our support team are available 24/7 to guide you through the process and answer
any concerns you might have.
With us, you’re selecting a reliable helper in financial
recovery.
Our knowledge in cyber finance and electronic payments means we’re perfectly
equipped to tackle your QIWI wallet issues.
Rest assured, we utilize advanced techniques and keep up with the newest security protocols.
In case of affected by unauthorized transactions or issues that caused a loss of funds, our
team is ready to assist.
Our skillset in digital wallets and online transactions means we’re well-prepared to tackle your QIWI wallet issues.
Be assured, we utilize state-of-the-art techniques and keep up with
the latest security protocols.
For those who’ve been victimized by unauthorized transactions
or errors that led to a loss of funds, you’ve got an ally in us.
Worried about your QIWI wallet transactions?
Let us handle the stress in retrieving what isrightfully yours.
Get in touch now and start the recovery journey.