pythonazureazure-web-app-servicefastapiazure-webapps

FastAPI deployed to an azure web app - getting environments variables


I have deployed a FastAPI application to an azure web app. I would like to access the environment variables from the web app in fast api. Is that possible and if yes or do you do that? Both from azure ofcource, but also how do you manage locally when developing. As we speak I am only using a basic hello world template:

from fastapi import FastAPI,Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi_azure_auth import SingleTenantAzureAuthorizationCodeBearer
import uvicorn
from fastapi import FastAPI, Security
import os
from typing import Dict

from settings import Settings

from pydantic import AnyHttpUrl,BaseModel

from contextlib import asynccontextmanager
from typing import AsyncGenerator

from fastapi_azure_auth.user import User

settings = Settings()

@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
    """
    Load OpenID config on startup.
    """
    await azure_scheme.openid_config.load_config()
    yield


app = FastAPI(
    swagger_ui_oauth2_redirect_url='/oauth2-redirect',
    swagger_ui_init_oauth={
        'usePkceWithAuthorizationCodeGrant': True,
        'clientId': settings.OPENAPI_CLIENT_ID,
        'scopes': settings.SCOPE_NAME,
    },
)

if settings.BACKEND_CORS_ORIGINS:
    app.add_middleware(
        CORSMiddleware,
        allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
        allow_credentials=True,
        allow_methods=['*'],
        allow_headers=['*'],
    )

azure_scheme = SingleTenantAzureAuthorizationCodeBearer(
    app_client_id=settings.APP_CLIENT_ID,
    tenant_id=settings.TENANT_ID,
    scopes=settings.SCOPES,
)

class User(BaseModel):
    name: str
    roles: list[str] = []


@app.get("/", dependencies=[Security(azure_scheme)])
async def root():
    print("Yo bro")
    return {"whoIsTheBest": "DNA Team is"}

@app.get("/test", dependencies=[Security(azure_scheme)])
async def root():
    print("Yo test")
    return {"whoIsTheBest": "DNA Team is!"}

@app.get("/me", dependencies=[Security(azure_scheme)])
async def me(request: Request):
    print("Me")
    return User(roles=request.state.user.roles,name=request.state.user.name)

if __name__ == '__main__':
    uvicorn.run('main:app', reload=True) 

   

Solution

  • Thanks @jonrsharpe for comment.

    I created simple FastAPI app to fetch environment variables and deployed to Azure App service.

    The os module is important for accessing the environment variables in Python.

    We need to install python-dotenv package to retrieve environment variables from .env file.

    .env:

    GREETING_MESSAGE=Hello, World!
    

    main. py

    from fastapi import FastAPI
    import os
    from dotenv import load_dotenv
    load_dotenv()
    app = FastAPI()
    @app.get("/")
    def read_root():
        greeting = os.getenv("GREETING_MESSAGE", "Hello from FastAPI!")
        return {"message": greeting}
    

    requirements.txt:

    fastapi
    uvicorn
    python-dotenv
    

    Below is my local Output:

    enter image description here

    After deploying to azure I added below Startup Command in Configuration section of Azure Web app.

     gunicorn --worker-class uvicorn.workers.UvicornWorker --timeout 600 --access-logfile '-' --error-logfile '-' main:app
    

    enter image description here

    To securely access environment variables in Azure, add them to the Environment Variables section of the Azure Web App, as shown below.

    enter image description here

    enter image description here

    Azure Output:

    enter image description here