Bigger Applications
Because libre-fastapi-jwt configure your setting via class state that applies across all instances of the class. You need to make sure to call load_config(callback) above from your endpoint. Thanks to FastAPI
when you make endpoint from APIRouter
it will actually work as if everything was the same single app.
So you only need to define load_config(callback) where Fastapi
instance created or you can import it where you included all the router.
An example file structure¶
Let's say you have a file structure like this:
.
├── multiple_files
│ ├── __init__.py
│ ├── app.py
│ └── routers
│ ├── __init__.py
│ ├── items.py
│ └── users.py
Here an example of app.py
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from libre_fastapi_jwt import AuthJWT
from libre_fastapi_jwt.exceptions import AuthJWTException
from routers import users, items
from pydantic import BaseModel
app = FastAPI()
class Settings(BaseModel):
authjwt_secret_key: str = "secret"
@AuthJWT.load_config
def get_config():
return Settings()
@app.exception_handler(AuthJWTException)
def authjwt_exception_handler(request: Request, exc: AuthJWTException):
return JSONResponse(status_code=exc.status_code, content={"detail": exc.message})
app.include_router(users.router, tags=["users"])
app.include_router(items.router, tags=["items"])
Here an example of users.py
from fastapi import APIRouter, Depends, HTTPException
from libre_fastapi_jwt import AuthJWT, AuthJWTBearer
from pydantic import BaseModel
class User(BaseModel):
username: str
password: str
router = APIRouter()
auth_dep = AuthJWTBearer()
@router.post("/login")
def login(user: User, Authorize: AuthJWT = Depends(auth_dep)):
if user.username != "test" or user.password != "test":
raise HTTPException(status_code=401, detail="Bad username or password")
access_token = Authorize.create_access_token(subject=user.username)
return {"access_token": access_token}
Here an example of items.py
from fastapi import APIRouter, Depends
from libre_fastapi_jwt import AuthJWT, AuthJWTBearer
router = APIRouter()
auth_dep = AuthJWTBearer()
@router.get("/items")
def items(Authorize: AuthJWT = Depends(auth_dep)):
Authorize.jwt_required()
items = ["item1", "item2", "item3"]
return {"items": items}