Service discovery and API documentation
Discover registered services, inspect their API contracts and local readiness, and publish documentation from Service metadata.
Federation publishes a service directory, per-service documentation, and an OpenAPI 3.1 document from the same registered Service, Action, and native route metadata. These documents describe the current instance, including custom services.
Discover services
The following GET endpoints are public and require no Federation token:
# Registered services and action summaries
curl -fsS 'https://fed.example.com/v1/services'
# Full documentation for one service
curl -fsS 'https://fed.example.com/v1/services/reports'
# Machine-readable API contract
curl -fsS 'https://fed.example.com/openapi.json' -o federation-openapi.jsonReplace reports with an id returned by the directory. These endpoints return Cache-Control: no-store. A missing service returns HTTP 404. Reading a document does not execute a business Action or grant permission to call it. Business endpoints still enforce their registered auth requirements.
Discover through the SDK
The public Federation entry supports discovery without a user or administrator token:
import { Federation } from "@downcity/federation";
const federation = new Federation({ url: "https://fed.example.com" });
const services = await federation.list_services();
const reports_document = await federation.describe_service("reports");
const api_document = await federation.openapi();list_services() returns the service array directly; describe_service(id) returns the detail object and rejects with an HTTP 404 error when the service is absent. openapi() returns the OpenAPI document. The same methods work on a local Federation configured with database; local calls dispatch in process without an HTTP listener.
Directory and detail fields
GET /v1/services returns an items array. Each item describes one registered service:
| Field | Meaning |
|---|---|
id | Service identifier used in /v1/services/{service_id} and its business route namespace. |
name | Display name. |
description | Short service description, or null when absent. |
env | Declared environment requirements: key, description, and required; no actual environment values. |
requirements | Public configuration and dependency requirements. |
availability | Local readiness status and optional public reason. |
actions | Registered business Action summaries. |
routes | Registered native HTTP route summaries, separate from Actions. |
docs_url | Relative URL of this service's detail document. |
Both entry arrays contain id, kind (action or native), description (string or null), method, path, auth, aliases, and availability, plus protocol when declared. aliases only contains HTTP aliases actually registered by Federation; native paths can contain wildcards.
GET /v1/services/{service_id} returns the service detail object directly. It retains the service summary fields and adds:
| Field | Meaning |
|---|---|
instruction | Resolved long-form guidance, or null when absent, empty, or unable to resolve. |
instruction_documented | Whether instruction text was supplied and resolved successfully. |
actions / routes | Detailed entries with the summary fields plus body, documentation, request_documented, and response_documented. |
An entry's documentation contains its declared description, request_schema, response_schema or response_content, media types, success status, errors, examples, protocol, and requirements. It is null when no documentation was registered. The availability callback and alias overrides are not serialized in this object; availability is a sibling result.
request_documented means a non-empty request schema was declared. response_documented means a non-empty response schema or at least one non-empty media-type response schema was declared. An empty object {} counts as undocumented. A false flag explicitly identifies a missing schema. True flags record declarations and do not certify their accuracy or completeness. The directory only carries summaries, so read the detail before constructing a request.
The list and OpenAPI do not resolve dynamic instruction text; only service detail does. OpenAPI generation does not run availability checks. Its HTTP servers URL uses the request origin.
Interpret availability
availability describes local configuration and dependencies:
status | Meaning |
|---|---|
ready | The declared local conditions are satisfied. |
partial | Only some entries are ready. Inspect the individual entries. |
unavailable | A required local dependency or configuration is explicitly missing. |
unknown | No check was provided, or the check did not produce a usable result. |
The optional reason is a safe, public explanation. A ready service does not promise that an upstream provider is online, that the caller has permission, or that the account has enough balance. An unknown result does not establish that the service is offline.
Service-level unavailable constrains all entries. Otherwise an entry uses its own check, falls back to the Service check, or returns unknown. The service status aggregates both Actions and native routes. Local checks are bounded to one second; failures, timeouts, and invalid results become unknown. Availability may change between discovery and a business call.
Checks must only read local configuration or dependency state. Do not call a paid API, generate content, send a notification, or run another business operation to produce availability. Never return raw exceptions, secrets, connection strings, or private account details in reason.
Publish a documented Service
Declare a short description and public requirements in the Service constructor. Put longer usage guidance in service.instruction; the documentation projection reuses that text. Each Action declares its own documentation alongside method, auth, and body.
This Node example reads one local configuration value. In a Worker, supply the value from the host's bindings instead.
import { Federation, Service } from "@downcity/federation";
const report_prefix = process.env.REPORT_PREFIX?.trim();
const check_availability = () => ({
status: report_prefix ? ("ready" as const) : ("unavailable" as const),
reason: report_prefix
? "Local configuration is present"
: "REPORT_PREFIX is required",
});
const reports = new Service({
id: "reports",
name: "Reports",
description: "Format report titles with the configured prefix.",
env: [{
key: "REPORT_PREFIX",
description: "Prefix for report titles",
required: true,
}],
requirements: ["The host must configure REPORT_PREFIX."],
availability: check_availability,
});
reports.instruction = [
"Use POST /v1/reports/title with a user token.",
"Send a non-empty title. The response contains the prefixed title.",
"This operation formats text locally and does not save a report.",
].join("\n");
reports.action("title", async (ctx) => {
const title = ctx.input.title;
if (typeof title !== "string" || !title.trim()) {
throw Object.assign(new Error("title must be a non-empty string"), {
statusCode: 400,
code: "INVALID_TITLE",
});
}
if (!report_prefix) {
throw Object.assign(new Error("Report formatting is unavailable"), {
statusCode: 503,
code: "REPORTS_UNAVAILABLE",
});
}
return { title: `${report_prefix}: ${title.trim()}` };
}, {
method: "POST",
auth: ["user"],
documentation: {
description: "Prefix a non-empty report title; no report is stored.",
requirements: ["REPORT_PREFIX must be configured."],
availability: check_availability,
request_schema: {
type: "object",
properties: { title: { type: "string", minLength: 1, pattern: "\\S" } },
required: ["title"],
},
response_schema: {
type: "object",
properties: { title: { type: "string" } },
required: ["title"],
},
errors: [
{ status: 400, description: "title is missing, blank, or not a string." },
{ status: 401, description: "A valid user token is required." },
{ status: 503, description: "REPORT_PREFIX is not configured." },
],
examples: [{
name: "Format a title",
request: { title: "Weekly summary" },
response: { title: "REPORT_PREFIX_PLACEHOLDER: Weekly summary" },
}],
},
});
const federation = new Federation({ database });
federation.use(reports);database is the host's explicit database Adapter. See Database adapters for configuration. Register Services before preparing or serving the instance.
Call the Action using a placeholder token in documentation:
curl -fsS 'https://fed.example.com/v1/reports/title' \
-H 'Authorization: Bearer USER_TOKEN_PLACEHOLDER' \
-H 'Content-Type: application/json' \
--data '{"title":"Weekly summary"}'The example response assumes a local prefix of REPORT_PREFIX_PLACEHOLDER. The handler performs its own input and configuration checks. JSON Schema in documentation describes the contract; it does not add runtime validation or change how Action bodies are parsed.
Documentation fields
Action options and native route configuration accept documentation with these fields:
| Field | Meaning |
|---|---|
description | Required public explanation of purpose, behavior, and limits. |
request_schema | Optional JSON Schema for input. GET uses query input; POST normally uses a JSON object. |
response_schema | Optional JSON Schema for the successful response. |
response_status | Successful HTTP status; defaults to 200. |
request_content_type | Request body media type; OpenAPI defaults to application/json for JSON Actions and text/plain for raw input. GET has no request body. |
response_content_type | Successful response media type; defaults to application/json. |
response_content | A media-type-to-schema map for multiple response formats under the same success status. Takes precedence over the single response schema and media type. |
protocol | Protocol hint such as sse, oauth, webhook, or binary. |
errors | { status, description } entries explaining error conditions. |
examples | { name, request?, response? } examples. GET requests use a query object; raw input or streaming output can use text. |
requirements | Public configuration or dependency requirements, with names rather than secret values. |
availability | A function returning { status, reason? }, synchronously or asynchronously, from local checks. |
aliases | Documentation overrides keyed by an already registered alias's absolute HTTP path. An override accepts the documentation fields except availability and nested aliases; it does not register a route. |
Supply meaningful schemas, concrete errors, and representative requests and responses. If a schema is missing, the contract is incomplete. Omit an unknown schema rather than setting {} and implying that the API is fully described. For complex workflows, explain the steps once in instruction and keep entry descriptions focused on the specific operation.
All directory fields, instructions, schemas, examples, requirements, availability reasons, and OpenAPI output are public. Use placeholders for credentials and sensitive data; never interpolate actual environment values or caught exception messages into documentation.
Native routes and streaming
Use ServiceInstallContext.route() with handler: { request } for native Request/Response protocols. Declare documentation on the route configuration, outside the handler. Native handlers own their response format; documenting a route does not wrap it in an Action JSON response.
This complete native route sends one SSE event and closes. It has no query input and no business-error responses:
import {
InstallableService,
type ServiceInstallContext,
} from "@downcity/federation";
class EventsService extends InstallableService {
override readonly id = "events";
override readonly name = "Events";
install(ctx: ServiceInstallContext): void {
ctx.route({
method: "GET",
path: "/ready",
auth: [],
documentation: {
description: "Send a ready event and close the stream.",
protocol: "sse",
request_schema: {
type: "object",
description: "This route takes no query parameters.",
},
response_content_type: "text/event-stream",
response_schema: {
type: "string",
description: "SSE wire text containing one ready event.",
},
availability: () => ({ status: "ready" }),
examples: [{
name: "Ready event",
request: {},
response: 'event: ready\ndata: {"ok":true}\n\n',
}],
},
handler: {
request: () => new Response('event: ready\ndata: {"ok":true}\n\n', {
headers: { "Content-Type": "text/event-stream" },
}),
},
});
}
}
federation.use(new EventsService());curl -N 'https://fed.example.com/v1/events/ready'For long-lived streams, describe event names, payloads, terminal events, and in-stream failures. response_schema and examples must describe the actual stream rather than a fictitious buffered JSON result. Set response_content_type to the real media type; protocol is descriptive metadata and does not implement streaming or error handling.
For OAuth callbacks, redirects, webhook signature verification, or binary downloads, document the actual request and response media types and successful status. Explain headers, redirects, signature requirements, and other protocol details in description or instruction. Public Federation access (auth: []) does not verify a webhook signature or authorize an external OAuth session; the native handler must implement those checks.
Use OpenAPI
Download /openapi.json for an API viewer or client-generation tool that supports OpenAPI 3.1. Service documentation and OpenAPI read the same registration metadata, so update the Service or route declaration when its contract changes.
The projection uses registered HTTP methods and paths. GET Action schema properties become query parameters; body-taking operations use requestBody; successful responses use response_status and the declared media types. response_content allows multiple successful response formats, such as JSON and SSE, under one status.
OpenAPI includes these extensions:
| Extension | Meaning |
|---|---|
x-downcity-auth | Declared Federation identities. security uses the HTTP bearerAuth scheme when this array is non-empty. |
x-downcity-kind / x-downcity-body | Entry kind and registered body mode. |
x-downcity-documentation | { request, response } schema-declaration flags; missing schemas remain explicit. |
x-downcity-protocol / x-downcity-requirements | Declared protocol and public dependency requirements. |
x-downcity-request-schema | Preserves a GET or bodyless/native request schema where needed. |
x-downcity-alias-of | Main path for a registered HTTP alias. |
x-downcity-wildcard-path | Original native wildcard path; the OpenAPI path uses {wildcard}. |
x-downcity-method | ALL when a native route is projected across standard HTTP methods. |
A wildcard template cannot fully express the runtime's empty-tail matching behavior. Consult the original wildcard extension and native protocol instructions. Schema coverage reflects registered declarations; custom Channel-specific protocols may need additional documentation. Do not assume that every Channel contract is fully described by the generic AI entry.
Authentication remains entry-specific: Actions default to auth: ["user"]; auth: ["admin"] requires an administrator identity; auth: [] allows unauthenticated access; auth: ["user", "admin"] explicitly declares both identities. Administrators pass the framework's route identity check, but handlers that access user-owned resources may still require a valid user context. Public access to the OpenAPI document does not make a protected operation public. Use the credentials appropriate to the operation, and keep real tokens out of exported examples.
Check the declared response media type before choosing a client. A text/event-stream response needs an SSE reader. A redirect, OAuth exchange, webhook, or binary response follows its declared native protocol. A generated JSON method alone cannot implement those interactions; use the entry's description, examples, and service instruction together with the OpenAPI contract.