MongoDB with FastAPI & Python

Lesson 2 of 6

Setting Up FastAPI and MongoDB

1. Install the pieces

pip install fastapi uvicorn motor
  • fastapi, the web framework itself.
  • uvicorn, the server that actually runs your FastAPI app.
  • motor, the official async MongoDB driver for Python.

2. A minimal app

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello, Kodstigen!"}

Run it with:

uvicorn main:app --reload

--reload restarts the server automatically whenever you save a file, handy during development.

3. Connecting to MongoDB

from motor.motor_asyncio import AsyncIOMotorClient

client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client.kodstigen_db
tasks_collection = db.tasks

A MongoDB server organizes data into databases, which contain collections (roughly, a collection is like a table), which contain documents (roughly, a document is like a row).

📝 Setup Quiz

Passing score: 70%
  1. 1.Which package actually runs (serves) a FastAPI application?

  2. 2.Running uvicorn with the ____ flag restarts the server automatically when files change.

  3. 3.In MongoDB, a collection contains documents, similar to how a table contains rows.