Skip to main content

Fast Actions

Fast Actions generates opinionated, class-based action routers for FastAPI.

It is intended for typed, action-oriented RPC APIs where every operation:

  • uses POST;
  • accepts exactly one Pydantic request object;
  • returns exactly one Pydantic response object;
  • has no path, query, header, or cookie parameters in its action signature; and
  • receives shared FastAPI dependencies through controller fields.

Fast Actions only generates endpoints. It does not replace the FastAPI application, install middleware, register global exception handlers, or change dependency injection and request validation behavior.

Installation

pip install fast-actions

Python 3.12 or newer is required.

Example

import typing as t

from fastapi import FastAPI
from pydantic import BaseModel

from fast_actions import Controller, Depends, Error, errors


class CreateUserRequest(BaseModel):
    email: str


class CreateUserResponse(BaseModel):
    user_id: str


class EmailAlreadyExists(Error):
    pass


async def provide_user_service() -> 'UserService':
    ...


class Users(Controller):
    users: t.Annotated['UserService', Depends(provide_user_service)]

    @errors(EmailAlreadyExists)
    async def create(self, request: CreateUserRequest) -> CreateUserResponse:
        if await self.users.email_exists(request.email):
            message = 'A user already exists with this email.'
            raise EmailAlreadyExists(message)

        user = await self.users.create(request.email)
        return CreateUserResponse(user_id=user.id)


app = FastAPI()
Users.mount_on(app, '/users')

This defines POST /users/create.

mount_on() is a convenience for regular FastAPI router inclusion. The following forms are equivalent:

Users.mount_on(app, '/users')
app.include_router(Users.to_router('/users'))

Both FastAPI and APIRouter instances can be mounting targets.

Actions

Every public asynchronous instance method declared on a controller is an action. Method names are converted from snake case to kebab case:

class Users(Controller):
    async def reset_password(
        self, request: ResetPasswordRequest
    ) -> ResetPasswordResponse:
        ...

This defines POST /users/reset-password when mounted on /users.

The method named exactly _ defines an action at the controller mount path itself:

class Users(Controller):
    async def _(self, request: ListUsersRequest) -> ListUsersResponse:
        ...

This defines POST /users. Other names beginning with _ are private and are not registered, so they can be used for controller helpers.

Action methods must:

  • be asynchronous instance methods;
  • accept exactly self and one required request argument; and
  • annotate the request and response with concrete Pydantic BaseModel subclasses or None.

Invalid controller definitions raise ControllerDefinitionError when converted to a router. Inherited controller actions are included. Action names that normalize to the same route are rejected rather than being registered ambiguously.

Dependencies

Controller dependencies use Annotated and Depends without a constructor:

class Users(Controller):
    users: t.Annotated[UserService, Depends(provide_user_service)]
    actor: t.Annotated[Actor, Depends(authenticate)]

Fast Actions creates one controller instance per request and assigns the resolved dependencies to its fields. Controllers cannot define __init__ or __new__, and action methods cannot declare additional dependencies.

All controller dependencies run for every action on that controller. Split a controller when its actions need materially different dependencies or authentication policies.

Depends is re-exported by fast_actions; it is FastAPI's normal dependency marker, so dependency overrides and dependency cleanup continue to work normally.

Empty Objects

Annotate a request or response as None to represent an empty JSON object:

class Cache(Controller):
    async def clear(self, request: None) -> None:
        ...

The client must send {}, the action receives None, the action returns None, and the HTTP response is {}.

Errors

Raise Error from an action to return a JSON error response:

class PermissionDenied(Error):
    @classmethod
    def get_status(cls) -> int:
        return 403


raise PermissionDenied('You cannot perform this action.')

The response is:

{
  "code": "PERMISSION_DENIED",
  "message": "You cannot perform this action."
}

Error.get_code() derives the stable code from the class name. Renaming an error class is therefore an API-breaking change. Error.get_status() defaults to 400 and may return any status from 400 through 599 except 422, which remains reserved for FastAPI request and dependency validation.

Declare errors for OpenAPI with the metadata-only @errors decorator:

@errors(EmailAlreadyExists, PermissionDenied)
async def create(self, request: CreateUserRequest) -> CreateUserResponse:
    ...

An undeclared Error raised by the action is still returned using its code, message, and status; it is simply absent from OpenAPI.

Fast Actions catches Error only around the controller method call. An Error raised by a dependency is not converted. FastAPI HTTPException, request validation, dependency validation, response validation, and unexpected exceptions keep their normal FastAPI behavior. In particular, invalid requests remain 422 responses.

Business Outcomes

Business outcomes that should all return 200 belong in the application's response model. Fast Actions has no special result or detailed-error abstraction:

class Created(BaseModel):
    user_id: str


class EmailUnavailable(BaseModel):
    code: t.Literal['EMAIL_UNAVAILABLE']
    message: str


class CreateUserResponse(BaseModel):
    result: Created | EmailUnavailable

Return these models normally instead of raising Error.

OpenAPI Metadata

Use the metadata-only @openapi_extra decorator to add properties to an action's OpenAPI operation:

from fast_actions import openapi_extra


class Users(Controller):
    @openapi_extra(
        {
            'x-required-permissions': ['users:create'],
            'x-audit': {'event': 'user.created'},
        }
    )
    @errors(EmailAlreadyExists)
    async def create(self, request: CreateUserRequest) -> CreateUserResponse:
        ...

These properties appear directly under paths['/users/create']['post'] in the generated OpenAPI. Custom extension names use the x- prefix. Standard operation properties such as summary and deprecated can also be supplied.

The decorator accepts a Mapping[str, JsonValue], where JsonValue is Pydantic's JSON value type. FastAPI deep-merges the metadata into the generated operation, including nested properties such as responses. This affects documentation only.

@openapi_extra preserves the method's signature and typing and can appear above or below @errors. Inherited methods retain their metadata; overriding a method replaces it, so the new method declares its own metadata. The supplied mapping is copied when the decorator is created, and every generated route receives its own independent copy.

OpenAPI Names

Fast Actions creates private request and response model copies for every action. The names are derived from the path known when to_router() or mount_on() is called:

/users                 -> UsersRequest, UsersResponse
/users/create          -> UsersCreateRequest, UsersCreateResponse
/api/v1/users/create   -> ApiV1UsersCreateRequest, ApiV1UsersCreateResponse

Reusing the same application model in multiple actions still produces distinct OpenAPI components.

Prefixes added later when a parent router is included are intentionally not part of these names:

Users.mount_on(api_router, '/users')
app.include_router(api_router, prefix='/api/v1')

The final route is /api/v1/users, but its components are named UsersRequest and UsersResponse.

Scope

Fast Actions is a good fit for internal APIs, backend-for-frontend services, and APIs consumed by generated clients. POST-only reads do not have normal HTTP cache or safe-method semantics. File uploads, streaming responses, and transport-oriented APIs should use FastAPI routes directly.

Metadata

Release files for fast-actions 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fast-actions 0.4.0
File Size Uploaded Provenance Actions
fast_actions-0.4.0.tar.gz 12.9 kB Without provenance Details for fast_actions-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fast-actions 0.4.0
File Interpreter ABI Platform Actions
fast_actions-0.4.0-py3-none-any.whl Python 3 none any Details for fast_actions-0.4.0-py3-none-any.whl

Total release size: 27.9 kB

Release files / fast_actions-0.4.0.tar.gz

Download URL fast_actions-0.4.0.tar.gz
Size 12.9 kB
Tags Source
SHA-256 checksum
How to use checksums
65c0b467a970737bf2035da2d24ba72ea93ef346deca1d750037f8950a6e834b
BLAKE2b-256 checksum
How to use checksums
3b4abf91a213e1e8d4e4f2f6cfcdc1d30d5769203c8795a034f293d1284d09a1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.12.13

Release files / fast_actions-0.4.0-py3-none-any.whl

Download URL fast_actions-0.4.0-py3-none-any.whl
Size 14.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d075b0905bc7cfc81c65dd1185838e73970def5de314c6ebdd0057d2d83b6e80
BLAKE2b-256 checksum
How to use checksums
378e315729b9d9ddd8feac116fab22883bf3451d5ccd084d6514780fd5a916c2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.12.13

Security for fast-actions 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page