skip to content

In FastAPI, after overriding app.openapi() with get_openapi to add a logo, why did tag descriptions vanish and new routes stop appearing in the schema?

level: seniorimportance: nice to knowfreq 15%

answer

  1. the override replaces the whole build
  2. get_openapi knows only its arguments
  3. a cache you wrote yourself
  4. wrap the built-in instead

basics

~20 s

get_openapi uses only the arguments passed, so openapi_tags, servers and separate_input_output_schemas fall back to defaults unless forwarded, and the docs' cache guard keeps returning the first schema. Wrapping the built-in app.openapi keeps every setting and its refresh.

solid answer

~40 s

The `/openapi.json` route calls `app.openapi()`, so replacing that method replaces the whole schema build. `fastapi.openapi.utils.get_openapi` is a function of its arguments only: called with just `title`, `version` and `routes`, it drops `openapi_tags`, `servers`, `summary`, `description`, contact and license data, and uses `separate_input_output_schemas=True` whatever the app was given. The docs' recipe also caches with `if app.openapi_schema: return app.openapi_schema`. In FastAPI 0.143 the built-in method rebuilds when the route table changes, but that guard keeps serving the first schema, so routes added after it was built do not appear. The robust pattern keeps the built-in: save `builtin = app.openapi`, have the override call it, add `x-logo` to `schema["info"]`, and return it. For a change to one operation, use `openapi_extra` instead.

code

python · 34 lines
python
from fastapi import FastAPI

app = FastAPI(
    title="Shop API",
    version="2.5.0",
    openapi_tags=[{"name": "items", "description": "Browse the catalogue."}],
    separate_input_output_schemas=False,
)


@app.get("/items", tags=["items"])
def list_items():
    return []


builtin_openapi = app.openapi  # keeps every app setting and the route-change refresh


def openapi_with_logo():
    schema = builtin_openapi()
    schema["info"]["x-logo"] = {"url": "https://example.com/logo.png"}
    return schema


app.openapi = openapi_with_logo


@app.get("/orders", tags=["items"])
def list_orders():  # registered after the override, still documented
    return []


schema = app.openapi()
print(schema["info"]["x-logo"], schema["tags"][0]["name"], sorted(schema["paths"]))

go deeper

for a junior

Know that /openapi.json is produced by app.openapi() and that FastAPI lets you replace that method to customise the whole document.

for a middle

Explain what get_openapi needs as arguments and how app.openapi_schema caches the result between requests.

for a senior

Diagnose lost tags, reappearing -Input schemas and missing routes as an override that dropped settings or froze its cache, and fix it by wrapping the built-in.

for a principal

Keep schema customisation in the narrowest tool, and guard the published document with tests so upgrades and overrides cannot change it unnoticed.

## How FastAPI serves the schema When the app is created with a non-empty `openapi_url`, FastAPI registers a route there. That route does one thing: it calls the app's `openapi()` method and returns the result as JSON. The built-in method: 1. Checks whether `app.openapi_schema` already holds a schema and whether the route table has changed since it was built. 2. If it needs a new one, calls `fastapi.openapi.utils.get_openapi(...)`, passing every relevant app setting. 3. Stores the result in `app.openapi_schema` and records the route-table version it was built from. Assigning `app.openapi = custom_openapi` shadows that method on the instance, and the route then calls your function instead. That is the documented extension point, and it is also why an override can quietly lose things: everything step 2 used to pass is now your responsibility. ## What get_openapi needs from you `get_openapi` requires `title`, `version` and `routes`; every other argument has its own default and knows nothing about the app. | App setting | `get_openapi` argument | If you omit it | |---|---|---| | `summary`, `description` | `summary`, `description` | no summary or description in `info` | | `openapi_tags` | `tags` | tag descriptions and their order are gone | | `servers` | `servers` | the configured servers list is gone | | `terms_of_service`, `contact`, `license_info` | same names | the legal and contact block is gone | | `separate_input_output_schemas` | same name | defaults to `True`, so `-Input` and `-Output` schemas can reappear | | `app.webhooks` | `webhooks=app.webhooks.routes` | webhooks disappear | | `openapi_external_docs` | `external_docs` | the external docs link is gone | That table is the first half of the symptom: an override written from the docs' example passes `title`, `version`, `summary`, `description` and `routes`, so `openapi_tags` silently drops out. ## The cache trap The docs' example caches by hand: ```python def custom_openapi(): if app.openapi_schema: return app.openapi_schema ... ``` - In FastAPI 0.143 the built-in method rebuilds when the route table changes; this guard does not, so after the first build the schema is frozen. - Routes registered after that first build, for example a router included during startup or after a test has already fetched the schema, never appear. - Only a process restart, or code that sets `app.openapi_schema = None`, makes those later routes visible. ## The safer override Keep FastAPI's own build and change only what you need: ```python builtin_openapi = app.openapi def openapi_with_logo(): schema = builtin_openapi() schema["info"]["x-logo"] = {"url": "https://example.com/logo.png"} return schema app.openapi = openapi_with_logo ``` - Every app setting still flows into the schema, because the built-in method passes them. - The route-change refresh still works, because the built-in method still decides when to rebuild. - The edit is idempotent: setting the same key on the cached dict on every call is harmless. - Edits that walk the generated document, such as adding an extension to every operation, stay correct after a rebuild, because the wrapper runs again on the fresh schema. If you do need `get_openapi` directly, for example to emit a second, trimmed document, forward every setting from the table above and do not cache it behind a guard that ignores route changes. Note that its `openapi_version` defaults to `"3.1.0"`, the same version the app publishes. ## When not to override at all Most customisations have a narrower tool, and each one survives FastAPI upgrades better than a full override: - per-operation extensions or a hand-described body: `openapi_extra`; - extra status codes and their models: `responses`; - naming: `operation_id` and `generate_unique_id_function`; - API-level text: the `FastAPI()` metadata arguments; - Swagger UI behaviour: `swagger_ui_parameters`. Reserve the override for document-wide changes those cannot express, such as an `info`-level extension, post-processing every operation, or removing parts of the generated document for a published variant. ## Guarding the published document Whatever form the customisation takes, pin it with a test so an upgrade or a refactor cannot change the document unnoticed: 1. Build the app as production does, including routers included at startup. 2. Call `app.openapi()` and assert the extension is present, for example `schema["info"]["x-logo"]`. 3. Assert the settings survived: the tag names and order from `openapi_tags`, the `servers` list, and the component names you expect, with or without `-Input` and `-Output`. 4. Assert that a route registered late, the case the hand-written cache guard breaks, appears under `paths`. These assertions take a few lines and run in milliseconds, because building the schema needs no server and no network.

  • In FastAPI, why does assigning app.openapi = custom_openapi change what /openapi.json serves?
    The schema route FastAPI registers calls the app's `openapi()` method on every request. Assigning a function to `app.openapi` shadows the method on that instance, so the route calls your function. Nothing else needs re-registering, which is also why a mistake in the function silently changes the published document.
  • In FastAPI, when is a full app.openapi override justified instead of openapi_extra?
    When the change is document-wide: an `info`-level extension such as a logo, post-processing every operation, or removing internal parts for a published variant. Anything scoped to one operation belongs in `openapi_extra` or `responses`, which leave FastAPI's build and caching untouched.

  • get_openapi reads the app's settings automatically.
  • An app.openapi override only needs title, version and routes.
  • app.openapi_schema refreshes itself under a hand-written cache guard.
  • Overriding app.openapi requires re-registering the /openapi.json route.
  • A logo in info needs a fork of FastAPI's schema generator.

Assumes FastAPI 0.143, whose built-in app.openapi() rebuilds the cached schema when the route table changes; a hand-written cache guard does not.