Skip to content

3. Group related operations

The task feature now has preparation and preview operations. Give callers one service object for the feature. Reuse the checked actions from the previous step, including their existing dependencies. Save this program as docs_src/tutorial/services.py.

"""Group the checked actions without reimplementing their bodies."""

import asyncio

from docs_src.quickstart import NewTask
from docs_src.tutorial.shared_checks import prepare_task, preview_task
from fastsprout.actions import Service


class TaskService(Service):
    prepare = prepare_task
    preview = preview_task


tasks = TaskService()


async def main() -> None:
    payload = NewTask(title="Write documentation")
    draft = await tasks.prepare(payload)
    print("Prepared:", draft.title)
    print("Preview:", await tasks.preview(payload))
    try:
        await tasks.preview(NewTask(title=""))
    except ValueError as error:
        print("Rejected:", error)


if __name__ == "__main__":
    asyncio.run(main())

Run it from your tutorial directory:

python -m docs_src.tutorial.services

Result

Prepared: Write documentation
Preview: Task: Write documentation
Rejected: Task title cannot be empty

What the service adds

TaskService inherits from Service. Its prepare and preview attributes reuse the actions you already wrote. Their input and result types remain available, and the shared title check still runs. The failed preview call shows that grouping an action preserves its dependency behavior.

Callers can now receive a TaskService and call the operations of the task feature through that object. A service can also define public async methods, request collaborators with Depends, and call other services. Those options are covered in the Actions guide.

Use Service to organize application behavior. When the next feature needs standard operations for a stored entity, DataS supplies those operations.

Previous: Shared checks · Next: Store and retrieve tasks