'FastApi settings / dependency
I have a FastAPI app with pydantic settings instance reading and validation env variables:
### config.py
from pydantic import BaseSettings
class Settings(BaseSettings):
VERSION: str
OPENAPI_PREFIX: str
settings = Settings()
### main.py
from fastapi import FastApi
from .config import settings
app = FastAPI(
title='projectX',
description="my description",
version=settings.VERSION,
root_path=settings.OPENAPI_PREFIX,
openapi_url="/openapi.json",
prefix="/api"
)
if I want to use dependency injection, (for testing purpose to override the dependency settings) as showed in this section of the docs , how do I go for:
settings.VERSION
within FastAPI constructor?any other references to
settings
outside the endpoints views functions ? Should I put them as dependencies for each endpoint (very repetitive code I believe) ? or go for a middleware ? see here a very similar situation.
Solution 1:[1]
If you pass the settings.VERSION into the FastAPI constructor only changed the app version it does not change your API version. To handle each endpoint you would use a router with each dependency to group and form that endpoint with the same dependency. You would check out what I did before through the below image. During this example I was using APIRouter to form a group of router and define a series of deps called Deps.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Klaus Wong |