Building Your First REST API with FastAPI: Step-by-Step Guide
Building Your First REST API with FastAPI: Step-by-Step Guide
FastAPI has become one of the most popular Python frameworks for building APIs in 2026, and for good reason. It’s fast (as the name suggests), automatically generates OpenAPI documentation, and uses modern Python features like type hints and async/await. I’ve used it for production APIs serving millions of requests, but it’s also friendly enough for your first API project. Here’s how to build one from scratch.
What We’re Building
A simple task management API with CRUD operations (Create, Read, Update, Delete). It’ll store tasks in memory (for simplicity), and by the end you’ll have a working API you can test with your browser or a tool like curl or Postman. The same patterns apply to any data you want to serve through an API — blog posts, user profiles, product listings.
Step 1: Set Up Your Environment
You’ll need Python 3.10 or newer (Python 3.13 is current in 2026). Create a project directory and a virtual environment:
mkdir task-api
cd task-api
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
Install FastAPI and an ASGI server:
pip install fastapi uvicorn
That’s it for dependencies. FastAPI doesn’t require much boilerplate.
Step 2: Your First Endpoint
Create a file called main.py:
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
app = FastAPI(title="Task API")
class Task(BaseModel):
id: Optional[int] = None
title: str
completed: bool = False
tasks = []
next_id = 1
@app.get("/")
def root():
return {"message": "Task API is running"}
@app.get("/tasks")
def list_tasks():
return tasks
Run it with: uvicorn main:app --reload
Open http://127.0.0.1:8000 in your browser — you’ll see the JSON response. Open http://127.0.0.1:8000/docs for auto-generated interactive API documentation.
Step 3: Add Create, Update, and Delete
@app.post("/tasks", status_code=201)
def create_task(task: Task):
global next_id
task.id = next_id
next_id += 1
tasks.append(task)
return task
@app.get("/tasks/{task_id}")
def get_task(task_id: int):
for task in tasks:
if task.id == task_id:
return task
return {"error": "Task not found"}, 404
@app.put("/tasks/{task_id}")
def update_task(task_id: int, updated: Task):
for i, task in enumerate(tasks):
if task.id == task_id:
updated.id = task_id
tasks[i] = updated
return updated
return {"error": "Task not found"}, 404
@app.delete("/tasks/{task_id}", status_code=204)
def delete_task(task_id: int):
for i, task in enumerate(tasks):
if task.id == task_id:
tasks.pop(i)
return
return {"error": "Task not found"}, 404
Step 4: Understanding What Just Happened
FastAPI uses Python type hints to automatically validate requests and generate documentation. When you define task: Task as a parameter, FastAPI reads the request body, validates it matches the Task model, and passes it to your function. If the data is invalid (missing required fields, wrong types), FastAPI returns a clear error message without you writing any validation code.
The /docs endpoint is interactive — you can test every endpoint directly in your browser. This alone saves hours of writing and maintaining API documentation.
Making It Production-Ready
For a production API, you’d replace the in-memory list with a database (SQLAlchemy + PostgreSQL is the standard FastAPI pattern), add authentication, and run behind a production ASGI server like Uvicorn with Gunicorn. But the structure stays the same — routes, models, and validation logic follow the patterns you just built. Our full-stack deployment guide covers Dockerizing this API for production deployment.
FastAPI also makes it straightforward to add async endpoints for I/O-bound operations, dependency injection for shared logic (database sessions, authentication), and background tasks. The framework grows with you — it’s beginner-friendly for a first API but production-capable when you’re ready.
Sources: FastAPI official documentation (2026), Uvicorn ASGI server docs, Real Python FastAPI tutorials.