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: Taskas a parameter tells FastAPI to parse and validate the request body as aTask.response_model=TaskOutshapes and validates what gets sent back, and shows up correctly in the auto-generated docs.- Raising
HTTPExceptionis how you return a non-200 status code with a message.