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 one typed JSON request body, or an empty object for a parameterless action;
- returns one typed JSON value;
- 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
self, optionally followed by one required positional request argument; - annotate the request argument when present; and
- always annotate the return value, including
-> None.
Request and response annotations can be any types supported by Pydantic validation and JSON schema
generation, including BaseModel, RootModel, dataclasses, TypedDict, collections, unions, scalar
types, and Annotated validators and serializers. Fast Actions creates TypeAdapter instances when
building the router and uses FastAPI's validation and serialization machinery.
class Numbers(Controller):
async def total(self, request: list[int]) -> int:
return sum(request)
POST /numbers/total accepts a JSON array such as [1, 2, 3] and returns 6. The request always comes
from the JSON body, including when its annotation is a scalar type such as str or int.
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.
Parameterless Actions and Null
Omit the request parameter when an action has no input:
class Cache(Controller):
async def clear(self) -> None:
...
The client sends {}, and Fast Actions calls the method with only self. The body is validated as
an empty model, with extra object fields ignored. The return annotation is still required: -> None
means the action returns None and the HTTP response is JSON null.
An explicit request: None also means JSON null, rather than {}:
class Values(Controller):
async def echo(self, request: str | None) -> str | None:
return request
This accepts a JSON string or null and returns the same value. Every action requires a request body,
even when its type allows null. A missing body is a 422 validation error.
Previously, None annotations represented empty JSON objects. Replace a request: None parameter
with a parameterless method to keep accepting {}. To keep returning {}, use an explicit empty
BaseModel and return an instance of it.
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.
Controller-Wide Decorators
Both @errors and @openapi_extra can decorate a controller to apply metadata to all of its actions:
@errors(PermissionDenied)
@openapi_extra({'tags': ['users']})
class Users(Controller):
@errors(EmailAlreadyExists)
@openapi_extra({'summary': 'Create a user'})
async def create(self, request: CreateUserRequest) -> CreateUserResponse:
...
async def list_users(self) -> list[CreateUserResponse]:
...
Both actions have the users tag and document PermissionDenied. The create action also documents
EmailAlreadyExists and has its own summary.
Metadata is combined when building the router, in this order:
- Base controllers, following reverse Python method resolution order (MRO).
- The concrete controller.
- The selected action method.
@errors combines the declarations, preserving their order and removing duplicate error classes
across scopes. @openapi_extra uses FastAPI's deep-merge rules: nested dictionaries merge, later
scalar values override earlier ones, and lists concatenate. For example, an action with
{'tags': ['write']} on a controller with {'tags': ['users']} receives ['users', 'write'].
Inherited actions receive the defaults of the controller being mounted. Overridden methods use their own action metadata together with those controller defaults. Each class contributes only its own declarations, including in diamond inheritance, and each generated action receives independent metadata.
Both decorators return the original function or class. Type checkers retain the precise action signature and concrete controller type, including its fields and methods. They accept controller classes and awaitable-returning callables; router construction still enforces asynchronous instance methods, action signatures, and required return annotations.
OpenAPI Names
Fast Actions creates named request and response type aliases for every action. The schema 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 type in multiple actions still produces distinct top-level OpenAPI components. Arrays, scalars, unions, and nulls also receive action-specific names.
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.5.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fast_actions-0.5.0.tar.gz | 15.3 kB | Without provenance | Details for fast_actions-0.5.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fast_actions-0.5.0-py3-none-any.whl | Python 3 | none | any | Details for fast_actions-0.5.0-py3-none-any.whl |
Total release size: 32.7 kB
Release files / fast_actions-0.5.0.tar.gz
| Download URL | fast_actions-0.5.0.tar.gz |
|---|---|
| Size | 15.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
b29c5f90f3a832f2203b11249f574805b38b47d8ffe1184b05a37d0a732f9f68
|
|
BLAKE2b-256 checksum How to use checksums |
ed0c240329e2154206226d484487a92a19cf80f48f348fa0aa19a0bd5302756e
|
| 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.5.0-py3-none-any.whl
| Download URL | fast_actions-0.5.0-py3-none-any.whl |
|---|---|
| Size | 17.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9d23d10720da9083364f7134d10c7f9d8981b9cb40b13baf7d1d6742f7965938
|
|
BLAKE2b-256 checksum How to use checksums |
c019b9ada879da173963d8eaf7e5e87cfd33b27f2282afaf033e0dd296ecaba4
|
| 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.5.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.