Decorate FastAPI endpoints with custom decorators.
Project description
FastAPI decorators
Small Python utility for wrapping your FastAPI endpoints in custom decorators.
Installation
pip install fastapi-decorators
Usage
Create a simple decorator that rejects unauthorized requests:
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="/api/v1/auth/login",
auto_error=False,
)
def authorize(*required_scopes: str):
def decorator(func):
def dependency(
token: Optional[str] = Depends(oauth2_password_scheme),
db_session: Session = Depends(get_db),
):
if token is None:
raise HTTPException(status_code=401, detail="Unauthenticated")
jwt = decode_jwt(token)
if not all(scope in jwt["scopes"] for scope in required_scopes):
raise HTTPException(status_code=403, detail="Unauthorized")
if not db_session.query(User).filter(User.id == jwt["sub"]).first():
raise HTTPException(status_code=403, detail="Unauthorized")
return add_dependencies(Depends(dependency))(func)
return decorator
The decorator can be used like so:
@app.put("/users/{user_id}")
@authorize("users:write")
def update_user(*, user_id: int, user_update: UserUpdate):
...
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for fastapi_decorators-0.0.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 025022194fef45c42f25389baeaffcad5840f04e1a5aec0e8d228a3f820483e8 |
|
MD5 | 04b749db2868263154a681210d513edd |
|
BLAKE2b-256 | b1873298c37c28e3e621dfbb8397b46bb6c20b974b8782267b3849af1244bcc6 |