from fastapi import Dependsdefget_token(token:str):return token@app.get("/users/")asyncdefread_users(token:str=Depends(get_token)):return{"token": token}
Security: OAuth2 with password and bearer token.
from fastapi.security import OAuth2PasswordBeareroauth2_scheme =OAuth2PasswordBearer(tokenUrl="token")@app.get("/users/me")asyncdefread_users_me(token:str=Depends(oauth2_scheme)):return{"token": token}
Background Tasks: Run background tasks.
from fastapi import BackgroundTasksdefwrite_log(message:str):withopen("log.txt","a")as log: log.write(message)@app.post("/send-notification/{email}")asyncdefsend_notification(email:str,background_tasks: BackgroundTasks): background_tasks.add_task(write_log,f"Notification sent to {email}")return{"message":"Notification sent"}
WebSockets: Support for WebSocket.
from fastapi import WebSocket@app.websocket("/ws")asyncdefwebsocket_endpoint(websocket: WebSocket):await websocket.accept()await websocket.send_text("Hello, WebSocket!")await websocket.close()
Middleware: Add middleware for handling requests and responses.
from fastapi.middleware.cors import CORSMiddlewareapp.add_middleware( CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)
from fastapi.staticfiles import StaticFilesapp.mount("/static", StaticFiles(directory="static"),name="static")
Custom Responses: Return custom responses.
from fastapi.responses import JSONResponse@app.get("/custom_response")asyncdefcustom_response():returnJSONResponse(content={"message":"Custom Response"})
Database Integration: Easily integrate with databases (example with SQLAlchemy).
from sqlalchemy import create_engine, Column, Integer, String, Sequencefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmakerSQLALCHEMY_DATABASE_URL="sqlite:///./test.db"engine =create_engine(SQLALCHEMY_DATABASE_URL)SessionLocal =sessionmaker(autocommit=False,autoflush=False,bind=engine)Base =declarative_base()classUser(Base): __tablename__ ="users"id=Column(Integer, Sequence("user_id_seq"),primary_key=True,index=True) name =Column(String,index=True)Base.metadata.create_all(bind=engine)@app.get("/users/{user_id}")asyncdefread_user(user_id:int,db: Session =Depends(get_db)): user = db.query(User).filter(User.id == user_id).first()return user
Asynchronous Support: First-class support for async and await.
@app.get("/async")asyncdefread_async():awaitsome_async_function()return{"message":"Async function called"}
OpenAPI and JSON Schema: Automatically generated OpenAPI and JSON Schema docs.
# No code needed; FastAPI automatically generates this at /docs and /redoc
These features and examples demonstrate the versatility and powerful capabilities of FastAPI.
2
tell me another 20
Sure! Here are 20 more features of FastAPI along with code examples:
Custom Request Validation: Define custom validation logic for requests.
Internationalization (i18n): Support for multiple languages.
APIRouter: Use routers to organize your application.
SQLAlchemy Integration: Use SQLAlchemy for database interactions.
Alembic Integration: Database migrations with Alembic.
Dependency Overrides: Override dependencies for testing or specific use cases.
Custom Routers: Create custom routers for different modules.
WebSocket Authentication: Handle authentication for WebSocket connections.
Custom URL Converters: Create custom URL converters for routes.
CLI Commands: Create custom CLI commands.
Environment Variables: Use environment variables for configuration.
These additional features and examples further illustrate the comprehensive capabilities of FastAPI, making it a versatile and powerful framework for building APIs.
3
tell me anoter 20
Of course! Here are 20 more features of FastAPI along with code examples:
Middleware for Logging: Implement logging with middleware.
Custom Response Class: Create and use custom response classes.
: str = Depends(oauth2_scheme)): if security_scopes.scopes and "admin" not in security_scopes.scopes: raise HTTPException(status_code=403, detail="Not enough permissions") return {"username": "admin"}
62. Response Compression: Enable Gzip compression for responses. ```python from fastapi.middleware.gzip import GZipMiddleware
63. Locale Detection: Automatically detect and handle user locales. ```python from fastapi_babel import Babel
64. Token-Based Rate Limiting: Implement token-based rate limiting. ```python from slowapi import Limiter from slowapi.util import get_remote_address
65. WebSocket Broadcast: Broadcast messages to multiple WebSocket clients. ```python from fastapi import WebSocket, WebSocketDisconnect from typing import List
66. Dependency Override in Tests: Override dependencies in tests. ```python from fastapi.testclient import TestClient
67. Request Hooks: Implement hooks to process requests before they reach the route. python @app.middleware("http") async def add_process_time_header(request: Request, call_next): start_time = time.time() response = await call_next(request) process_time = time.time() - start_time response.headers["X-Process-Time"] = str(process_time) return response
FastAPI with Celery: Integrate FastAPI with Celery for task queues.
SQLAlchemy with Alembic: Integrate SQLAlchemy with Alembic for migrations.
Admin Interface: Integrate with an admin interface (e.g., fastapi-admin).
These features, along with the previously mentioned ones, illustrate the extensive functionality and flexibility that FastAPI offers for building modern web APIs and applications.
4
give me another 20
Sure! Here are another 20 features of FastAPI along with code examples:
Custom Dependency Classes: Use custom classes as dependencies.
SQLAlchemy with FastAPI: Integrate SQLAlchemy ORM with FastAPI.
Testing Dependencies: Override dependencies in tests.
Peewee ORM: Use Peewee ORM with FastAPI.
CORS Configuration: Configure CORS for specific routes.
Custom Field Validation: Use Pydantic for custom field validation.
Event-driven Architecture: Use event handlers for different stages.
WebSocket Middleware: Implement middleware for WebSocket connections.
Custom Dependencies with State: Use FastAPI state to share dependencies.
Dependency Injection with Context Managers: Use context managers as dependencies.
GraphQL with Strawberry: Use Strawberry for GraphQL API.
HTML Forms Handling: Handle HTML forms with FastAPI.
FastAPI with Django ORM: Use FastAPI with Django ORM.
SQLAlchemy with PostgreSQL: Use SQLAlchemy with PostgreSQL.
Data Encryption: Encrypt and decrypt data in FastAPI.
Rate Limiting with Redis: Use Redis for rate limiting.
WebSocket Authentication with JWT: Authenticate WebSocket connections with JWT.
Throttling: Implement request throttling.
HTML Template Rendering: Render HTML templates with Jinja2.
Rate Limiting with FastAPI-Limiter: Use fastapi-limiter for rate limiting.
GraphQL with Graphene: Use Graphene for GraphQL APIs.
Event Notifications: Implement event notifications. ```python from pydantic import BaseModel
These features and examples illustrate the extensive and diverse capabilities of FastAPI for creating robust and scalable APIs and applications.
5
I apologize for the previous issues. Here are the 20 features with properly formatted code examples:
101. Automatic Documentation Generation
FastAPI automatically generates interactive API documentation at /docs (Swagger UI) and /redoc (ReDoc).
102. Dependency Injection for Classes
Use class-based dependencies.
103. GraphQL Subscriptions
Implement GraphQL subscriptions with WebSockets.
104. Redis Cache Integration
Use Redis for caching.
105. Dependency Overriding
Override dependencies for testing.
106. Pydantic Settings Management
Use Pydantic for settings management.
107. Database Transactions
Use transactions with databases.
108. OpenAPI Customization
Customize the OpenAPI schema.
109. Async Task Queues with RQ
Use RQ for background tasks.
110. File Streaming
Stream files to the client.
111. Rate Limiting with IP Address
Implement rate limiting based on IP addresses.
112. Streaming JSON Responses
Stream JSON responses to the client.
113. Session Management
Use sessions for user management.
114. WebSocket Chat
Implement a WebSocket chat server.
115. Advanced Dependency Injection
Use advanced dependency injection with classes and methods.
116. Request Validation
Custom request validation with Pydantic.
117. OAuth2 with JWT
Implement OAuth2 authentication with JWT tokens.
118. Handling Background Tasks
Run background tasks in FastAPI.
119. WebSocket Authentication
Handle authentication for WebSocket connections.
120. SQLAlchemy Integration with FastAPI
Use SQLAlchemy ORM with FastAPI.
121. Role-Based Access Control (RBAC)
Implement RBAC with FastAPI.
122. Custom Middleware
Create and use custom middleware in FastAPI.
123. Request Validation with Dependencies
Validate requests with custom dependencies.
124. Dependency Injection for Multiple Levels
Use dependencies that depend on other dependencies.
125. Rate Limiting with FastAPI-Limiter
Implement rate limiting using the fastapi-limiter library.
These additional features and examples further illustrate the flexibility and power of FastAPI in building modern web APIs and applications.
6
I have 4 routes in FastAPI. Out of 4, 3 of them having tenant_id like below
I want to keep middleware where I would prepend tenant_id without specifically mention in each route.
To apply a middleware that automatically handles the tenant_id in FastAPI, you can create a middleware component that extracts the tenant_id from the path of incoming requests and then makes it conveniently available throughout your application, perhaps by attaching it to the request state.
Here's how you can define such middleware:
Create a Middleware: This middleware will capture requests, extract the tenant_id from the path if present, and then store it in the request state for use in your endpoint functions.
Use Starlette's Request Object: Since FastAPI is built on Starlette, you can utilize the request object's state to pass around the tenant_id.
Here's an example of how you might implement this:
Explanation
Middleware: TenantMiddleware checks each request's URL path for a tenant_id pattern. If found, it stores this tenant_id in the request.state, which is accessible throughout the lifecycle of the request.
Regex Usage: The regex r'^/(\d+)/' is used to extract the first group of digits in the path, which is assumed to be the tenant_id. You can adjust the regex to match the specific format of your tenant_id.
Endpoint: In the endpoint function, tenant_id is retrieved from request.state. If it's not found (i.e., None), an HTTP exception is raised. This centralizes the handling of tenant_id and avoids repeating the extraction logic in each endpoint.
By using this middleware, you simplify your route handlers by removing the need to manually extract the tenant_id from the path, ensuring that the ID handling logic is consistent and easily maintainable across your application.
7
Dependency Injection for Multiple Levels
how to use this in FastAPI in realtime
Dependency Injection (DI) in FastAPI is a powerful feature that allows you to decouple components and ensure that dependencies are managed automatically by the framework. This makes your code cleaner, easier to test, and more modular. FastAPI uses a system where dependencies are "injected" into your path operation functions as arguments.
Here’s a step-by-step guide to using dependency injection in FastAPI, especially focusing on multiple levels of dependencies:
1. Basic Dependency
A dependency in FastAPI can be any callable that returns a value. These are often used to provide database connections, configurations, or custom logic that can be reused across multiple endpoints.
2. Multiple Level Dependencies
Dependencies can also depend on other dependencies, creating a chain or a tree of dependencies. This is useful when a particular service or component requires another service.
3. Sub-dependencies
Here’s how you might define a sub-dependency where one dependency function relies on another. This allows you to build a complex but manageable dependency injection system.
4. Using Classes for Dependencies
You can also use classes for organizing dependencies. This is useful when your dependencies have state or configuration.
5. Advanced Usage with Scopes
FastAPI allows you to specify how often a dependency should be reused. This can be configured using use_cache in the Depends function.
Real-Time Considerations
When considering real-time applications or features:
Cache Control: Managing the use_cache parameter carefully ensures that dependencies are re-evaluated as needed, which is critical in high-concurrency or rapidly-changing data environments.
Async Dependencies: If your dependency involves IO operations (like database or network calls), it should ideally be asynchronous to avoid blocking the server loop.
Error Handling: Dependencies can also perform error handling or security checks, which can preemptively return errors before reaching the actual business logic of your endpoints.
This approach to dependency injection keeps your FastAPI application modular, testable, and clean, enabling you to manage complex dependencies efficiently in real-time operations.
8
Give me some real time sample for "Error Handling" in FastAPI
Error handling in FastAPI is critical for managing exceptions and providing meaningful error responses to clients. FastAPI offers several built-in tools to streamline error handling, including exception handlers and dependency injections that can pre-validate data or manage security concerns. Here, I'll show you how to effectively use FastAPI’s features to handle errors in a practical, real-world application context.
1. Using HTTPException for Simple Error Handling
One of the simplest ways to handle errors in FastAPI is by raising an HTTPException when something goes wrong.
2. Custom Exception Handlers
You can define custom exception handlers to catch specific exceptions and return custom responses. This is particularly useful for catching broad exceptions that might be raised by libraries or your own code.
3. Custom Dependency with Error Handling
Dependencies in FastAPI can be used to encapsulate security logic, parameter validation, or any other preparatory steps that should happen before an endpoint function is called.
4. Handling Errors in Background Tasks
Background tasks in FastAPI can also benefit from structured error handling, especially to avoid silent failures.
Real-World Considerations
Extensive Use of HTTPException: For API endpoints, using HTTPException is common practice for immediately stopping request processing and responding with a specific HTTP status code.
Logging: Ensure that all exceptions are logged properly. This helps in debugging and understanding the paths that lead to errors.
User Feedback: Customize error messages to be helpful but avoid exposing sensitive details or implementation specifics that could be exploited.
These examples cover various scenarios of error handling in FastAPI, each tailored to different aspects of an application's needs, from simple validations to managing asynchronous tasks.
from fastapi import HTTPException, Request
@app.post("/validate/")
async def validate_request(request: Request):
data = await request.json()
if "key" not in data:
raise HTTPException(status_code=400, detail="Key not found in request")
return {"message": "Valid request"}
from fastapi.responses import JSONResponse
class UnicornException(Exception):
def __init__(self, name: str):
self.name = name
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
return JSONResponse(status_code=418, content={"message": f"Oops! {exc.name} did something."})
@app.get("/unicorns/{name}")
async def read_unicorn(name: str):
if name == "yolo":
raise UnicornException(name=name)
return {"unicorn_name": name}
from fastapi import status
@app.post("/status/", status_code=status.HTTP_201_CREATED)
async def create_item():
return {"message": "Item created"}
from fastapi.responses import PlainTextResponse
@app.get("/custom_response", response_class=PlainTextResponse)
async def custom_response():
return "This is a plain text response"
from peewee import SqliteDatabase, Model, CharField
db = SqliteDatabase('test.db')
class User(Model):
name = CharField()
class Meta:
database = db
@app.on_event("startup")
def startup():
db.connect()
db.create_tables([User])
@app.on_event("shutdown")
def shutdown():
db.close()
@app.get("/users/")
async def read_users():
users = User.select()
return [{"name": user.name} for user in users]
from pydantic import BaseModel, validator
class Item(BaseModel):
name: str
price: float
@validator('price')
def price_must_be_positive(cls, v):
if v <= 0:
raise ValueError('Price must be positive')
return v
@app.post("/items/")
async def create_item(item: Item):
return item
from pydantic import BaseModel, validator
class Item(BaseModel):
name: str
price: float
@validator('price')
def price_must_be_positive(cls, v):
if v <= 0:
raise ValueError('Price must be positive')
return v
@app.post("/items/")
async def create_item(item: Item):
return item
from fastapi import FastAPI, Request, HTTPException
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.responses import Response
import re
app = FastAPI()
class TenantMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
path = request.url.path
match = re.search(r'^/(\d+)/', path) # Assuming tenant_id is a digit group
if match:
tenant_id = match.group(1)
request.state.tenant_id = tenant_id # Store tenant_id in request state
else:
request.state.tenant_id = None # Default or handle error
response = await call_next(request)
return response
# Add the middleware to the app
app.add_middleware(TenantMiddleware)
# Example endpoint using tenant_id from request state
@app.get("/{tenant_id}/log-test")
async def log_test(request: Request):
tenant_id = getattr(request.state, 'tenant_id', None)
if tenant_id is None:
raise HTTPException(status_code=404, detail="Tenant ID not found")
return {"message": "Logging for tenant", "tenant_id": tenant_id}