1. What is FastAPI?¶
FastAPI is a modern, fast (high-performance) Python-based web framework for building APIs. It has several outstanding features:
- High Performance: Built on Starlette and Pydantic, with performance close to Node.js and Go
- Automatic API Documentation: Automatically generates interactive Swagger UI and ReDoc documentation
- Type Hint Support: Uses Python type hints for automatic data validation and documentation generation
- Simple and Easy to Use: Concise code with a gentle learning curve, suitable for beginners to get started quickly
2. Installing FastAPI¶
To start using FastAPI, first install it along with an ASGI server like Uvicorn:
pip install fastapi uvicorn
3. Basic Route Definition¶
Routes map URLs to handler functions in an API. FastAPI uses the @app decorator to define routes.
3.1 The Most Basic Route¶
from fastapi import FastAPI
# Create a FastAPI application instance
app = FastAPI()
# Define a GET request route with path "/"
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
@app.get("/"): This is a path operation decorator that handles GET requests at the root path/def read_root(): The handler function that returns a dictionary (FastAPI automatically converts it to a JSON response)
3.2 Routes with Path Parameters¶
Path parameters are dynamic parts of the URL, such as 123 in /items/123.
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id, "message": f"你请求的商品ID是: {item_id}"}
{item_id}: Path parameter, whereitem_idis the parameter nameitem_id: int: Parameter type hint, FastAPI automatically validates and converts the type- When accessing
/items/5, it returns{"item_id": 5, "message": "你请求的商品ID是: 5"}
3.3 Routes with Query Parameters¶
Query parameters are key-value pairs after the ? in the URL, used to pass additional information.
@app.get("/search")
def search_items(q: str = None, limit: int = 10):
return {"query": q, "limit": limit}
q: str = None: Query parameterqwith a default value ofNonelimit: int = 10: Query parameterlimitwith a default value of 10- When accessing
/search?q=test&limit=5, it returns{"query": "test", "limit": 5}
4. Request Handling¶
When receiving data from clients (like JSON data in POST requests), FastAPI uses request bodies.
4.1 Using Pydantic Models to Define Request Bodies¶
Pydantic is a data validation library. FastAPI uses it to define request data structures:
from pydantic import BaseModel
# Define data model
class Item(BaseModel):
name: str
price: float
is_offer: bool = None # Optional field with default value None
@app.post("/items/")
def create_item(item: Item):
return {"item_name": item.name, "item_price": item.price}
- The
Itemclass inherits fromBaseModeland defines three fields:name(string),price(float), andis_offer(boolean, optional) - In the
create_itemfunction, theitem: Itemparameter indicates receiving a request body of type Item - FastAPI automatically parses the JSON data from the request body and validates if the data types match
4.2 Testing with Request Body¶
Send a POST request using curl:
curl -X POST "http://localhost:8000/items/" \
-H "Content-Type: application/json" \
-d '{"name": "iPhone", "price": 999.99, "is_offer": true}'
5. Response Handling¶
FastAPI automatically converts function return values into JSON responses.
5.1 Returning Pydantic Models¶
@app.get("/items/{item_id}", response_model=Item)
def get_item(item_id: int):
# Simulate database query
return {"name": "Example Item", "price": 100.0, "is_offer": None}
response_model=Item: Specifies the model for response data. FastAPI automatically converts the returned dictionary to an Item model and generates the corresponding JSON structure- The response will include
name,price, andis_offerfields, even if some fields in the model areNone
5.2 Returning Status Codes¶
Use the status_code parameter to specify the HTTP status code:
@app.post("/items/", status_code=201) # 201 indicates "Created Successfully"
def create_item(item: Item):
return item # Return the created Item data
Common status codes:
- 200 OK: Default status code (success for GET/POST)
- 201 Created: Resource created successfully (POST)
- 404 Not Found: Resource not found
- 400 Bad Request: Request parameter error
5.3 Returning Dictionaries or Simple Types¶
@app.get("/hello/{name}")
def say_hello(name: str):
return {"message": f"Hello, {name}!"} # Returns a dictionary
Or return a string:
@app.get("/version", response_class=str)
def get_version():
return "1.0.0" # Returns a string
6. Complete Example¶
Here’s a complete FastAPI application with routes, requests, and responses:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI(title="FastAPI Basic Example")
# Define data model
class Item(BaseModel):
name: str
price: float
is_offer: bool = None
# 1. Root route
@app.get("/")
def read_root():
return {"message": "Welcome to the FastAPI Example API!"}
# 2. Route with path parameters
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "query": q}
# 3. Route with request body
@app.post("/items/", response_model=Item, status_code=201)
def create_item(item: Item):
return item # Return the created Item object
# 4. Another route with parameters
@app.get("/search")
def search_items(q: str = None, limit: int = 10):
return {"search_term": q, "limit": limit}
7. Running and Testing¶
- Save the code to a file named
main.py - Run the application with Uvicorn:
uvicorn main:app --reload
main:app: Import theappinstance from themain.pyfile--reload: Automatically reload code, convenient for debugging during development
- Access API documentation:
- Swagger UI:http://localhost:8000/docs
- ReDoc:http://localhost:8000/redoc
8. Summary¶
Through this article, you should have mastered the basic usage of FastAPI:
- Define routes using the
@appdecorator - Handle path parameters and query parameters
- Use Pydantic models to receive request bodies
- Return response data and set status codes
- Use automatically generated API documentation for testing
The core advantages of FastAPI lie in its simplicity and automatic documentation features, making API construction and maintenance more efficient. You can explore more advanced features next, such as dependency injection, middleware, and asynchronous processing.