FastAPI is a modern, fast (high-performance) web framework based on standard Python types for building APIs. It is based on standard Python type hints, and its main advantages are speed, type safety, and automatic API documentation generation.
If you are going to use FastAPI, here are some key points and related commands that you must know:
-
Installation :
pip install fastapi[all] pip install uvicorn
fastapi[all]
: Install FastAPI and all its dependencies.uvicorn
: ASGI server, used to run FastAPI applications.
-
Create a basic API :
from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return { "Hello": "World"}
Analysis: In this simple example, we initialize a FastAPI application and define an endpoint. When the user makes a GET request for the root path (
/
), it will be returned{"Hello": "World"}
. -
Run the application :
uvicorn your_filename:app --reload
Parsing: Use
uvicorn
to run your FastAPI application.your_filename:app
Refers to your Python file name and the name of the FastAPI application instance.--reload
Enables automatic restart after code changes in the development environment. -
Path parameters and query parameters :
@app.get("/items/{item_id}") def read_item(item_id: int, q: str = None): return { "item_id": item_id, "q": q}
Analysis:
item_id
It is a path parameter andq
a query parameter. FastAPI will automatically verify the type and display it in the documentation. -
Request body :
Import a data structure from a Pydantic model and use it to validate the request body.from pydantic import BaseModel class Item(BaseModel): name: str description: str = None price: float @app.post("/items/") def create_item(item: Item): return item
Analysis: Using the Pydantic model, request data, serialization and deserialization can be automatically verified, and FastAPI will automatically generate relevant API documents.
-
Automatic API documentation :
Visit/docs
to view the automatically generated Swagger interface, or visit/redoc
to view the Redoc interface.
[Reminder] The above are just some basic contents of FastAPI. The framework also provides many advanced features such as dependency injection, security and OAuth2, event hooks, etc. In order to make full use of FastAPI, it is recommended to read its official documentation in depth.
-
Dependency injection :
FastAPI uses a very powerful dependency injection system. It allows you to easily manage and control database connections, configurations, etc.
Example:
def get_db(): db = "Some DB connection" try: yield db finally: db.close() @app.get("/items/") def read_items(db=Depends(get_db)): return { "items": "Items from " + db}
Analysis:
get_db
It is a dependent function that will be called every time it is requested.read_items
Depends onget_db
the function, soget_db
will be executed first. -
Security :
FastAPI offers a variety of security and authentication options, including password-based authentication, OAuth2, Bearer tokens, and more.
Example (using HTTP Basic authentication):
from fastapi import Depends, HTTPException from fastapi.security import HTTPBasic, HTTPBasicCredentials security = HTTPBasic() def get_current_user(credentials: HTTPBasicCredentials = Depends(security)): if credentials.username != "alice" or credentials.password != "password": raise HTTPException(status_code=400, detail="Incorrect email or password") return credentials.username @app.get("/users/me") def read_current_user(username: str = Depends(get_current_user)): return { "username": username}
Analysis: HTTP Basic authentication is used in this example. If the username and password do not match, it will return an HTTP 400 error.
-
OAuth2 :
OAuth2 is an authorization framework and FastAPI provides support for it.
Example (using Password mode):
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @app.post("/token") def login(form_data: OAuth2PasswordRequestForm = Depends()): if form_data.username != "alice" or form_data.password != "password": raise HTTPException(status_code=400, detail="Incorrect username or password") return { "access_token": form_data.username, "token_type": "bearer"} @app.get("/users/me") def read_current_user(token: str = Depends(oauth2_scheme)): return { "token": token}
Resolution: The user needs to first
/token
obtain a token using their username and password via the endpoint, and then the token can be used for subsequent requests. -
Event hook :
FastAPI provides event "hooks" or callbacks that allow code to be executed when the application starts and shuts down.
Example:
@app.on_event("startup") async def startup_event(): app.state.database = "Some database connection" @app.on_event("shutdown") async def shutdown_event(): app.state.database.close()
Analysis: When the application starts,
startup_event
the function will be called and can set the application state, such as database connection. Similarly, when the application is closed,shutdown_event
the function will be called and can be used to close resources, such as database connections.
These are just a brief overview of FastAPI features. To fully understand and utilize them, it is recommended to consult FastAPI’s official documentation, which provides detailed explanations and examples for each feature.