=== application.jinja2 / populated
"""Build the router and the application of every selected operation from the services that implement them."""

from typing import Final
from fastapi import FastAPI

ROUTES: Final = (
    *pets.LITERAL_ROUTES,
    *pets.TEMPLATED_ROUTES,
)
INFO: Final[dict[str, Any]] = {'title': '日本 {braces}', 'version': '1.0'}


def build_router(
    *,
    pets: PetsService[PrincipalT],
    authorize: Authorize[PrincipalT],
    dependencies: Sequence[params.Depends] = (),
    prefix: str = "",
) -> APIRouter:
    """Register every operation on a new router, literal paths first."""
    return build(
        ROUTES,
        services={'pets': pets},
        authorize=authorize,
        dependencies=dependencies,
    )


def create_app(
    *,
    pets: PetsService,
    source_openapi: bool = True,
    **fastapi_kwargs: Any,
) -> FastAPI:
    """Create the application with every operation, passing the other keyword arguments to FastAPI.

    Validation errors leave out the request's values, unless exception_handlers handles RequestValidationError. The
    application serves the source OpenAPI document of its operations, or FastAPI's own with source_openapi=False.
    """
    fastapi_kwargs["exception_handlers"] = error_handlers(fastapi_kwargs.get("exception_handlers"))
    app = FastAPI(**{**INFO, **fastapi_kwargs})
    app.include_router(
        build_router(
            pets=pets,
            authorize=authorize,
        )
    )
    if source_openapi:
        serve_source_openapi(app, prefix=prefix, metadata=fastapi_kwargs)
    return app


__all__ = [
    'build_router',
    'create_app',
]

=== application.jinja2 / empty
"""Build the router and the application of every selected operation from the services that implement them."""

from typing import Final
from fastapi import FastAPI

ROUTES: Final = ()
INFO: Final[dict[str, Any]] = {}


def build_router(
    *,
) -> APIRouter:
    """Register every operation on a new router, literal paths first."""
    return build(
        ROUTES,
        services={},
    )


def create_app(
    *,
) -> FastAPI:
    """Create the application with every operation, passing the other keyword arguments to FastAPI.

    Validation errors leave out the request's values, unless exception_handlers handles RequestValidationError. The
    application serves the source OpenAPI document of its operations, or FastAPI's own with source_openapi=False.
    """
    fastapi_kwargs["exception_handlers"] = error_handlers(fastapi_kwargs.get("exception_handlers"))
    app = FastAPI(**{**INFO, **fastapi_kwargs})
    app.include_router(
        build_router(
        )
    )
    if source_openapi:
        serve_source_openapi(app, prefix=prefix, metadata=fastapi_kwargs)
    return app


__all__ = [
]

=== authorize.jinja2 / populated
"""Authorize the secured operations of app.server; app.server.main imports authorize from this module.

datamodel-code-generator wrote this module once, with a stub, and never overwrites it.
"""

from __future__ import annotations

from app.server import Credentials, RequirementSets


def authorize(requirement_sets: RequirementSets, credentials: Credentials) -> object:
    """Return the principal of the credentials, or raise HTTPException to refuse the request.

    A secured operation passes its requirement sets whose every scheme presented a credential, in declaration order,
    and the credentials by scheme name; its service method receives the principal as its principal argument.
    """
    raise NotImplementedError

=== contract.jinja2 / populated
"""Operation plans of this package; regenerate them instead of editing."""

from __future__ import annotations

from typing import Final, TypedDict
OperationDependencies = TypedDict(
    'OperationDependencies',
    {
        'get_pet': Sequence[params.Depends],
        'list_pets': Sequence[params.Depends],
    },
    total=False,
)


class GetPet:
    """Plans of the get_pet operation."""

    @dataclass(frozen=True, slots=True, kw_only=True)
    class Parameters:
        """The adapter parameters of get_pet."""

        pet_id: int
        tags: list[str] | None

    PARAMETERS: Final = ParameterAdapter(
        arguments=(ParameterArgument(name='pet_id', plan=PathPlan(location='path', name='petId')),),
        record=Parameters,
        path=RawPath(template='/pets/{petId}', names=frozenset({'petId'})),
    )
    BODY: Final = BodyAdapter(
        media=(BodyMedia(media_type='text/plain', kind='text'),),
        required=False,
    )
    RESPONSES: Final = OperationResponses(
        responses={'200': Declared(media_type='application/json', model=models.Pet)},
        primary=200,
        head=True,
        bare=False,
    )


class ListPets:
    """Plans of the list_pets operation."""

    BODY: Final = BodyAdapter(
        media=(BodyMedia(media_type='application/json', kind='json'),),
    )
    RESPONSES: Final = OperationResponses(
        responses={'204': Declared()},
        bare=False,
    )


class DeletePet:
    """Plans of the delete_pet operation."""

    @dataclass(frozen=True, slots=True, kw_only=True)
    class Parameters:
        """The adapter parameters of delete_pet."""

        pet_id: int

    PARAMETERS: Final = ParameterAdapter(
        arguments=(ParameterArgument(name='pet_id', plan=PathPlan(location='path', name='petId')),),
        record=Parameters,
    )
    RESPONSES: Final = OperationResponses(
        responses={'204': Declared()},
        bare=False,
    )

=== contract.jinja2 / empty
"""Operation plans of this package; regenerate them instead of editing."""

from __future__ import annotations

from typing import TypedDict
OperationDependencies = TypedDict('OperationDependencies', {}, total=False)

=== facade.jinja2 / populated
"""FastAPI server 日本 {braces}."""

from .application import build_router, create_app

__all__ = [
    "build_router",
    "create_app",
]

=== facade.jinja2 / empty
"""Router groups of this package."""

=== implementation.jinja2 / asynchronous
"""Implement PetsService of app.server.services; app.server.main imports Pets from this module.

datamodel-code-generator wrote this module once, with a stub for each method, and never overwrites it. Generating the
server again updates the Protocol, so type checkers point at the methods to change.
"""

from __future__ import annotations

from app import models
from app.server import HTTPResult
from app.server.services import PetsService
from fastapi.responses import Response


class Pets(PetsService):
    """Implement the pets operations."""

    async def list_pets(
        self,
        *,
        limit: int | None,
    ) -> models.Pets | HTTPResult[models.Pets | models.PetsGetResponse] | Response:
        """
        Handle GET /pets.
        """
        raise NotImplementedError

    async def create_pets(
        self,
    ) -> None | HTTPResult[models.PetsPostResponse] | Response:
        """
        Handle POST /pets.
        """
        raise NotImplementedError

    async def show_pet_by_id(
        self,
        *,
        petId: str,
    ) -> models.Pets | HTTPResult[models.Pets | models.Error] | Response:
        """
        Handle GET /pets/{petId}.
        """
        raise NotImplementedError

=== implementation.jinja2 / secured
"""Implement DefaultService of app.server.services; app.server.main imports Default from this module.

datamodel-code-generator wrote this module once, with a stub for each method, and never overwrites it. Generating the
server again updates the Protocol, so type checkers point at the methods to change.
"""

from __future__ import annotations

from app.server import HTTPResult
from app.server.services import DefaultService
from fastapi.responses import Response


class Default(DefaultService[object]):
    """Implement the default operations."""

    def get_keys(
        self,
        *,
        principal: object,
    ) -> None | HTTPResult[None] | Response:
        """
        Handle GET /keys.
        """
        raise NotImplementedError

=== main.jinja2 / populated
"""Serve the application with your services: `uvicorn app.server.main:app`.

Generation overwrites this module. It imports your implementations from app.services, as Next steps in README.md
describes, and passes them to create_app; to pass others, such as fakes in tests, call create_app yourself.
"""

from ._runtime.server.application import missing_implementation
from .application import create_app

try:
    from app.services.authorize import authorize as DefaultImplementation
    from app.services.default import Default
except ImportError as error:
    missing_implementation(
        error,
        {
            'app.services.default': 'Default',
            'app.services.authorize': 'authorize',
        },
    )
    raise

app = create_app(
    default=DefaultImplementation(),
    authorize=authorize,
)

=== main.jinja2 / empty
"""Serve the application with your services: `uvicorn app.server.main:app`.

Generation overwrites this module. It imports your implementations from app.services, as Next steps in README.md
describes, and passes them to create_app; to pass others, such as fakes in tests, call create_app yourself.
"""

from .application import create_app

app = create_app(
)

=== openapi.jinja2 / module
"""Serve the source OpenAPI document of the selected operations, which `openapi.json` beside this module holds."""

from __future__ import annotations

import json
from importlib.resources import files
from typing import TYPE_CHECKING, Any

from .._runtime.server.openapi import serve_openapi

if TYPE_CHECKING:
    from collections.abc import Mapping

    from fastapi import FastAPI


def document() -> dict[str, Any]:
    """Return a new copy of the source document, read from `openapi.json` beside this module.

    A build that left the file out of the package fails here, on the document's first request.
    """
    package = __name__.rpartition(".")[0]
    try:
        text = (files(package) / "openapi.json").read_text(encoding="utf-8")
    except FileNotFoundError as error:
        msg = (
            f"openapi.json of {package} is missing: include _generated/openapi.json"
            " as package data when building the package, such as with setuptools"
            " package-data or MANIFEST.in"
        )
        raise FileNotFoundError(msg) from error
    loaded: dict[str, Any] = json.loads(text)
    return loaded


def serve_source_openapi(
    app: FastAPI,
    *,
    prefix: str = "",
    metadata: Mapping[str, Any] | None = None,
) -> None:
    """Serve the source document instead of FastAPI's, read on its first request.

    Its paths take `prefix`, and the FastAPI settings in `metadata`, such as `title`, replace its own.
    """
    serve_openapi(app, document, prefix=prefix, metadata=metadata)

=== readme.jinja2 / populated
# API 日本 {braces}

The `server` package serves the API 日本 {braces} API with FastAPI.
datamodel-code-generator generated it from the OpenAPI document, together with the `models` models of the `pydantic_v2.BaseModel` backend.
Generation overwrites every file of the package, as it does the models: keep your code outside the package, in the `services` modules of [Next steps](#next-steps), and regenerate the package instead of editing it; see [Regenerating](#regenerating).

FastAPI server generation is experimental.
The server supports the `pydantic_v2.BaseModel` and `pydantic_v2.dataclass` model backends, while client generation supports all five.

## Next steps

`main.py` serves the application: it imports your implementation of each router group and your `authorize` function from the `services` package beside this package, and passes them to `create_app`.
Generation writes each of these modules that is missing, with a stub for each method that raises `NotImplementedError`, and never overwrites or deletes one.

| Module | File | Defines |
| --- | --- | --- |
| `app.services.default` | `../services/default.py` | `class Default(DefaultService[object])` |
| `app.services.other` | `../services/other.py` | `class Default(OtherService)` |
| `app.services.authorize` | `../services/authorize.py` | `def authorize(requirement_sets, credentials)` |

The file paths are relative to this README.
Replace each stub with your code, then run the application with an ASGI server, from the directory that holds the top-level package (add `--app-dir src` for a `src` layout):

```console
uv add uvicorn
uv run uvicorn server.main:app --reload
```

`fastapi dev` runs it too: `uv add "fastapi[standard]"`, then `uv run fastapi dev` with the path of `main.py`, beside this README.
To pass other instances, such as fakes in tests, call `create_app` yourself; see [Implementing the services](#implementing-the-services).

### `app.services.default`

```python
implementation:services/default.py
```

### `app.services.other`

```python
implementation:services/other.py
```

### `app.services.authorize`

```python
implementation:services/authorize.py
```

## Dependencies

The package needs these distributions at run time:

- `fastapi>=0.141.1`
- `pydantic>=2.14.0`
- `typing-extensions>=4.16`

Add them to your project with the command each generation prints:

```console
uv add "fastapi>=0.141.1" "pydantic>=2.14.0" "typing-extensions>=4.16"
```

Running the application also needs an ASGI server: `uvicorn`, or `fastapi[standard]` for `fastapi dev`, as in [Next steps](#next-steps).

## Operations

| Service | Method | HTTP method | Path | Operation reference |
| --- | --- | --- | --- | --- |
| `Pets` | `get` | GET | `/pets/{id}` | `get` |
| `Pets` | `create` | POST | `/pets` | `create` |

`operation_dependencies` takes the method names, the keys of `OperationDependencies`; the per-operation generation settings, such as `--server-handler-modes`, take the operation references.

## Implementing the services

`services.py` declares a Protocol for each router group, with an abstract method for each operation of the group.
A method takes the operation's arguments as keywords, with `None` for an optional parameter or body the request omits, and returns the value to send, an `HTTPResult` with another declared status, headers, or both, or a `Response` sent as it is.
`main.py` passes an instance of each group's class to `create_app` under the group's name.
Subclass the Protocol, so that type checkers report a missing or mismatched method and Python refuses to create an instance while a method is missing; any other object with the same methods is checked where you pass it.
The package looks each method up when it registers the routes, and refuses a coroutine function where the operation's handler mode needs a plain method, or the reverse, and a method that cannot take the keyword arguments of its operation; type checkers check their types.
The Protocols of groups with secured operations take the type of the principal your `authorize` callback returns.

Call `create_app` yourself to pass other instances.
Tests pass fakes, as this pytest test does with FastAPI's `TestClient`, which needs `httpx2`: each fake subclasses your class of its group and overrides the methods the test calls.
An application that builds its services with arguments, such as a database pool or settings, calls `create_app` in a module of its own and runs that module's application instead of `main.py`'s.

```python
from fastapi.testclient import TestClient

from server import Credentials, RequirementSets, create_app
from app.services.default import Default
from app.services.other import Default as Default_1


class FakeDefault(Default):
    """Override the methods the test calls, such as `get`."""


class FakeDefault_1(Default_1):
    """Override the methods the test calls, such as `list`."""


def authorize(requirement_sets: RequirementSets, credentials: Credentials) -> object:
    ...


def test_app() -> None:
    with TestClient(create_app(default=FakeDefault(), other=FakeDefault_1(), authorize=authorize)) as client:
        ...
```

`create_app` passes its other keyword arguments, such as `lifespan`, `middleware`, or `dependencies`, to `FastAPI`, over the title, version, and other metadata of the source document.
To keep your own `FastAPI` application, include the router:

```python
from fastapi import FastAPI

from server import build_router
from app.services.default import Default
from app.services.other import Default as Default_1
from app.services.authorize import authorize

app = FastAPI()
app.include_router(build_router(default=Default(), other=Default_1(), authorize=authorize))
```

## Authentication

The secured operations use these security schemes:

- `bearer`: bearer token
- `api_key`: API key

`security.py` declares one FastAPI dependency for each scheme; replace one with `app.dependency_overrides`, for example to read a scheme no FastAPI class reads.
Each secured operation calls `authorize` once with its requirement sets whose every scheme presented a credential, in declaration order, and the credentials by scheme name, and receives the principal it returns.
`authorize` checks the credentials, tokens, and scopes, and rejects a request by raising `HTTPException`, such as `403`; it may be a coroutine function.
A request that presents no complete requirement set answers `401`, unless the operation also accepts no credentials, in which case it receives `None`.
The package never contacts a token endpoint.

## Served OpenAPI document

`create_app` serves the part of the source document the selected operations use, which generation writes into `_generated/openapi.json`; the application reads it on the first request for it.
`_generated/openapi.json` is package data, so a distribution that holds the package must include it: Hatchling, uv_build, poetry-core, pdm-backend, and flit_core include it by default, while setuptools needs it in `package-data` or `MANIFEST.in`.
`create_app(..., source_openapi=False)` serves FastAPI's own document instead, built from the routes and the models they declare, in which an optional parameter or request body is `anyOf` of its type and `null`.
An application of your own that includes `build_router(...)` serves FastAPI's document unless it calls `serve_source_openapi(app)`, imported from `server`.

## Validation

The models are the contract: FastAPI validates parameters, bodies, and responses with the generated model types, so the model generation settings decide how strictly a value follows the OpenAPI document.
Parameter styles, parameter types, and media types that FastAPI cannot read, such as deepObject parameters or cookie arrays, strict integers, numbers, and booleans, text and binary bodies, and multipart forms, pass through generated adapters.
An adapter parses the HTTP syntax, then validates the value with the model's `TypeAdapter`; it answers `400` for malformed syntax, `415` for an undeclared media type, and `422`, with FastAPI's error records, for an invalid value.
A repeated single value is taken as FastAPI takes it, by adapters too: the last query value, cookie, form field, and object member, and the first header.
A cookie parameter with a single value arrives as the request sent it, without percent-decoding.
Adapters accept integers and numbers as JSON writes them and booleans as `true` or `false`, which is fewer spellings than FastAPI accepts for the parameters it reads.
URL-encoded form bodies are FastAPI form models, so FastAPI's form extraction applies; set the operation's `body_modes` entry to `request` when the exact submitted values matter.
Operations with the `request` body mode receive the Starlette `Request` and read and validate their body themselves.

## Production settings

A request that fails validation answers `422` with FastAPI's `{"detail": [...]}` records.
`create_app` keeps the `type`, `loc`, and `msg` of each record and leaves out the `input` and `ctx` FastAPI adds, and pydantic's `url`, so the response does not return the rejected value as such.
`loc` and `msg` are pydantic's and can still hold text the client chose: a mapping key or an unexpected field name, a discriminator tag, or the message of a validator of your own.
An application of your own that includes `build_router(...)` keeps FastAPI's records; register the same handler with `app.add_exception_handler(RequestValidationError, validation_error_handler)`, importing `validation_error_handler` from `server`.
To send other error bodies, pass FastAPI's `exception_handlers` to `create_app`; its entry for `RequestValidationError` replaces the package's.
A result that fails its response model answers `500` without details, and the error, with the values, goes to the server log, as in any FastAPI application.
`create_app(..., docs_url=None, redoc_url=None, openapi_url=None)` removes `/docs`, `/redoc`, and `/openapi.json`.
The `server` response header belongs to the ASGI server, not to the application: uvicorn leaves it out with `--no-server-header`.

## Regenerating

Run the same generation again whenever the OpenAPI document changes; the `--check` option reports the files it would change without writing them.
Generation overwrites every generated file, restoring any you edited or deleted, and never deletes one: delete the modules of removed operations yourself, which `--check` lists as extra files.
When an operation is added, removed, or changed, its method in `services.py` changes with it, so type checkers point at the implementations to update, and Python refuses to create an instance of a subclass that lacks a new method.
Generation writes only the missing modules of `services`: a new router group gets its module with stubs, and the module of a renamed or removed group stays for you to move or delete.
The `services` package belongs to this server alone, as the docstring of its `__init__.py` records: generation refuses another server package beside this one, in a later run or in the same batch, since that package would import its implementations from it too, whatever the docstring says.
Put each server package under a parent package of its own.
A server package renamed or moved within the parent package, or spelled from another import root, takes the package over while no other generated server package is beside it, and generation rewrites the docstring to name it, as `--check` reports and a notice says.
After a take-over, the modules of `services` still import the server package they were written for, as in `from <old package>.services import ...`: update those imports to `server` yourself, since generation never rewrites them.
Each generation prints the `uv add` command that adds the runtime dependencies of the package to your project;
run it again when a new version of datamodel-code-generator changes them.

=== readme.jinja2 / empty
# API 日本 {braces}

The `app.server` package serves the API 日本 {braces} API with FastAPI.
datamodel-code-generator generated it from the OpenAPI document, together with the `app.models` models of the `pydantic_v2.BaseModel` backend.
Generation overwrites every file of the package, as it does the models: keep your code outside the package and regenerate the package instead of editing it; see [Regenerating](#regenerating).

FastAPI server generation is experimental.
The server supports the `pydantic_v2.BaseModel` and `pydantic_v2.dataclass` model backends, while client generation supports all five.

## Next steps

`main.py` serves the application of `create_app`; run it with an ASGI server, from the directory that holds the top-level package (add `--app-dir src` for a `src` layout):

```console
uv add uvicorn
uv run uvicorn app.server.main:app --reload
```

`fastapi dev` runs it too: `uv add "fastapi[standard]"`, then `uv run fastapi dev --entrypoint app.server.main:app` from the same directory, or `uv run --directory src fastapi dev --entrypoint app.server.main:app` for a `src` layout.
To pass other instances, such as fakes in tests, call `create_app` yourself; see [Implementing the services](#implementing-the-services).

## Dependencies

The package needs these distributions at run time:

- `fastapi>=0.141.1`

Add them to your project with the command each generation prints:

```console
uv add "fastapi>=0.141.1"
```

Running the application also needs an ASGI server: `uvicorn`, or `fastapi[standard]` for `fastapi dev`, as in [Next steps](#next-steps).

## Operations

| Service | Method | HTTP method | Path | Operation reference |
| --- | --- | --- | --- | --- |

`operation_dependencies` takes the method names, the keys of `OperationDependencies`; the per-operation generation settings, such as `--server-handler-modes`, take the operation references.

## Implementing the services

`services.py` declares a Protocol for each router group, with an abstract method for each operation of the group.
A method takes the operation's arguments as keywords, with `None` for an optional parameter or body the request omits, and returns the value to send, an `HTTPResult` with another declared status, headers, or both, or a `Response` sent as it is.
`main.py` passes an instance of each group's class to `create_app` under the group's name.
Subclass the Protocol, so that type checkers report a missing or mismatched method and Python refuses to create an instance while a method is missing; any other object with the same methods is checked where you pass it.
The package looks each method up when it registers the routes, and refuses a coroutine function where the operation's handler mode needs a plain method, or the reverse, and a method that cannot take the keyword arguments of its operation; type checkers check their types.

Call `create_app` yourself to pass other instances.
Tests pass fakes, as this pytest test does with FastAPI's `TestClient`, which needs `httpx2`: each fake subclasses your class of its group and overrides the methods the test calls.
An application that builds its services with arguments, such as a database pool or settings, calls `create_app` in a module of its own and runs that module's application instead of `main.py`'s.

```python
from fastapi.testclient import TestClient

from app.server import create_app


def test_app() -> None:
    with TestClient(create_app()) as client:
        ...
```

`create_app` passes its other keyword arguments, such as `lifespan`, `middleware`, or `dependencies`, to `FastAPI`, over the title, version, and other metadata of the source document.
To keep your own `FastAPI` application, include the router:

```python
from fastapi import FastAPI

from app.server import build_router

app = FastAPI()
app.include_router(build_router())
```

## Served OpenAPI document

`create_app` serves the part of the source document the selected operations use, which generation writes into `_generated/openapi.json`; the application reads it on the first request for it.
`_generated/openapi.json` is package data, so a distribution that holds the package must include it: Hatchling, uv_build, poetry-core, pdm-backend, and flit_core include it by default, while setuptools needs it in `package-data` or `MANIFEST.in`.
`create_app(..., source_openapi=False)` serves FastAPI's own document instead, built from the routes and the models they declare, in which an optional parameter or request body is `anyOf` of its type and `null`.
An application of your own that includes `build_router(...)` serves FastAPI's document unless it calls `serve_source_openapi(app)`, imported from `app.server`.

## Validation

The models are the contract: FastAPI validates parameters, bodies, and responses with the generated model types, so the model generation settings decide how strictly a value follows the OpenAPI document.
Parameter styles, parameter types, and media types that FastAPI cannot read, such as deepObject parameters or cookie arrays, strict integers, numbers, and booleans, text and binary bodies, and multipart forms, pass through generated adapters.
An adapter parses the HTTP syntax, then validates the value with the model's `TypeAdapter`; it answers `400` for malformed syntax, `415` for an undeclared media type, and `422`, with FastAPI's error records, for an invalid value.
A repeated single value is taken as FastAPI takes it, by adapters too: the last query value, cookie, form field, and object member, and the first header.
A cookie parameter with a single value arrives as the request sent it, without percent-decoding.
Adapters accept integers and numbers as JSON writes them and booleans as `true` or `false`, which is fewer spellings than FastAPI accepts for the parameters it reads.

## Production settings

A request that fails validation answers `422` with FastAPI's `{"detail": [...]}` records.
`create_app` keeps the `type`, `loc`, and `msg` of each record and leaves out the `input` and `ctx` FastAPI adds, and pydantic's `url`, so the response does not return the rejected value as such.
`loc` and `msg` are pydantic's and can still hold text the client chose: a mapping key or an unexpected field name, a discriminator tag, or the message of a validator of your own.
An application of your own that includes `build_router(...)` keeps FastAPI's records; register the same handler with `app.add_exception_handler(RequestValidationError, validation_error_handler)`, importing `validation_error_handler` from `app.server`.
To send other error bodies, pass FastAPI's `exception_handlers` to `create_app`; its entry for `RequestValidationError` replaces the package's.
A result that fails its response model answers `500` without details, and the error, with the values, goes to the server log, as in any FastAPI application.
`create_app(..., docs_url=None, redoc_url=None, openapi_url=None)` removes `/docs`, `/redoc`, and `/openapi.json`.
The `server` response header belongs to the ASGI server, not to the application: uvicorn leaves it out with `--no-server-header`.

## Regenerating

Run the same generation again whenever the OpenAPI document changes; the `--check` option reports the files it would change without writing them.
Generation overwrites every generated file, restoring any you edited or deleted, and never deletes one: delete the modules of removed operations yourself, which `--check` lists as extra files.
When an operation is added, removed, or changed, its method in `services.py` changes with it, so type checkers point at the implementations to update, and Python refuses to create an instance of a subclass that lacks a new method.
Each generation prints the `uv add` command that adds the runtime dependencies of the package to your project;
run it again when a new version of datamodel-code-generator changes them.

=== router.jinja2 / populated
"""Endpoints of 日本 {braces}; regenerate them instead of editing."""

from fastapi import APIRouter


def _add_get_pet(
    router: APIRouter,
    wiring: Wiring,
) -> None:
    pets: PetsService[object] = wiring.services['pets']
    get_pet_handler = checked(
        pets.get_pet,
        'The pets.get_pet method of GET /pets/{petId} 日本',
        ('petId',),
        asynchronous=True,
    )

    get_pet_authorize = wiring.authorizer()

    async def get_pet_principal(
        *,
        api_key: Annotated[str | None, Security(security.api_key)],
    ) -> object:
        return await authenticate(
            ((('api_key', ()),),),
            {'api_key': api_key},
            get_pet_authorize,
            'APIKey',
        )

    async def get_pet(
        *,
        pet_id: Annotated[int, Path(alias='petId')],
        limit: Annotated[int, Query(alias='limit')] = 20,
        principal: Annotated[object, Depends(get_pet_principal)],
    ) -> object:
        return dispatch(
            await get_pet_handler(
                pet_id=pet_id,
                limit=limit,
            ),
            contract.GetPet.RESPONSES,
        )

    router.add_api_route(
        '/pets/{petId}',
        get_pet,
        methods=['GET'],
        status_code=200,
        response_model=models.Pet,
        response_model_by_alias=True,
        response_model_exclude_unset=True,
        operation_id='getPet',
        summary='日本 {braces} \\ "quotes"',
        dependencies=wiring.dependencies.get('get_pet'),
    )


def _add_list_pets(
    router: APIRouter,
    wiring: Wiring,
) -> None:
    pets: PetsService = wiring.services['pets']
    list_pets_handler = checked(
        pets.list_pets,
        'The pets.list_pets method of GET /pets',
        ('limit', 'offset'),
    )

    def list_pets() -> object:
        return dispatch(
            list_pets_handler(),
            contract.ListPets.RESPONSES,
        )

    router.add_api_route(
        '/pets',
        list_pets,
        methods=['GET'],
        status_code=204,
        response_model=None,
        response_class=Response,
        dependencies=wiring.dependencies.get('list_pets'),
    )


LITERAL_ROUTES: Final = (
    ('list_pets', _add_list_pets),
)
TEMPLATED_ROUTES: Final = (
    ('get_pet', _add_get_pet),
)


def build_router(
    *,
    pets: PetsService[PrincipalT],
    authorize: Authorize[PrincipalT],
    dependencies: Sequence[params.Depends] = (),
    prefix: str = "",
) -> APIRouter:
    """Register the pets operations on a new router, literal paths first."""
    return build(
        (*LITERAL_ROUTES, *TEMPLATED_ROUTES),
        services={'pets': pets},
        authorize=authorize,
        dependencies=dependencies,
    )

=== router.jinja2 / mixed
"""Endpoints of 日本 {braces}; regenerate them instead of editing."""

from fastapi import APIRouter


def _add_get_pet(
    router: APIRouter,
    wiring: Wiring,
) -> None:
    pets: PetsService[object] = wiring.services['pets']
    get_pet_handler = checked(
        pets.get_pet,
        'The pets.get_pet method of GET /pets/{petId} 日本',
        ('petId',),
    )

    def get_pet(
        *,
        pet_id: Annotated[int, Path(alias='petId')],
        limit: Annotated[int, Query(alias='limit')] = 20,
    ) -> object:
        return dispatch(
            get_pet_handler(
                pet_id=pet_id,
                limit=limit,
            ),
            contract.GetPet.RESPONSES,
        )

    router.add_api_route(
        '/pets/{petId}',
        get_pet,
        methods=['GET'],
        status_code=200,
        response_model=models.Pet,
        response_model_by_alias=True,
        response_model_exclude_unset=True,
        operation_id='getPet',
        summary='日本 {braces} \\ "quotes"',
        dependencies=wiring.dependencies.get('get_pet'),
    )


def _add_list_pets(
    router: APIRouter,
    wiring: Wiring,
) -> None:
    pets: PetsService = wiring.services['pets']
    list_pets_handler = checked(
        pets.list_pets,
        'The pets.list_pets method of GET /pets',
        ('limit', 'offset'),
        asynchronous=True,
    )

    async def list_pets() -> object:
        return dispatch(
            await list_pets_handler(),
            contract.ListPets.RESPONSES,
        )

    router.add_api_route(
        '/pets',
        list_pets,
        methods=['GET'],
        status_code=204,
        response_model=None,
        response_class=Response,
        dependencies=wiring.dependencies.get('list_pets'),
    )


LITERAL_ROUTES: Final = (
    ('list_pets', _add_list_pets),
)
TEMPLATED_ROUTES: Final = (
    ('get_pet', _add_get_pet),
)


def build_router(
    *,
    pets: PetsService[PrincipalT],
    authorize: Authorize[PrincipalT],
    dependencies: Sequence[params.Depends] = (),
    prefix: str = "",
) -> APIRouter:
    """Register the pets operations on a new router, literal paths first."""
    return build(
        (*LITERAL_ROUTES, *TEMPLATED_ROUTES),
        services={'pets': pets},
        authorize=authorize,
        dependencies=dependencies,
    )

=== router.jinja2 / empty
"""Endpoints of 日本 {braces}; regenerate them instead of editing."""

from fastapi import APIRouter


LITERAL_ROUTES: Final = ()
TEMPLATED_ROUTES: Final = ()


def build_router(
    *,
) -> APIRouter:
    """Register every operation on a new router, literal paths first."""
    return build(
        (*LITERAL_ROUTES, *TEMPLATED_ROUTES),
        services={},
    )

=== security.jinja2 / populated
"""Security dependencies of this package, one for each scheme; override one with app.dependency_overrides."""

from fastapi.security import APIKeyHeader


api_key = APIKeyHeader(
    name='X-Key',
    description='日本 {braces}',
    auto_error=False,
)


def custom() -> object:
    """Return the custom 日本 credential, which no FastAPI security class reads; override this dependency."""
    return None


__all__ = [
    'api_key',
    'custom',
]

=== services.jinja2 / populated
"""Service interfaces of this package's router groups; regenerate them instead of editing."""

from __future__ import annotations

from typing import Protocol
from typing_extensions import TypeVar

PrincipalT_contra = TypeVar("PrincipalT_contra", contravariant=True)


class PetsService(Protocol[PrincipalT_contra]):
    """Pets 日本 {braces}"""

    @abstractmethod
    async def get_pet(
        self,
        *,
        pet_id: int,
        principal: PrincipalT_contra | None,
    ) -> models.Pet | HTTPResult[models.Pet] | Response:
        """
        Show a pet 日本 {braces} \\ \"quotes\".
        """

    @abstractmethod
    def list_pets(
        self,
    ) -> None | HTTPResult[None] | Response:
        """Handle GET /pets."""


class OtherService(Protocol):
    """Other"""

=== services.jinja2 / empty
"""Service interfaces of this package's router groups; regenerate them instead of editing."""

from __future__ import annotations

from typing import Protocol
