Metadata-Version: 2.4
Name: fast-actions
Version: 0.6.0
Summary: Opinionated class-based action routers for FastAPI
Author: Florian Daude
Author-email: Florian Daude <floriandaude@hotmail.fr>
License-Expression: Apache-2.0
License-File: LICENSE
Requires-Dist: fastapi>=0.116.0
Requires-Dist: pydantic>=2.11.0
Requires-Python: >=3.12
Description-Content-Type: text/markdown

# 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

```console
pip install fast-actions
```

Python 3.12 or newer is required.

## Example

```python
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:

```python
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:

```python
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:

```python
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.

```python
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:

```python
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:

```python
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 `{}`:

```python
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:

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


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

The response is:

```json
{
  "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:

```python
@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:

```python
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:

```python
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](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#openapi-extra)
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:

```python
@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:

1. Base controllers, following reverse Python method resolution order (MRO).
2. The concrete controller.
3. 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 Schemas

Request and response schemas use the declared types directly:

```python
class Users(Controller):
    async def get(self, request: str) -> User:
        ...
```

The request schema is an inline `{"type": "string"}` schema. The `200` response schema references
`#/components/schemas/User`. Reusing `User` in other actions reuses its schema component.

Collections and unions use their normal Pydantic schemas: `list[User]` is an inline array with items
referencing `User`, and `None` is an inline `{"type": "null"}` schema. Named models and type aliases,
including recursive types, retain their Pydantic component names. Pydantic may generate separate
input and output components when needed.

Fast Actions does not generate action-specific request or response components. Route names and
mount prefixes do not rename the declared types.

## 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.
