Skip to main content

FastAPI permissions system

Project description

fastapi-has-permissions

license test codecov pypi downloads

Introduction

Declarative permissions system for FastAPI. Define permission checks as classes or functions, compose them with &, |, ~ operators, and plug them into FastAPI's dependency injection.

Installation

pip install fastapi-has-permissions

Usage

Class-Based Permissions

Subclass Permission and implement check_permissions():

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!"}

Permissions with parameters are automatically dataclasses:

class HasRole(Permission):
    role: str

    async def check_permissions(self, request: Request) -> bool:
        return request.headers.get("role") == self.role

Boolean Composition

Combine permissions with & (AND), | (OR), and ~ (NOT):

# All must pass
Depends(HasAuthorizationHeader() & HasRole("admin"))

# Any must pass
Depends(HasAuthorizationHeader() | HasRole("admin"))

# Negated
Depends(~HasAuthorizationHeader())

Function-Based Permissions

Use the @permission decorator for a lightweight alternative:

from typing import Annotated

from fastapi import Header

from fastapi_has_permissions import permission


@permission
async def has_admin_role(role: Annotated[str, Header()]) -> bool:
    return role == "admin"


@app.get("/admin", dependencies=[Depends(has_admin_role())])
async def admin_endpoint():
    return {"message": "Admin access granted"}

Function-based permissions also support Dep arguments for injecting FastAPI dependencies:

from fastapi_has_permissions import Dep, permission


async def get_admin_role() -> str:
    return "admin"


AdminRoleDep = Annotated[str, Depends(get_admin_role)]


@permission
async def has_role(admin_role: Dep[str], /, role: Annotated[str, Header()]) -> bool:
    return role == admin_role


@app.get("/admin", dependencies=[Depends(has_role(AdminRoleDep))])
async def admin_endpoint():
    return {"message": "Admin access granted"}

Function-based permissions support the same &, |, ~ composition.

Lazy Permissions

Defer dependency resolution to request time with lazy() - useful when dependencies may not always be available:

from fastapi.exceptions import RequestValidationError

from fastapi_has_permissions import lazy

# Skip the check instead of failing if the "age" header is missing
Depends(lazy(AgeIsMoreThan(age=18), skip_on_exc=(RequestValidationError,)))

Other Features

  • Custom error responses -- set default_exc_message / default_exc_status_code class variables or override get_exc_message() / get_exc_status_code() methods
  • Skip / Fail helpers -- call skip() or fail() inside check_permissions() for explicit control flow
  • Built-in common permissions -- IsAuthenticated, HasScope, HasRole ready to use with your auth dependencies
  • Full FastAPI DI support -- check_permissions() accepts any FastAPI-injectable parameters

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_has_permissions-0.1.4.tar.gz (97.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_has_permissions-0.1.4-py3-none-any.whl (14.2 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_has_permissions-0.1.4.tar.gz.

File metadata

  • Download URL: fastapi_has_permissions-0.1.4.tar.gz
  • Upload date:
  • Size: 97.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.2 {"installer":{"name":"uv","version":"0.10.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for fastapi_has_permissions-0.1.4.tar.gz
Algorithm Hash digest
SHA256 aa8f6bf8a3b2c049f6ce9dd0855b5825b9e06ac8330d3b88bf31a8951a7375bd
MD5 18a90ecb84fc6275816d16c0beb211be
BLAKE2b-256 2935b7787c5293c5024498f3a4ad301d1d5ec73658f828b80cb68b5385a84bac

See more details on using hashes here.

File details

Details for the file fastapi_has_permissions-0.1.4-py3-none-any.whl.

File metadata

  • Download URL: fastapi_has_permissions-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 14.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.2 {"installer":{"name":"uv","version":"0.10.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for fastapi_has_permissions-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 89ecad99a18aa3f68166370466e5e466752de8841f093336345e893aca96af2f
MD5 8fd2cc461bbf8748e5c864d20467eca9
BLAKE2b-256 f5f2826f6d73d0704d06973add0a70f17a4944e667cd8664fffff8e1078bd45a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page