FastAPI Cheat Sheet
-
Installation:
- Install FastAPI using pip:
$ pip install fastapi
- Install FastAPI using pip:
-
Importing FastAPI:
- Import the FastAPI module in your Python script:
from fastapi import FastAPI
- Import the FastAPI module in your Python script:
-
Creating an App:
- Create an instance of the FastAPI class to represent your application:
app = FastAPI()
- Create an instance of the FastAPI class to represent your application:
-
Creating Routes:
- Define routes using the
@app.route()
decorator and specify the HTTP methods:@app.route("/path", methods=["GET"]) async def endpoint_name(): # Endpoint logic goes here return {"message": "Hello, FastAPI!"}
- Define routes using the
-
Request Parameters:
- Access request parameters using function parameters:
@app.route("/items/{item_id}") async def get_item(item_id: int): # Access item_id parameter return {"item_id": item_id}
- Access request parameters using function parameters:
-
Query Parameters:
- Define query parameters using function parameters with default values:
@app.route("/items") async def get_items(skip: int = 0, limit: int = 10): # Access skip and limit query parameters return {"skip": skip, "limit": limit}
- Define query parameters using function parameters with default values:
-
Request Body:
- Define request body models using Pydantic models:
from pydantic import BaseModel class Item(BaseModel): name: str price: float @app.route("/items", methods=["POST"]) async def create_item(item: Item): # Access item request body return {"item": item}
- Define request body models using Pydantic models:
-
Response Models:
- Define response models using Pydantic models:
class Item(BaseModel): name: str price: float @app.route("/items/{item_id}") async def get_item(item_id: int): # Return item response with model return {"item_id": item_id, "name": "Item Name", "price": 9.99}
- Define response models using Pydantic models:
-
Path Operations:
- Use different HTTP methods for the same path by defining separate route functions:
@app.route("/items/{item_id}", methods=["GET"]) async def get_item(item_id: int): # Get item logic @app.route("/items/{item_id}", methods=["PUT"]) async def update_item(item_id: int, item: Item): # Update item logic
- Use different HTTP methods for the same path by defining separate route functions:
-
Middleware:
- Use middleware functions to intercept and modify requests and responses:
@app.middleware("http") async def middleware(request, call_next): # Modify request before passing to route response = await call_next(request) # Modify response before returning return response
- Use middleware functions to intercept and modify requests and responses:
-
Exception Handling:
- Use exception handlers to handle specific exceptions raised within routes:
@app.exception_handler(ExceptionType) async def exception_handler(request, exc): # Handle exception and return custom response return JSONResponse(status_code=400, content={"message": "Error"})
- Use exception handlers to handle specific exceptions raised within routes:
-
Running the App:
- Start the FastAPI application using the
uvicorn
command:
Replace$ uvicorn main:app --reload
main
with the name of your Python script andapp
with the name of your FastAPI instance.
- Start the FastAPI application using the
This cheat sheet covers the basics of FastAPI to help you get started with building web APIs using the framework. For more detailed information, refer to the official FastAPI documentation.