[Python] Set SwaggerUI Access Token on App Startup

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    I have a FastAPI app below.

    from fastapi import Depends, FastAPI, HTTPException, Security
    from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

    async def verify(token: HTTPAuthorizationCredentials | None = Depends(HTTPBearer())):
    if token is None:
    raise HTTPException(status_code=401)
    # VERIFY TOKEN
    return token

    app = FastAPI(
    swagger_ui_parameters={"preauthorizeApiKey": {"HTTPBearer": "demo_key_for_testing"}}
    )

    @app.get("/api/private")
    def private(auth_result: str = Security(verify)):
    """A valid access token is required to access this route"""
    return auth_result


    Looking at SwaggerUI docs generated from this code, I'm given the following authorization form to set an access token.

    [​IMG]

    I'd like to pre-populate this form with an access token.

    To do this, Swagger has a config parameter preauthorizeApiKey which should be configurable through FastAPIs swagger_ui_parameters param. However, there are no docs on implementation details for this config setting.

    How can I programmatically set a value in my app's authorization form?

    My attempt above does not work as desired.

    Continue reading...

Compartilhe esta Página