Bigger Applications
Because fastapi-paseto-auth configures your setting via a class state that applies across all instances of the class, you only need to make sure to call load_config(callback) before declaring any endpoint. Thanks to FastAPI
when you make an 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 your FastAPI
instance is created or you can import it where you include all the routers.
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_paseto_auth import AuthPASETO
from fastapi_paseto_auth.exceptions import AuthPASETOException
from routers import users, items
from pydantic import BaseModel
app = FastAPI()
class Settings(BaseModel):
authpaseto_secret_key: str = "secret"
@AuthPASETO.load_config
def get_config():
return Settings()
@app.exception_handler(AuthPASETOException)
def authpaseto_exception_handler(request: Request, exc: AuthPASETOException):
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_paseto_auth import AuthPASETO
from pydantic import BaseModel
class User(BaseModel):
username: str
password: str
router = APIRouter()
@router.post("/login")
def login(user: User, Authorize: AuthPASETO = 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_paseto_auth import AuthPASETO
router = APIRouter()
@router.get("/items")
def items(Authorize: AuthPASETO = Depends()):
Authorize.paseto_required()
items = ["item1", "item2", "item3"]
return {"items": items}