Search code examples
pythonrequestfastapistarlette

Check if request is coming from Swagger UI


Using Python and Starlette or FastAPI, How can I know if the request is coming from the Swagger UI or anywhere else (Postman, Frontend app)?

I tried to see if there's something in Request object which I can use:

from fastapi import Request

@app.get("/")
async def root(request: Request):
    # request.client.host just returns some IP
    # request.headers doesn't contain any hint
    # request.scope ?
    request_from_swagger = request.hints_on_whether_request_is_coming_from_swagger_ui
    if request_from_swagger:
        return {"message": "Hello Swagger UI"}

    return {"message": "Hello World"}

I need to take some actions based of that. So is there anyway I can tell, whether the request is coming from the Swagger UI?


Solution

  • You could always use the referer header of the request:

    from fastapi import Request
    
    @app.get("/")
    async def root(request: Request):
        request_from_swagger = request.headers['referer'].endswith(app.docs_url)
        if request_from_swagger:
            return {"message": "Hello Swagger UI"}
    
        return {"message": "Hello World"}