Created
June 20, 2024 00:18
-
-
Save bnusunny/d366c669e19f06d6fbfd0fe8e870467f to your computer and use it in GitHub Desktop.
FastAPI + Powertools Tracer + Lambda Web Adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from aws_lambda_powertools import Logger, Tracer | |
from fastapi import FastAPI, Request | |
import boto3 | |
import os | |
logger = Logger() | |
tracer = Tracer() | |
s3 = boto3.resource('s3') | |
app = FastAPI() | |
async def x_ray_trace_id_middleware(request: Request, call_next): | |
# Extract the X-Amzn-Trace-Id header from the incoming request | |
x_amzn_trace_id = request.headers.get("x-amzn-trace-id") | |
if x_amzn_trace_id: | |
# Set the trace ID as an environment variable | |
os.environ["_X_AMZN_TRACE_ID"] = x_amzn_trace_id | |
logger.debug(f"X-Ray trace ID set: {x_amzn_trace_id}") | |
else: | |
logger.debug("No X-Ray trace ID found in the request") | |
# Call the next middleware or the route handler | |
response = await call_next(request) | |
# Remove the environment variable after the request is processed | |
if "_X_AMZN_TRACE_ID" in os.environ: | |
del os.environ["_X_AMZN_TRACE_ID"] | |
return response | |
app.middleware("http")(x_ray_trace_id_middleware) | |
@app.get("/") | |
@tracer.capture_method(capture_response=False) | |
async def root(): | |
# Findout how many S3 buckets are in the account | |
s3_count = len(list(s3.buckets.all())) | |
return { | |
"message": "Hello World", | |
"s3_count": s3_count | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment