Skip to content

Bigger Applications

Because fastapi-jwt-auth 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 fastapi_jwt_auth import AuthJWT
from fastapi_jwt_auth.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 fastapi_jwt_auth import AuthJWT
from pydantic import BaseModel

class User(BaseModel):
    username: str
    password: str


router = APIRouter()

@router.post('/login')
def login(user: User, Authorize: AuthJWT = Depends()):
    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 fastapi_jwt_auth import AuthJWT

router = APIRouter()

@router.get('/items')
def items(Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()

    items = [
        "item1",
        "item2",
        "item3"
    ]

    return {"items": items}