What is a Web Framework and FastAPI?¶
Before we start, let’s clarify some basic concepts:
Web Framework: Simply put, a web framework is a tool that helps you quickly build web applications. It encapsulates complex details like handling HTTP requests, routing, data processing, etc., allowing you to focus on business logic. Without a framework, you’d need to handle socket connections, parse HTTP protocols, and manage routing manually—this would be extremely tedious.
FastAPI: This is a modern Python-based web framework. Its core features include high performance (powered by Starlette and Pydantic), automatic API documentation (Swagger UI and ReDoc), asynchronous programming support (ideal for high-concurrency scenarios), and data validation. For Python developers, FastAPI has become one of the preferred frameworks for building RESTful APIs.
Installation and Basic Example¶
Install FastAPI and a Server¶
FastAPI is a Python library that requires an ASGI server to run (similar to Django’s Gunicorn+Uvicorn). We’ll use Uvicorn as the server:
pip install fastapi uvicorn
First “Hello World” Application¶
Create a file named main.py with the following code:
from fastapi import FastAPI
# Create an instance of the FastAPI application
app = FastAPI()
# Define a route: triggered when accessing the root path ("/")
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
Run the Application¶
Execute in the terminal:
uvicorn main:app --reload
main:app: Indicates importing theappinstance from themain.pyfile--reload: Automatically restarts the server when code changes are detected (great for development)
Open your browser and visit http://localhost:8000 to see the returned JSON data: {"message": "Hello, FastAPI!"}.
Routing and Parameters¶
Path Parameters¶
You can define dynamic parameters in the URL, such as an interface to get a user ID:
@app.get("/users/{user_id}")
def get_user(user_id: int): # Parameter type is int, with automatic validation
return {"user_id": user_id, "message": f"User {user_id} data"}
- Accessing
http://localhost:8000/users/123returns{"user_id": 123, "message": "User 123 data"} - FastAPI automatically validates parameter types (e.g.,
user_idmust be an integer; otherwise, an error is returned)
Query Parameters¶
For optional parameters, use query parameters:
@app.get("/search")
def search_items(query: str = None, limit: int = 10):
return {"query": query, "limit": limit}
- Accessing
http://localhost:8000/search?query=book&limit=5returns{"query": "book", "limit": 5} - Default values (e.g.,
query: str = None) make parameters optional
Data Validation with Pydantic¶
FastAPI uses the Pydantic library for data validation and serialization to ensure request data matches the expected format.
Define a Data Model¶
Create an Item model:
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_offer: bool = None # Optional field with default None
Use the Model to Receive Request Data¶
@app.post("/items/")
def create_item(item: Item):
return {"item_name": item.name, "item_price": item.price}
- When sending a POST request to
/items/with JSON data (e.g.,{"name": "apple", "price": 5.99}), FastAPI automatically validates the data types - If the data format is invalid (e.g.,
priceis a string), FastAPI returns a clear error message
Request Methods and Data Handling¶
GET vs POST¶
- GET: Used to retrieve data (e.g., query lists), with parameters in the URL. Not suitable for sensitive data.
- POST: Used to submit data (e.g., create resources), with parameters in the request body. More secure.
Handling POST Requests (JSON Data)¶
Use the previously defined Item model to process JSON data:
@app.post("/items/")
def create_item(item: Item):
return {"message": f"Created {item.name}", "price": item.price}
Handling Form Data¶
For HTML form submissions, use the Form class:
from fastapi import Form
@app.post("/login")
def login(username: str = Form(...), password: str = Form(...)):
return {"username": username, "status": "logged in"}
Form(...)indicates the parameter is required; it will be automatically parsed when the user submits the form
Automatic API Documentation¶
One of FastAPI’s most powerful features is automatic generation of interactive API documentation—no manual documentation writing required!
Access Swagger UI¶
After running the app, visit http://localhost:8000/docs to see the visual API documentation interface:
- Test all endpoints directly (click “Try it out”)
- Automatically displays parameter descriptions, response formats, and example data
ReDoc Documentation¶
Visit http://localhost:8000/redoc for an alternative, more concise API documentation format.
Asynchronous Support (Advanced)¶
FastAPI supports asynchronous programming, making it suitable for handling time-consuming operations (e.g., database queries, external API calls):
from fastapi import FastAPI
import asyncio
app = FastAPI()
@app.get("/async-data")
async def get_async_data():
# Simulate an asynchronous operation (e.g., database query)
await asyncio.sleep(1) # Wait for 1 second
return {"data": "This is an async response"}
- Asynchronous endpoints use
async defandawait - Asynchronous programming significantly improves performance in high-concurrency scenarios
Summary and Practical Recommendations¶
FastAPI’s core strengths are simplicity and automatic documentation, making it ideal for rapid RESTful API development.
Beginner Practice Steps:¶
- Install FastAPI and Uvicorn
- Complete basic examples (Hello World, path parameters, query parameters)
- Use Pydantic models for data validation
- Experiment with GET and POST endpoints, testing the API documentation
- Use async functions for simple time-consuming operations
Advanced Directions:¶
- Middleware: Process all requests/responses
- Dependency Injection: Reuse code logic
- Database Integration (SQLAlchemy/FastAPI-SQLAlchemy)
- Middleware and CORS configuration (for cross-origin requests)
FastAPI has a gentle learning curve. From basics to advanced features, you can expand gradually. It’s recommended to combine official documentation with practical projects to get started quickly!