Skip to content

Middleware for Starlette/FastAPI #710

@hawkaa

Description

@hawkaa

Hi,

Is your feature request related to a problem?

I recently discovered FastAPI and I see a bright future for this project. I for sure will no longer use Flask to develop any micro backends anymore, as I find FastAPI better in all aspects.

No matter if you agree or not, I wonder if we need an OpenTelemetry middleware here. It does not exist at the moment, but I believe FastAPI is such of a big project that an integration should be provided by this package.

Describe alternatives you've considered

FastAPI builds on Starlette, so a middleware for Starlette will work with no problem for FastAPI as well. I have created a proof of concept middleware that looks like this:

from fastapi import FastAPI
from opentelemetry.trace import Tracer
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request


class OpenTelemetryMiddleware(BaseHTTPMiddleware):
    def __init__(self, app: FastAPI, tracer: Tracer):
        super().__init__(app)
        self._tracer = tracer

    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint):
        span_name = str(request["path"])
        with self._tracer.start_as_current_span(span_name):
            return await call_next(request)

It is included in the FastAPI app like this:

from opentelemetry import trace
tracer = trace.get_tracer(__name__)
app.add_middleware(OpenTelemetryMiddleware, tracer=tracer)

However, as you probably can see, it doesn't read the headers and set the context correctly, as you have probably seen. Also, I'm not sure if it's the python-esque or opentelemetry way to include/inject the objects.

I'm thinking a combination of the opentelemetry-ext-flask package and the starlette-opentracing package is the right way to go.

Additional context
I'm no active open source contributor, and I don't have a lot of time on my hands, but I guess I could take a look at making such package if you are interested.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions