Skip to content

Implement a new domain

This tutorial walks you through adding the Tag domain from scratch. By building each layer in order you will see how nene2-python's clean architecture fits together.

Prerequisite: Complete Getting started first.

What we are building

GET    /tags           — list tags
POST   /tags           — create a tag
GET    /tags/{tag_id}  — get a tag
PUT    /tags/{tag_id}  — update a tag
DELETE /tags/{tag_id}  — delete a tag

Step 1: Entity

Create src/example/tag/entity.py.

python
from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class Tag:
    id: int
    name: str

frozen=True makes the object immutable; slots=True reduces memory overhead.

Step 2: Repository Interface

Define the contract in src/example/tag/repository.py.

python
from abc import ABC, abstractmethod
from .entity import Tag

class TagRepositoryInterface(ABC):
    @abstractmethod
    def find_all(self, limit: int, offset: int) -> list[Tag]: ...

    @abstractmethod
    def find_by_id(self, tag_id: int) -> Tag | None: ...

    @abstractmethod
    def save(self, name: str) -> Tag: ...

    @abstractmethod
    def update(self, tag_id: int, name: str) -> Tag | None: ...

    @abstractmethod
    def delete(self, tag_id: int) -> bool: ...

    @abstractmethod
    def count(self) -> int: ...

Step 3: InMemory implementation

Provide an in-memory repository for tests — no database required.

python
class InMemoryTagRepository(TagRepositoryInterface):
    def __init__(self) -> None:
        self._store: dict[int, Tag] = {}
        self._next_id = 1

    def save(self, name: str) -> Tag:
        tag = Tag(id=self._next_id, name=name)
        self._store[self._next_id] = tag
        self._next_id += 1
        return tag
    # ... other methods

Step 4: UseCase

src/example/tag/use_case.py contains business logic — no HTTP or database imports.

python
from dataclasses import dataclass
from .entity import Tag
from .exceptions import TagNotFoundException
from .repository import TagRepositoryInterface

@dataclass(frozen=True)
class CreateTagInput:
    name: str

class CreateTagUseCase:
    def __init__(self, repository: TagRepositoryInterface) -> None:
        self._repository = repository

    def execute(self, input_: CreateTagInput) -> Tag:
        return self._repository.save(input_.name)

Step 5: HTTP Handler

src/example/tag/handler.py — only three steps: parse → use-case → response.

python
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from .use_case import CreateTagInput, CreateTagUseCase

class CreateTagBody(BaseModel):
    name: str

def make_tag_router(create_use_case: CreateTagUseCase, ...) -> APIRouter:
    router = APIRouter(prefix="/tags", tags=["tags"])

    @router.post("", status_code=201)
    async def create_tag(body: CreateTagBody) -> JSONResponse:
        tag = create_use_case.execute(CreateTagInput(name=body.name))
        return JSONResponse({"id": tag.id, "name": tag.name}, status_code=201)

    return router

Step 6: Wire into app.py

Add the router in src/example/app.py.

python
app.include_router(make_tag_router(
    list_use_case=ListTagsUseCase(tag_repo),
    ...
))

Step 7: Write tests

python
# tests/example/tag/test_tag_use_case.py
def test_create_tag() -> None:
    repo = InMemoryTagRepository()
    tag = CreateTagUseCase(repo).execute(CreateTagInput(name="python"))
    assert tag.name == "python"

Done

The Tag domain you just built matches the Comment domain at src/example/comment/. See src/example/tag/ for the full reference implementation.

Next steps

Released under the MIT License.