Build High‑Performance APIs with FastAPI and Swagger: A Hands‑On Guide
Learn how to create fast, modern Python APIs using FastAPI, automatically generate interactive Swagger documentation, and enhance your endpoints with validation, metadata, and a full-featured to‑do list project, all illustrated with clear code examples and step‑by‑step deployment instructions.
FastAPI is a modern, high‑performance Python web framework designed for building APIs, while Swagger is an open‑source tool built around the OpenAPI specification that helps design, build, document, and use RESTful web services.
This article explores the basics of FastAPI and Swagger through analogies, code snippets, and practical examples, enabling you to create APIs with FastAPI and explore them via Swagger's interactive UI.
FastAPI
FastAPI provides the following features for modern Python developers:
Speed : performance comparable to Node.js and Go.
Ease of use : simple syntax aided by Python type hints.
Built‑in validation : automatic request validation using Pydantic models.
Automatic documentation : generates interactive docs displayed with Swagger.
Swagger
Swagger simplifies API documentation and testing. When combined with FastAPI, it offers an interactive interface where developers can explore and test API endpoints, view input/output requirements, and more.
Analogy: FastAPI as a restaurant kitchen
FastAPI is like an efficiently organized kitchen allowing chefs to quickly and accurately prepare dishes (APIs).
Swagger acts as the menu, clearly describing each dish (endpoint) and letting customers (developers) order (test) them.
Waiter represents FastAPI routing, ensuring the correct dish (response) reaches the customer.
Getting Started with FastAPI
Installation
To install FastAPI and its ASGI server uvicorn , run:
<code>pip install fastapi uvicorn</code>Create Your First API
Let's create a simple API that greets users by name.
Code Example:
<code>from fastapi import FastAPI
app = FastAPI()
@app.get("/greet/{name}")
def greet(name: str):
return {"message": f"Hello, {name}!"}
</code>Run the API:
Save the code to a file named main.py .
Start the server with Uvicorn:
<code>uvicorn main:app --reload</code>The --reload flag enables hot‑reload, automatically updating the server after code changes.
Open a browser and visit http://127.0.0.1:8000/docs .
Viewing FastAPI in Swagger
Visiting the docs URL shows Swagger's interactive UI with endpoint list, method details, and interactive testing.
Endpoint list : all available API endpoints grouped by tags.
Method details : HTTP method, parameters, request body, and response schema.
Interactive testing : input values and execute requests directly.
For the example endpoint /greet/{name} , entering a name like “John” and clicking “Execute” returns {"message": "Hello, John!"} .
Understanding FastAPI’s Swagger
FastAPI automatically generates an OpenAPI specification describing your API’s structure, routes, request/response patterns, and metadata.
Key Features of Swagger UI
Interactive testing : send requests and view responses directly.
Clear documentation : overview of all endpoints, methods, and parameters.
Error handling : descriptive error messages for issues.
Customizable : enhance UI with tags, summaries, and descriptions.
Enhancing Your API with FastAPI and Swagger
Adding Request Validation
FastAPI’s Pydantic models allow validation of request data, ensuring inputs match expected formats.
Example:
<code>from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_offer: bool = False
@app.post("/items/")
def create_item(item: Item):
return {"item_name": item.name, "item_price": item.price}
</code>In Swagger UI, the /items/ endpoint appears with a request body schema; you can input name , price , and is_offer . Swagger validates input and provides error messages for invalid data.
Adding Metadata
You can enrich Swagger UI with tags, summaries, and descriptions.
Example:
<code>@app.get("/users/", tags=["users"], summary="Get all users", description="Retrieve a list of all registered users.")
def read_users():
return ["Alice", "Bob", "Charlie"]
</code>The /users/ endpoint appears under the “users” tag, and the summary and description give developers additional context.
Full Project: Building a To‑Do List API
Let's build a simple to‑do list API to consolidate what we have learned.
Code Example:
<code>from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
app = FastAPI()
todos = []
class TodoItem(BaseModel):
id: int
title: str
completed: bool = False
@app.get("/todos/", response_model=List[TodoItem], tags=["todos"], summary="Get all to‑do items", description="Retrieve the list of all to‑do items.")
def get_todos():
return todos
@app.post("/todos/", response_model=TodoItem, tags=["todos"], summary="Create a to‑do item", description="Add a new to‑do item to the list.")
def create_todo(todo: TodoItem):
todos.append(todo)
return todo
@app.put("/todos/{todo_id}", response_model=TodoItem, tags=["todos"], summary="Update a to‑do item", description="Update details of a to‑do item by ID.")
def update_todo(todo_id: int, todo: TodoItem):
for i, t in enumerate(todos):
if t.id == todo_id:
todos[i] = todo
return todo
return {"error": "To‑do item not found"}
@app.delete("/todos/{todo_id}", tags=["todos"], summary="Delete a to‑do item", description="Delete a to‑do item by ID.")
def delete_todo(todo_id: int):
global todos
todos = [t for t in todos if t.id != todo_id]
return {"message": "To‑do item deleted"}
</code>Running Steps
Save the code to todo_api.py .
Start the server:
<code>uvicorn todo_api:app</code>Open http://127.0.0.1:8000/docs to explore the to‑do API.
In Swagger you will see endpoints for listing, creating, updating, and deleting to‑do items, each with request/response schemas and interactive testing options.
Conclusion
FastAPI and Swagger provide a seamless experience for building and documenting APIs. FastAPI’s speed and simplicity combined with Swagger’s interactive documentation make them a powerful combination for modern API development.
Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.