Master FastAPI: Build High‑Performance Python APIs Quickly
This article introduces FastAPI, a modern high‑performance Python web framework, walks through installation, basic routing, async handling, query and path parameters, data modeling with Pydantic, template rendering with Jinja2, and compares its speed to Flask, providing complete code examples and screenshots.
What is FastAPI?
FastAPI is a modern, high‑performance web framework for building APIs with Python 3.6+ using standard type hints. It is built on Starlette and Pydantic, and its syntax is very similar to Flask, making the transition easy.
Installation
pip install fastapi
pip install uvicornFirst Application
Create a main.py file with the following content:
from fastapi import FastAPI
app = FastAPI()
@app.get("/") # root route
async def root():
return {"武汉": "加油!!!"}
@app.get("/say/{data}")
async def say(data: str, q: int = None):
return {"data": data, "item": q}Run the server with: uvicorn main:app --reload Uvicorn is an ASGI server built on uvloop and httptools, providing lightning‑fast performance.
After starting, the server listens on http://127.0.0.1:8000 and returns the JSON response shown above.
Async Endpoints
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"武汉": "加油!!!"}
@app.get("/say/{data}")
async def say(data: str, q: int = None):
return {"data": data, "q": q}Query Parameters
FastAPI automatically parses query parameters. Example:
from fastapi import FastAPI
app = FastAPI()
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
return fake_items_db[skip: skip + limit]Access with http://127.0.0.1:8000/items/?skip=0&limit=10 to retrieve a slice of the list.
Path and Query Parameters Combined
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: str, q: str = None, short: bool = False):
item = {"item_id": item_id}
if q:
item.update({"q": q})
if not short:
item.update({"description": "This is an amazing item that has a long description"})
return itemFastAPI converts various truthy strings (e.g., 1, true, yes) to True for boolean parameters.
Data Models with Pydantic
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str = "武汉加油 !!"
description: str = None
price: float = 233
tax: float = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return itemSending a POST request with a JSON body matching Item returns the same data.
Updating Resources
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
app = FastAPI()
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, q: str = None):
result = {"item_id": item_id, **item.dict()}
if q:
result.update({"q": q})
return resultThe PUT method updates an existing item and returns the combined dictionary.
Template Rendering with Jinja2
FastAPI does not include a built‑in template engine, but you can use Jinja2.
pip install jinja2
pip install aiofiles # for async static files from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import uvicorn
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/data/{data}")
async def read_data(request: Request, data: str):
return templates.TemplateResponse("index.html", {"request": request, "data": data})
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)Template index.html:
<html>
<head><title>武汉加油</title></head>
<body><h1>高呼: {{ data }}</h1>
</body>
</html>Accessing http://127.0.0.1:8000/data/武汉加油 renders the HTML with the provided data.
Performance Comparison
Benchmarks show FastAPI outperforms Flask and even the asynchronous framework Tornado in concurrency.
Conclusion
FastAPI offers a simple, fast, and robust way to build APIs with automatic validation, interactive documentation, and async support. While its ecosystem is still growing compared to Flask, its performance advantages make it a compelling choice for modern backend development.
Official documentation: https://fastapi.tiangolo.com/
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
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.
