MongoDB with FastAPI & Python

Lesson 5 of 6

Building REST Endpoints

Wiring a Pydantic model and Motor together inside a path operation gives you a real REST endpoint.

from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.post("/tasks", response_model=TaskOut)
async def create_task(task: Task):
    result = await tasks_collection.insert_one(task.model_dump())
    created = await tasks_collection.find_one({"_id": result.inserted_id})
    return {**created, "id": str(created["_id"])}

@app.get("/tasks/{task_id}", response_model=TaskOut)
async def get_task(task_id: str):
    task = await tasks_collection.find_one({"_id": ObjectId(task_id)})
    if task is None:
        raise HTTPException(status_code=404, detail="Task not found")
    return {**task, "id": str(task["_id"])}

Key ideas

  • {task_id} in the route path becomes a function parameter automatically, FastAPI calls this path parameter binding.
  • task: Task as a parameter tells FastAPI to parse and validate the request body as a Task.
  • response_model=TaskOut shapes and validates what gets sent back, and shows up correctly in the auto-generated docs.
  • Raising HTTPException is how you return a non-200 status code with a message.

📝 Endpoints Quiz

Passing score: 70%
  1. 1.How do you return a 404 response from inside a FastAPI path operation?

  2. 2.Writing {task_id} inside a route path like "/tasks/{task_id}" is called a path ____.

  3. 3.Declaring a parameter as `task: Task` tells FastAPI to validate the request body against the Task model.