1. Introduction to FastAPI and Uvicorn¶
In the field of Python web development, FastAPI has become a highly popular high-performance web framework in recent years. It is based on standard Python type hints, supports asynchronous operations, and automatically generates API documentation, making it extremely efficient for development. Uvicorn, on the other hand, is a lightweight ASGI (Asynchronous Server Gateway Interface) server specifically designed for high-performance Python web applications, and it is also one of the officially recommended servers for FastAPI.
In simple terms, FastAPI is responsible for defining API interface logic, while Uvicorn handles receiving requests, processing concurrency, and returning responses. When used together, they enable both rapid development and stable deployment.
2. Environment Installation¶
1. Create a Virtual Environment (Recommended)¶
To avoid dependency conflicts, it is recommended to create a virtual environment first:
# Create a virtual environment
python -m venv venv
# Activate the virtual environment (Windows)
venv\Scripts\activate
# Activate the virtual environment (Mac/Linux)
source venv/bin/activate
2. Install FastAPI and Uvicorn¶
Execute the following command in the activated virtual environment:
pip install fastapi uvicorn
After installation, you can verify the successful installation with pip list.
3. Local Development Environment Configuration¶
1. Write the First FastAPI Application¶
Create a file named main.py and add the following code:
from fastapi import FastAPI
# Initialize the FastAPI application
app = FastAPI()
# Define a root route ("/") that returns JSON data
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI+Uvicorn!"}
# Define a route with parameters (e.g., "/items/123")
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "query": q}
2. Start the Application with Uvicorn¶
Execute the following command in the terminal to start the server:
uvicorn main:app --reload
- Parameter Explanation:
main:app: Imports theappobject (i.e., the FastAPI instance) from themain.pyfile.--reload: Automatically reloads the code in development mode (no manual restart needed after modifications).
3. Verify if the Interface is Running¶
After successful startup, the terminal will display information similar to:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [12345]
You can test the interface in the following ways:
- Browser Access: Open http://127.0.0.1:8000, and the page will display {"message": "Hello, FastAPI+Uvicorn!"}.
- Call the Parameterized Interface: Visit http://127.0.0.1:8000/items/456?query=test, and the return will be {"item_id": 456, "query": "test"}.
4. Basic Production Environment Deployment¶
Using --reload is convenient for debugging locally, but auto-reload should be disabled in production environments, and other optimizations should be configured.
1. Basic Deployment Command¶
Start directly with Uvicorn (without auto-reload):
uvicorn main:app --host 0.0.0.0 --port 8000
- Parameter Explanation:
--host 0.0.0.0: Allows access from external devices (default is only local access to127.0.0.1).--port 8000: Specifies the port (can be changed to another port, e.g.,80requires admin privileges).
2. Multi-Process Deployment (Improve Performance)¶
If the server has multiple CPU cores, start multiple processes using the --workers parameter:
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
--workers 4: Starts 4 worker processes (it is recommended to set this to twice the number of CPU cores).
3. Deploy to a Server (e.g., Alibaba Cloud/Tencent Cloud)¶
- Upload Code: Upload
main.pyand the virtual environment to the server (or create them directly on the server). - Start the Application: Execute the deployment command in the server terminal (ensure the server opens the corresponding port, e.g., 8000).
- Run in Background: To run the application for a long time, use
nohuporsystemdto manage the process:
# Run in the background using nohup
nohup uvicorn main:app --host 0.0.0.0 --port 8000 &
5. Common Issues and Solutions¶
1. What if the Port is Occupied?¶
- Check Occupying Process:
lsof -i :8000(Mac/Linux) ornetstat -ano | findstr :8000(Windows). - Change the Port: Execute
uvicorn main:app --port 8001to use an unoccupied port.
2. Cannot Access the Interface?¶
- Confirm the host Parameter: Ensure
--host 0.0.0.0is used instead of127.0.0.1(the local loopback address only allows access from the local machine). - Check Firewall: The server must open the corresponding port (e.g., 8000). For Ubuntu, use
ufw allow 8000to open the port.
3. Installation Failed?¶
- Update pip:
pip install --upgrade pip. - Confirm Python Version: FastAPI requires Python 3.6+, and Python 3.9+ is recommended.
6. Summary¶
The core steps for the local development and deployment process of FastAPI+Uvicorn are:
1. Development: Use uvicorn main:app --reload to quickly debug the interface.
2. Deployment: Use uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4 to start the production environment.
Through this article, you have mastered basic configuration and common issue handling. In the future, you can explore FastAPI’s asynchronous interfaces, database integration, or Uvicorn’s advanced parameters (such as SSL certificate configuration).
Hands-on Practice: Try modifying main.py to add new interfaces or deploy it to a cloud server to experience the complete development process!