Skip to content

Publish an OpenAPI document for the docs API and answer errors as RFC 9457 problems - #4896

Merged
akira28 merged 4 commits into
mainfrom
feature/docs-api-openapi
Nov 18, 2026
Merged

akira28 merged 4 commits into
mainfrom
feature/docs-api-openapi

Conversation

@akira28

@akira28 akira28 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

The docs API now describes itself: GET /docs/_api/v1/openapi.json serves an OpenAPI 3.2 document generated from the endpoints. Every error is now an RFC 9457 problem (application/problem+json), including errors that used to come back empty.

Affects: API

Closes: elastic/docs-eng-team#1205

Stack: third layer of #4895, on top of #4894 (hardening) and #4887 (API operations).

Prompt summary: After hardening the docs API (#4894), make every error use one body and declare each endpoint's response types (review findings 8 and 9), and publish an OpenAPI spec as described in elastic/docs-eng-team#1205. Then adopt RFC 9457 for that error body, before anything outside the unreleased CLI command reads it.

Why

The API had no contract: clients copied routes and shapes by hand. Errors came in several shapes:

  • {errorType, message} from the API operations endpoints.
  • An empty 400 from navigation search, page feedback and parameter binding.
  • A bare 503 from feedback.
  • A bad /changes cursor silently restarted the feed.

"Not found" was inferred from an _not_found suffix on the error type.

What

OpenAPI document

  • Generation: Microsoft.AspNetCore.OpenApi (11.0.0, MIT; it needs Microsoft.OpenApi [3.11.0, 4.0.0), which the repo already pins). MapOpenApi serves the document at /docs/_api/v1/openapi.json.
  • Endpoint metadata: every endpoint declares a tag (Search, Ask AI, Changes, Page feedback, API reference), a summary, its success type, and its error codes through a small ProducesErrors helper. Every endpoint also lists 500.
  • Excluded: the empty root probe routes.
  • Document info: the title, the public server, and a description. The description names the CDN cookie gate here; Stop documenting the docs API cookie gate #4898 drops that once the gate is gone.
  • Native AOT: the document initially failed in the native AOT binary, though it built without warnings and passed every test, because AOT has no reflection fallback for parameter types such as bool?.
    • ApiJsonContext now registers the route and query parameter types.
    • The test host removes the reflection resolver from the app's JSON options, so it runs like the AOT app. A missing type now fails OpenApiDocumentTests instead of production.
  • Operation names: every endpoint is named (search, get-api-operation, ...). API Explorer uses them for page slugs, such as operation-search.

RFC 9457 problems

Every error is a problem: type, title, status, detail, plus the request's traceId.

type (fragment of …/docs-builder/tree/main/data/api) Status
#invalid-arguments 400
#not-found, #operation-not-found, #api-not-found, #group-not-found 404
#internal-error 500
#search-unavailable (with Retry-After), #feedback-unavailable 503
  • Type URIs: each type resolves to its own section of docs/data/api.md, which this PR adds with a custom anchor per type. The local build renders all eight anchors. They use docs-v3-preview.elastic.dev, where docs-builder's docs live today. Clients match on type, so moving them later is a breaking change; the base URL is one constant in ApiProblems if a permanent home is preferred before release.
  • Titles and details: a title is the same for every occurrence of a type (RFC 9457 §3.1.3), and what varies goes in detail. A 500 never includes the exception message.
  • How they're written:
    • AddProblemDetails writes every problem.
    • ApiProblems.Customize gives a type to the problems ASP.NET writes itself.
    • UseExceptionHandler has no custom writer; its StatusCodeSelector maps binding failures to 400, SearchUnavailableException to 503 with Retry-After, and everything else to 500.
    • UseStatusCodePages covers bodyless errors, such as size=many, which fails binding without throwing.
  • Logging: binding failures aren't logged as errors (SuppressDiagnosticsCallback).
  • The service's errors: the endpoints return problems for their own errors too: navigation search and page feedback 400s, both feedback 503s, and a /changes cursor the endpoint didn't return. That last case is now a 400 instead of silently restarting the feed.
  • Rejections: ApiReferenceRejection gains IsNotFound through Invalid(...) and NotFound(type, ...) factories, replacing the _not_found suffix check. Its snake_case type, which MCP keeps, maps to the kebab-case fragment.
  • Spec: ProducesProblem describes every error as application/problem+json with the ProblemDetails schema.
  • Tests: the HTTP snapshots scrub traceId, which differs on every request.
  • Docs: docs/data/api.md links the spec, documents each problem type, and drops the "OpenAPI as a follow-up" note.

Verify

dotnet test --project tests/Elastic.Documentation.Api.Tests
# OpenApiDocumentTests: every path with its status codes, unique operation ids, ProblemDetails on every error, info and server
# ApiErrorResponseTests: problems for binding failures, the /changes cursor, feedback and search 503
# http snapshots: page feedback 400s now carry a problem; no status changed
dotnet test --project tests/Mcp.Remote.Tests
dotnet publish src/api/Elastic.Documentation.Api -c Release -r osx-arm64
# then run the binary and GET /docs/_api/v1/openapi.json

Locally: 290 API tests and 76 MCP tests pass. The AOT publish has no trim or AOT warnings. The native binary serves the document and answers problems for a bad parameter, a missing parameter and an unknown path.

Out of scope: listing this document in API Explorer is the next PR in the stack.

🤖 Generated with Claude Code

@akira28
akira28 added this pull request to stack #4895 November 17, 2026 14:51
@akira28 akira28 changed the title feature/docs api openapi Publish an OpenAPI document for the docs API and use one error body Nov 17, 2026
@github-actions

Copy link
Copy Markdown
Contributor

akira28 added a commit that referenced this pull request Nov 17, 2026
The copy follows #4896, where every error is now an RFC 9457 problem.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@akira28 akira28 changed the title Publish an OpenAPI document for the docs API and use one error body Publish an OpenAPI document for the docs API and answer errors as RFC 9457 problems Nov 17, 2026
@akira28
akira28 force-pushed the feature/docs-api-openapi branch from 3c8c1a7 to 52977d7 Compare November 17, 2026 15:48
akira28 added a commit that referenced this pull request Nov 17, 2026
The copy follows #4896, where every error is now an RFC 9457 problem.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@akira28
akira28 force-pushed the feature/docs-api-openapi branch from 52977d7 to 4b45de0 Compare November 17, 2026 16:24
akira28 added a commit that referenced this pull request Nov 17, 2026
The copy follows #4896, where every error is now an RFC 9457 problem.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@akira28
akira28 force-pushed the feature/docs-api-openapi branch 2 times, most recently from 1c780b3 to 6be5357 Compare November 18, 2026 09:38
@akira28
akira28 marked this pull request as ready for review November 18, 2026 09:39
@akira28
akira28 requested a review from a team as a code owner November 18, 2026 09:39
@akira28
akira28 requested a review from reakaleek November 18, 2026 09:39
Comment thread docs/data/api.md
### Errors

A request these resources can't answer returns `{ "errorType": "...", "message": "..." }`. The status is `404` when `errorType` ends in `_not_found`: `operation_not_found`, `api_not_found`, or `group_not_found`. Invalid arguments return `400` with `invalid_arguments`.
The API operations resources report errors like every other endpoint; see [Errors](#errors).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: P3 (Low)

The page now has two headings called "Errors": this ### Errors and the new ## Errors further down. [Errors](#errors) will resolve to the first one, which is this subsection, so the link points back to itself instead of to the problem-type reference. Give the new section a custom anchor (for example ## Errors [problems]) and link to that.

Generated by Libra. Specialist: libra-complexity. React with 👍 or 👎 to give feedback on this comment.

.WithName("list-apis")
.WithSummary("List every API")
.Produces<ApiListResponse>()
.ProducesErrors();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: P3 (Low)

Declare 503 for the other API-reference endpoints too. Listing APIs, reading an API, listing groups, and reading an operation all reach ApiGateway.Search, which throws SearchUnavailableException on timeout or overload. The middleware returns a retryable 503, but these operations omit it from the new OpenAPI contract; only the operations collection declares it. Add 503 to their response metadata and update the document assertions.

Generated by Libra. React with 👍 or 👎 to give feedback on this comment.

Comment on lines +269 to +270
[FromQuery(Name = "include_deprecated")] bool? includeDeprecated,
ApiReferenceService apiReference,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: P3 (Low)

An empty cursor (/changes?since=...&cursor=) now returns 400. Minimal APIs bind cursor= to "", not null, so cursor is not null passes, and IsValidCursor("") is false because DecodeCursor returns null for blank input. Before this change a blank cursor meant the first page. A client that always sends the parameter and leaves it empty for the first request will now fail. Use !string.IsNullOrWhiteSpace(cursor) && !ChangesService.IsValidCursor(cursor) so only a non-empty cursor the endpoint never returned is rejected.

Generated by Libra. Specialist: libra-complexity. React with 👍 or 👎 to give feedback on this comment.

Comment on lines +58 to +61
: app.UseExceptionHandler(new ExceptionHandlerOptions
{
var ex = context.Features.Get<IExceptionHandlerFeature>()?.Error;
ApiError error;
if (ex is SearchUnavailableException)
{
// Transient by construction (timeout, overload): tell clients and the CDN to retry instead of failing.
logger.LogWarning(ex, "Search unavailable on {Method} {Path}", context.Request.Method, context.Request.Path);
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
context.Response.Headers.RetryAfter = "5";
error = new ApiError("search_unavailable", ex.Message);
}
else
{
if (ex != null)
logger.LogError(ex, "Unhandled exception on {Method} {Path}", context.Request.Method, context.Request.Path);
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
error = new ApiError("internal_error", "An unexpected error occurred.");
}
await context.Response.WriteAsJsonAsync(error, ApiJsonContext.Default.ApiError);
}));
// No handler: with AddProblemDetails the middleware writes the problem, typed by ApiProblems.Customize.
StatusCodeSelector = ApiProblems.StatusCodeFor,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: P3 (Low)

Keep a problem-writing fallback for SSE requests. The Ask AI clients use fetchEventSource, which sends Accept: text/event-stream, but the default AddProblemDetails writer does not accept that media type. With the custom exception writer removed, binding failures and provider exceptions before streaming return an empty 400/500 instead of the declared problem document. Add a writer/fallback that covers these requests and test with the actual SSE Accept header.

Generated by Libra. React with 👍 or 👎 to give feedback on this comment.

Comment on lines +58 to +64
: app.UseExceptionHandler(new ExceptionHandlerOptions
{
var ex = context.Features.Get<IExceptionHandlerFeature>()?.Error;
ApiError error;
if (ex is SearchUnavailableException)
{
// Transient by construction (timeout, overload): tell clients and the CDN to retry instead of failing.
logger.LogWarning(ex, "Search unavailable on {Method} {Path}", context.Request.Method, context.Request.Path);
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
context.Response.Headers.RetryAfter = "5";
error = new ApiError("search_unavailable", ex.Message);
}
else
{
if (ex != null)
logger.LogError(ex, "Unhandled exception on {Method} {Path}", context.Request.Method, context.Request.Path);
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
error = new ApiError("internal_error", "An unexpected error occurred.");
}
await context.Response.WriteAsJsonAsync(error, ApiJsonContext.Default.ApiError);
}));
// No handler: with AddProblemDetails the middleware writes the problem, typed by ApiProblems.Customize.
StatusCodeSelector = ApiProblems.StatusCodeFor,
// A parameter that does not bind is the client's mistake, not an error worth logging.
SuppressDiagnosticsCallback = context => context.Exception is BadHttpRequestException
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: P3 (Low)

The old handler logged SearchUnavailableException as a warning, on purpose, because it is a transient timeout or overload. With no custom handler, ExceptionHandlerMiddleware now logs every exception that isn't suppressed at Error level, and SuppressDiagnosticsCallback only suppresses BadHttpRequestException. Every 503 caused by Elasticsearch overload will now show up as an unhandled error, which can trigger error alerts during load spikes. Either suppress diagnostics for SearchUnavailableException too and log it as a warning yourself, or confirm that the change in log level is intended.

Generated by Libra. Specialist: libra-complexity. React with 👍 or 👎 to give feedback on this comment.


status.Should().Be(HttpStatusCode.BadRequest);
body.GetProperty("detail").GetString().Should().Be("cursor is not a nextCursor that /changes returned.");
A.CallTo(Changes.Current).MustNotHaveHappened();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: P3 (Low)

Inject Changes.Current into the test host before asserting that it was not called. SharedFactory replaces only the search and feedback services, so /changes resolves the production IChangesService, while this assertion checks an unrelated fake. It can never detect backend work before cursor rejection. Add an IChangesService replacement alongside the existing service swaps.

Generated by Libra. React with 👍 or 👎 to give feedback on this comment.

Base automatically changed from fix/docs-api-hardening to main November 18, 2026 10:00
akira28 and others added 4 commits November 18, 2026 11:00
The API serves its OpenAPI document at /docs/_api/v1/openapi.json, generated
from the endpoints, which now declare their tags, summaries and response
types. Every error answers { errorType, message }: navigation search and page
feedback 400s, the feedback 503s, parameters that do not bind, and a /changes
cursor the endpoint did not return, which used to restart the feed. API
reference rejections say whether nothing matched instead of relying on a
_not_found suffix. ApiJsonContext gains the parameter types, without which
the document fails under Native AOT, and the test host drops the reflection
fallback so such gaps fail a test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Without operation ids, API Explorer derives page slugs and ids from the paths, such as docs-api:docs-_api-v1-search. Names give it docs-api:search.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Errors are application/problem+json with a type URI per problem, a fixed
title, the occurrence in detail, and the request's traceId. AddProblemDetails
writes them; ApiProblems.Customize types the problems ASP.NET writes itself,
so the exception handler and status code pages no longer need custom writers.
Each type resolves to its section of the REST API page. ApiError is gone, and
the spec describes every error as ProblemDetails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@akira28
akira28 force-pushed the feature/docs-api-openapi branch from 6be5357 to 638f314 Compare November 18, 2026 10:00
@akira28
akira28 merged commit 9c3c075 into main Nov 18, 2026
44 checks passed
@akira28
akira28 deleted the feature/docs-api-openapi branch November 18, 2026 10:18
akira28 added a commit that referenced this pull request Nov 18, 2026
The copy follows #4896, where every error is now an RFC 9457 problem.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants