Files
romm/backend/utils/router.py
Stu Anderson e06e0e4010 chore(docs): better openapi descriptions (#5660)
* docs(api): describe the core endpoints and add a docs test

Give the parameters, operations and response fields of the core routers a
description in the OpenAPI document: roms, platforms, collections, users,
saves, states, screenshots, channels, snapshots, streaming, devices, client
tokens, play sessions, search, auth, music, memory cards, firmware, sync,
config, feeds, notifications and permissions.

Response models read attribute docstrings (`use_attribute_docstrings` on the
shared response `BaseModel`), so a string after a field is its description.
The update-rom form reads its descriptions from `RomUpdateForm`, so they
have one home. The paging parameters gain examples, such as 72 per page.

`tests/endpoints/test_openapi_docs.py` reads `app.openapi()` and fails when a
parameter or operation of a listed router has no description, or when a
schema with some described fields leaves others bare. Add a router to
`DOCUMENTED_ROUTERS` once its parameters and operations are described.

Descriptions only: no parameter, constraint or default changes. The frontend
types need regenerating (`npm run generate`).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* docs(api): describe the remaining routers and the roms list parameters

Cover the last routers (tasks, activity, heartbeat, audit events, stats, logs
and netplay) and add the routers to the docs test's allow-list, so every
router is now held to a description on each parameter and operation.

Describe the schemas that test found partly documented: the task status
responses and `TaskInfo` (as `Annotated[..., Field(...)]`, since a TypedDict
takes no attribute docstrings) and the audit page's `max_id`.

Rewrite the `GET /api/roms` parameters that did not say what they do:
`with_char_index`, `with_filter_values`, `with_rom_id_index`, `with_total`,
`with_provider_metadata`, `order_by`, `with_files`, `group_by_meta_id` and
`search_term`, each with an example or the values it accepts.

Replace a franchise name in an existing docstring example with a neutral one.

Descriptions only: no parameter, constraint or default changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* chore(api): regenerate the frontend types

Run `npm run generate` against the backend so the generated models carry the
descriptions added to the OpenAPI document. Only comments change: no type,
field or signature differs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* docs(api): fix alternative_names and shorten docstrings per review

Address the review feedback:

- Describe `alternative_names` as the hand-set titles when there are any,
  otherwise the titles from IGDB, MobyGames and ScreenScraper, as
  `resolve_alternative_names` returns them. It said every matched provider.
- Check HEAD routes in the docs test. Both existing HEAD routes already pass.
- Keep docstrings to one paragraph, as the repository asks. The test module
  docstring is one sentence and its two rules are short comments. Nineteen
  operation docstrings added in this change drop their second paragraph.

Descriptions and a test only: no parameter, constraint or default changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* chore(api): regenerate the frontend types

Pick up the corrected `alternative_names` description. Only comments change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* docs(api): correct descriptions that disagree with the code (pr-ready: code-review)

Fix 12 OpenAPI descriptions that contradicted handler behavior (empty
provider metadata, virtual collection types, streaming container lookup,
save device sync, user collections, search terms, file order, firmware
file name, audit max_id, play session offset, save target layouts).
Share the music filter descriptions through Annotated aliases and drop
comments that restated the new docstrings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(api): share parameter aliases and check every router (pr-ready: simplify)

Move the rom id and sort direction aliases to utils/router.py and reuse
them, add per-router id path aliases in place of repeated inline params,
let LimitOffsetPage inherit the shared BaseModel config, and drop Args
blocks that restated parameter descriptions. The docs test now covers
every /api path instead of an allowlist. The OpenAPI spec is unchanged
apart from description strings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(api): form model for rom updates, shared schema config and rom id alias

- Take RomUpdateForm as a FastAPI form model instead of 33 Form params
  and a duplicate field dict; only sent keys still count as provided.
- Document TypedDict responses with attribute docstrings through
  @with_config(API_SCHEMA_CONFIG) instead of per-field Annotated wrappers.
- Move request payload models onto the shared BaseModel and use
  attribute docstrings for their descriptions.
- Replace the 32 inline rom id path params with RomIdPath, which now
  carries ge=1 (adds minimum: 1 to the activity and streaming rom ids).

The update rom request body now references a RomUpdateForm schema; the
multipart fields are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): keep only the descriptions that explain something

Drop the field and parameter descriptions that restate the name, the
type, or what the schema already shows (enum and literal values,
defaults, bounds, nullability), along with the wrappers and aliases
that only carried them. Reword four that did not say what the field
is. The docs test now checks operations only, since requiring a
description on every parameter and field is what produced the filler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): plainer wording for three sync and rom descriptions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): rewrite clipped descriptions as full sentences

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): document error statuses in responses instead of docstrings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): document pairing code exchange errors

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): move error statuses from route docstrings into responses

Covers the routes whose docstrings stated an error in prose or in a
Raises: block, new in this PR or older.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-11-20 14:11:13 -05:00

91 lines
3.3 KiB
Python

import inspect
from collections.abc import Callable
from typing import Annotated, Any
from fastapi import APIRouter as FastAPIRouter
from fastapi import Path, Query
from fastapi.types import DecoratedCallable
from pydantic import BaseModel
RomIdPath = Annotated[int, Path(description="The ID of the rom.", ge=1)]
RomIdQuery = Annotated[int, Query(description="The ID of the rom.")]
OrderDirQuery = Annotated[
str, Query(description="The sort direction, `asc` or `desc`.")
]
class APIRouter(FastAPIRouter):
"""FastAPI router that automatically adds an alternate route with a trailing slash.
This is needed as FastAPI does not include a built-in way to handle routes with and without
trailing slashes, without requiring a redirect or duplicating the route definition.
Reference: https://github.com/fastapi/fastapi/discussions/7298
"""
def api_route(
self, path: str, *, include_in_schema: bool = True, **kwargs: Any
) -> Callable[[DecoratedCallable], DecoratedCallable]:
if path.endswith("/") and len(path) > 1:
path = path[:-1]
add_path = super().api_route(
path, include_in_schema=include_in_schema, **kwargs
)
alternate_path = path + "/"
add_alternate_path = super().api_route(
alternate_path, include_in_schema=False, **kwargs
)
def decorator(func: DecoratedCallable) -> DecoratedCallable:
# Path without trailing slash is registered first, for router's `url_path_for` to prefer it.
result = add_path(func)
add_alternate_path(func)
return result
return decorator
def as_query_dependency[ModelT: BaseModel](
model: type[ModelT],
) -> Callable[..., ModelT]:
"""Expose a model's fields as the individual query parameters of a route.
`Annotated[Model, Query()]` does this natively, but only on a route whose
*only* query parameter is the model (FastAPI's
`_get_flat_fields_from_params`). With any other one present the model stays
a single parameter named after the argument, which both documents the route
wrongly and makes it reject the fields it should accept. A dependency's
parameters are flattened individually, so this builds one whose signature
carries the fields, each with its own constraints.
"""
parameters: list[inspect.Parameter] = []
for name, field in model.model_fields.items():
# A signature default is built once, and a parameter is named for the
# field rather than its alias, so neither shape can be served here.
if field.default_factory is not None:
raise TypeError(f"{model.__name__}.{name} has a default_factory")
if field.alias is not None:
raise TypeError(f"{model.__name__}.{name} has an alias")
parameters.append(
inspect.Parameter(
name,
inspect.Parameter.KEYWORD_ONLY,
default=field.get_default(),
annotation=Annotated[
field.annotation,
*field.metadata,
Query(description=field.description),
],
)
)
def dependency(**kwargs: Any) -> ModelT:
return model(**kwargs)
dependency.__signature__ = inspect.Signature(parameters) # type: ignore[attr-defined]
return dependency