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).