skip to content

In FastAPI, how is each operationId generated by default, and how do you keep operationIds stable for a generated frontend client?

level: middleimportance: should knowfreq 32%

answer

  1. client method names come from it
  2. function name, path and method
  3. a function that receives an APIRoute
  4. tag plus function name
  5. uniqueness becomes your job

basics

~20 s

The default generate_unique_id joins function name, path and method, e.g. read_item_items__item_id__get, so renaming a path renames client methods. Set operation_id on a route, or pass generate_unique_id_function, typically tag plus function name, and keep them unique.

solid answer

~40 s

FastAPI gives each path operation a unique ID from `generate_unique_id`: the function name plus the full path with non-word characters turned into `_`, plus the lowercase method, so `read_item` on `GET /items/{item_id}` becomes `read_item_items__item_id__get`. Client generators name methods after `operationId`, so a new prefix or a renamed path renames every generated method. Two fixes: `operation_id="getItem"` on one decorator, which wins over everything, or `generate_unique_id_function=` on a decorator, an `APIRouter`, `include_router` or `FastAPI`, the most specific winning. FastAPI's docs return `f"{route.tags[0]}-{route.name}"`. Uniqueness is then yours: a duplicate only raises a `UserWarning` ("Duplicate Operation ID ...") when the schema is built, and the same function also names generated body models such as `Body_login_login_post`.

code

python · 28 lines
python
from fastapi import APIRouter, FastAPI
from fastapi.routing import APIRoute


def tag_and_name(route: APIRoute) -> str:
    return f"{route.tags[0]}-{route.name}"


app = FastAPI(generate_unique_id_function=tag_and_name)
items = APIRouter(prefix="/items", tags=["items"])


@items.get("/")
def list_items():
    return []


@items.get("/{item_id}", operation_id="getItem")
def read_item(item_id: int):
    return {"id": item_id}


app.include_router(items, prefix="/api/v2")

for path, ops in app.openapi()["paths"].items():
    print(path, ops["get"]["operationId"])
# /api/v2/items/ items-list_items
# /api/v2/items/{item_id} getItem

go deeper

for a junior

Know that FastAPI sets an operationId for every route and that generated client method names come from it.

for a middle

Explain the default recipe of name, path and method, then operation_id versus generate_unique_id_function and which scope wins.

for a senior

Anticipate the failure modes: prefix changes renaming a client, duplicates that only warn, untagged routes breaking a tag-based generator, unstable multi-method IDs.

for a principal

Fix the naming convention before the first client ships, since changing it later renames every consumer's calls at once.

## Why operationId matters here Every operation in an OpenAPI schema can carry an `operationId`, a string that must be unique across the document. Client generators turn it into a method name, so in a generated frontend client the `operationId` *is* the function a developer calls. FastAPI always sets one; the question is whether you like what it sets, and whether it stays the same as the code evolves. ## How FastAPI builds the default FastAPI computes a **unique ID** for each route with `fastapi.utils.generate_unique_id`: 1. Take the route's `name`, which defaults to the endpoint function's name, and append the full path format, including any router prefix. 2. Replace every non-word character with `_`. 3. Append `_` and the lowercase HTTP method. | Route | Default operationId | |---|---| | `GET /items/{item_id}` on `read_item` | `read_item_items__item_id__get` | | `POST /items/` on `create_item` | `create_item_items__post` | | `GET /users` on `list_users`, included with `prefix="/api/v1"` | `list_users_api_v1_users_get` | Unless a route sets `operation_id`, FastAPI uses this unique ID as its `operationId`. ## Why the default hurts generated clients - **Paths leak into method names.** A generator turns `create_item_items__post` into something like `createItemItemsPost`. - **Renames ripple.** Moving a router from `/api/v1` to `/api/v2`, or renaming a path segment, renames every affected client method even though nothing about the operation changed. - **Multi-method routes are unstable.** An `api_route` with `methods=["GET", "POST"]` gets one ID built from whichever method its internal set yields first, which can differ between processes, and both methods share that ID, so FastAPI warns about a duplicate. ## Ways to take control | Setting | Scope | Notes | |---|---|---| | `operation_id="getItem"` | one path operation | wins over every generator | | `generate_unique_id_function=` on the decorator | one path operation | | | `APIRouter(generate_unique_id_function=...)` | that router's operations | | | `include_router(..., generate_unique_id_function=...)` | one inclusion | | | `FastAPI(generate_unique_id_function=...)` | the whole app | | The function receives the `APIRoute` (with its effective tags, including those added by the router or `include_router`) and returns a string. When several scopes set one, the most specific wins: the path operation, then the `APIRouter`, then `include_router`, then the app. The pattern in FastAPI's docs is `f"{route.tags[0]}-{route.name}"`, giving `items-create_item`, stable across path changes and grouped the way generators group by tag. ## Keeping IDs unique Once you replace the default, uniqueness is your responsibility: - **Duplicates are only a warning.** FastAPI emits a `UserWarning` reading "Duplicate Operation ID ... for function ..." the first time it builds the schema, usually on the first request to `/openapi.json`, and keeps both IDs. A generator may then produce clashing methods. A test that builds `app.openapi()` with warnings turned into errors catches this in CI. - **Function names must be unique across modules** if the ID is just the function name, as FastAPI's docs warn. - **A tag-based generator needs a tag on every route.** `route.tags[0]` raises `IndexError` when an untagged route is registered, which fails at import rather than in production, a useful guard. - **The same function names generated models.** When an operation takes several body parameters, FastAPI wraps them in a model named `Body_` plus the unique ID, such as `Body_login_login_post`; a custom generator renames those types in the client too. ## Choosing a convention | Convention | Example ID | Stable across path changes | Main risk | |---|---|---|---| | FastAPI default | `create_item_items__post` | no | client renames on every prefix or path change | | tag plus function name | `items-create_item` | yes | needs exactly one meaningful tag per route | | function name only | `create_item` | yes | collisions between modules | | explicit `operation_id` everywhere | `createItem` | yes | easy to forget on a new route | The tag-plus-name generator from FastAPI's docs is a common choice for the whole app: the tag already exists for the docs, and its `IndexError` on an untagged route enforces the convention for free. For a public API whose client is generated, pick one convention early, apply it at the app level, and reserve `operation_id=` for the few operations whose client names need to differ. Changing the convention later renames the client's whole surface at once, which every consumer of the generated code feels as a breaking change.

  • In FastAPI, what happens when two path operations end up with the same operationId?
    FastAPI emits a `UserWarning`, "Duplicate Operation ID ... for function ...", when it builds the schema, then keeps both. Nothing fails, so a generated client may get two clashing methods. Building `app.openapi()` in a test with warnings turned into errors makes the duplicate fail CI instead.
  • In FastAPI, why can an api_route with methods=["GET", "POST"] get a different default operationId from one process start to the next?
    The default generator appends the first method from the route's set of methods, and the iteration order of a set of strings can change between interpreter runs. Both methods also share the one ID, so FastAPI warns about a duplicate. Separate decorators per method, or explicit `operation_id`s, make the IDs stable.

  • FastAPI's default operationId is just the function name.
  • FastAPI refuses to start when two operationIds collide.
  • The router prefix never affects default operationIds.
  • generate_unique_id_function can only be set on the FastAPI app.
  • Changing operationIds is harmless because clients call URLs, not IDs.