First Steps¶
Here is a minimal example of using fastapi-has-permissions to protect a route:
from fastapi import Depends, FastAPI, Request
from fastapi_has_permissions import Permission
class HasAuthorizationHeader(Permission):
async def check_permissions(self, request: Request) -> bool:
return "Authorization" in request.headers
app = FastAPI()
@app.get(
"/protected",
dependencies=[Depends(HasAuthorizationHeader())],
)
async def protected():
return {"message": "You have access!"}
Steps:
- Import
Permissionfromfastapi_has_permissions. - Create a class that inherits from
Permissionand implement thecheck_permissionsmethod. - Instantiate the permission and pass it to
Depends()in the route'sdependencieslist.
When a request is made to /protected:
- If the
Authorizationheader is present, the route handler executes normally and returns200 OK. - If the header is missing,
check_permissionsreturnsFalseand the library raises anHTTPExceptionwith status code403 Forbidden.
How It Works¶
Permission subclasses integrate directly with FastAPI's dependency injection system. When you write
Depends(HasAuthorizationHeader()), the permission instance is called as a FastAPI dependency. It:
- Resolves any parameters declared in
check_permissionsusing FastAPI's DI (e.g.,Request,Header, etc.). - Calls
check_permissionswith the resolved values. - If the result is
True, the request proceeds. - If the result is
False, anHTTPExceptionis raised with status403and detail"Permission denied".
Tip
The check_permissions method supports any parameter that FastAPI can inject -- Request, Header,
Depends, Query, Path, and more. This makes permission checks fully integrated with your
existing FastAPI dependencies.