# API Genie > API Genie is a command-line toolkit for API-first development. `apigenie` lints, formats, diffs, bundles, converts and translates OpenAPI 3.x, Swagger 2.0, AsyncAPI, Protobuf and GraphQL files, and contract-tests live APIs; `apigenie-generator` generates clients, servers and documentation for TypeScript, Python, Go, Java, C#, Elixir and Rust (experimental); `apigenie-server` serves mocks and validating proxies for HTTP, WebSocket, MQTT, gRPC and GraphQL. --- # Documentation Source: https://apigenie.pl/docs Learn API Genie with the Quickstart, the guides and the concepts, look up every command in the reference, and read what each linter rule checks. Every page of Docs has a Markdown copy at the same address plus `.md`; /llms.txt lists them. ## Get started Install the CLI and run the first commands on an API you have, a new one, or a set of APIs to keep consistent. - [Quickstart](/docs/quickstart.md) ## How-to guides One job each, from the first command to CI. All of them: [How-to guides](/docs/guides.md). - [Lint and format API descriptions](/docs/guides/lint-and-format-api-descriptions.md) - [Catch breaking changes in CI](/docs/guides/catch-breaking-changes-in-ci.md) - [Generate a client and a server](/docs/guides/generate-a-client-and-a-server.md) - [Mock and contract-test an API](/docs/guides/mock-and-contract-test-an-api.md) - [Publish API documentation](/docs/guides/publish-api-documentation.md) - [Edit an API in forms](/docs/guides/edit-an-api-in-forms.md) - [Catalog the APIs of a repository](/docs/guides/catalog-the-apis-of-a-repository.md) - [Work with AI agents](/docs/guides/work-with-ai-agents.md) ## Coming from another tool What changes, what stays and what has no counterpart when a repository moves to API Genie. All of them: [Coming from another tool](/docs/guides.md#coming-from-another-tool). - [Migrate from Spectral](/docs/guides/migrate-from-spectral.md) - [Migrate from Prism](/docs/guides/migrate-from-prism.md) - [Migrate from OpenAPI Generator](/docs/guides/migrate-from-openapi-generator.md) - [Migrate from Buf](/docs/guides/migrate-from-buf.md) - [Migrate from Redocly CLI](/docs/guides/migrate-from-redocly.md) - [Migrate from oasdiff](/docs/guides/migrate-from-oasdiff.md) ## By industry Repositories that follow an industry's own API rules, such as CAMARA's. All of them: [By industry](/docs/guides.md#by-industry). - [Lint CAMARA APIs](/docs/guides/industry/lint-camara-apis.md) ## Concepts How the tools decide, each explained with a document to try it on: the mock's answers, the proxy's checks, the configuration file and the catalog. - [How the mock picks a response](/docs/concepts/how-the-mock-picks-a-response.md) - [What the validating proxy checks](/docs/concepts/what-the-proxy-checks.md) - [Where apigenie.yaml is found and how settings merge](/docs/concepts/where-the-configuration-is-found.md) - [What the catalog counts as a specification](/docs/concepts/what-the-catalog-counts-as-a-specification.md) - [The compatibility promise](/docs/reference/cli/compatibility.md) ## Reference Every command, option and setting, by product. - [CLI](/docs/reference/cli.md): `apigenie` - [Generator](/docs/reference/generator.md): `apigenie-generator` - [Server](/docs/reference/server.md): `apigenie-server` - [Catalog](/docs/reference/catalog.md): `apigenie-catalog` - [Editor](/docs/reference/editor/hosts.md) - [Doc components](/docs/reference/doc-components.md): `@mykulyak/apigenie-docs` ## CI Lint, format and diff in every pull request, on any system. All of them: [CI](/docs/ci.md). - [GitHub Action](/docs/ci/github-action.md) - [GitLab CI](/docs/ci/gitlab.md) - [Azure Pipelines](/docs/ci/azure-pipelines.md) - [Jenkins](/docs/ci/jenkins.md) - [CircleCI](/docs/ci/circleci.md) - [Bitbucket Pipelines](/docs/ci/bitbucket-pipelines.md) ## Linter rules What each rule of apigenie lint checks and why, and the rulesets that turn them on. All of them: [Linter rules](/docs/linter.md). - [OpenAPI: 67 rules](/docs/linter/openapi.md) - [AsyncAPI: 42 rules](/docs/linter/asyncapi.md) - [Swagger 2.0: 48 rules](/docs/linter/swagger.md) - [GraphQL: 87 rules](/docs/linter/graphql.md) - [Protobuf: 39 rules](/docs/linter/protobuf.md) ## Help The questions teams ask before adopting, and what to do when a command misbehaves. - [FAQ](/docs/faq.md) - [Troubleshooting](/docs/troubleshooting.md) ## Changelog What changed in each release of the CLI. - [Changelog](/changelog.md) --- # Quickstart Source: https://apigenie.pl/docs/quickstart Install the tools, pick where you are starting from, and run your first commands. Each path takes about five minutes, with an OpenAPI file of your own or the example below. ## Install One package installs the five command-line tools: `apigenie`, `apigenie-generator`, `apigenie-server`, `apigenie-catalog` and `apigenie-mcp`. Pick the channel that fits where you work; `apigenie --version` prints the version of all five. ### Homebrew On macOS and Linux: ```sh brew install mykulyak/apigenie/apigenie apigenie --version ``` ### npm Anywhere Node.js 18 or later runs, Windows included. The package downloads the binaries of your platform: ```sh npm install -g @mykulyak/api-genie apigenie --version ``` `npx @mykulyak/api-genie --version` runs the CLI without a global install. ### Docker Two images, built for `linux/amd64`, work in `/mnt/data`, so mount the directory of your files there. `mykulyak/apigenie` runs `apigenie` and holds `apigenie-generator` (`--entrypoint apigenie-generator`): ```sh docker run --rm -v "$PWD:/mnt/data" mykulyak/apigenie lint openapi.yaml ``` `mykulyak/apigenie-server` runs the mock, listening on every interface of the container, on port 4010: ```sh docker run --rm -p 4010:4010 -v "$PWD:/mnt/data" mykulyak/apigenie-server openapi.yaml ``` ### Linux packages [Downloads](/downloads) has a `.deb`, an `.rpm` and a `.tar.gz` for x64 Linux, each with a `.sha256` file next to it. The packages put the tools in `/usr/bin`: ```sh sudo dpkg -i apigenie--linux-x64.deb # Debian and Ubuntu sudo rpm -i apigenie--linux-x64.rpm # Fedora and RHEL ``` The archive holds the executables without a directory, so extract it where you keep binaries: ```sh sha256sum -c apigenie--linux-x64.tar.gz.sha256 sudo tar -xzf apigenie--linux-x64.tar.gz -C /usr/local/bin ``` ### Windows Download `apigenie--windows-x64.zip` from [Downloads](/downloads), extract it, and add the folder to the `PATH`: it holds `apigenie.exe` and the other executables. Then, in a new terminal: ```powershell apigenie --version ``` npm works on Windows too. ### GitHub Action A step with `mykulyak/api-genie-action@v0` and no `command` installs `apigenie` on the runner and puts it on the `PATH` for the steps after it; `version` pins a release: ```yaml - uses: mykulyak/api-genie-action@v0 - run: apigenie lint openapi.yaml ``` With `command`, the step runs `lint`, `format` or `diff` itself and annotates the pull request ([GitHub Action](/docs/ci/github-action)). The other CI systems install with npm or the archive ([CI](/docs/ci)). The editor runs in the browser with nothing to install: [open it](/tools/editor) on a folder of your API files. ## Pick your starting point - [I have an API](#i-have-an-api): check the description you have, catch breaking changes in pull requests, and publish its documentation. - [I'm building a new API](#im-building-a-new-api): write the contract first, mock it for the client teams, and generate the code of both sides. - [I need my APIs consistent](#i-need-my-apis-consistent): give every API of the organization the same rules and style, and know what APIs there are. ### I have an API Start with what the linter says about your description. It reads OpenAPI, Swagger 2.0, AsyncAPI, Protobuf and GraphQL files, and applies the [recommended ruleset](/docs/linter/openapi) until you configure another. ```sh apigenie lint openapi.yaml ``` Every issue names its line and its rule, and each rule has a page that says why it matters. `--fix` fixes the issues that have a safe fix. Then put the file in a consistent style; `--check` only reports the files it would change. ```sh apigenie format openapi.yaml ``` Before the next change ships, compare it with the version on the main branch. The command exits with status 1 when a change breaks clients. ```sh git show main:openapi.yaml > main.yaml apigenie diff main.yaml openapi.yaml ``` To run both on every pull request, add the [GitHub Action](/docs/ci/github-action) to `.github/workflows/api.yaml`. It shows the issues and the breaking changes on the lines of the pull request. ```yaml on: pull_request jobs: api: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: mykulyak/api-genie-action@v0 with: command: lint files: openapi.yaml - uses: mykulyak/api-genie-action@v0 with: command: diff files: openapi.yaml ``` Finally, a documentation site, with search and Try it out, from the same file. Serve `docs/dist` from any static host. ```sh apigenie-generator docs openapi.yaml -o docs cd docs && npm install && npm run build ``` ### I'm building a new API Describe the API before writing its code. Save this as `openapi.yaml`, or start from a file of your own: ```yaml openapi: 3.1.0 info: title: Notes API version: 0.1.0 servers: - url: http://localhost:4010 paths: /notes: get: operationId: listNotes summary: List the notes responses: "200": description: The notes content: application/json: schema: type: array items: $ref: "#/components/schemas/Note" components: schemas: Note: type: object required: [id, text] properties: id: type: integer format: int64 text: type: string maxLength: 500 ``` Lint it as you write it: the linter knows what a good contract needs, such as descriptions and limits. ```sh apigenie lint openapi.yaml ``` Serve it as a mock, so that client teams can start now. `--dynamic` generates every answer from the schemas; without it, the mock answers with the document's examples first. ```sh apigenie-server openapi.yaml --dynamic curl http://127.0.0.1:4010/notes ``` Generate a TypeScript client and an Express server from the same contract. [The generator](/docs/reference/generator) also writes Java, Go, Python, C# and Elixir. ```sh apigenie-generator client fetch openapi.yaml -o client apigenie-generator server express openapi.yaml -o server ``` Once the real server runs, put the mock in front of it as a validating proxy. Your tests then check that the server keeps the contract. ```sh apigenie-server openapi.yaml --proxy-to http://localhost:8080 --report contract.json --fail-on errors ``` ### I need my APIs consistent Put the rules in an `apigenie.yaml` at the root of the repository. Every command finds it, and editors that read the schema comment complete and check it. ```yaml # yaml-language-server: $schema=https://apigenie.pl/schemas/apigenie-config/latest.json version: '1.0' commands: lint: extends: [recommended] rules: tags-unique: error ``` Lint and format every API of the repository with the same rules and the same style, whatever its standard. ```sh apigenie lint apis/*.yaml proto/*.proto apigenie format apis/*.yaml proto/*.proto ``` List the APIs of the repository, then record their names and owners in the same `apigenie.yaml`. ```sh apigenie-catalog list apigenie-catalog init ``` The [linter rules](/docs/linter) list every rule and ruleset; your own rules are written like [Spectral rules](/docs/reference/cli/lint#custom-rules). ## Next steps - [Configuration](/docs/reference/cli/configuration): every setting of `apigenie.yaml`. - [`apigenie`](/docs/reference/cli): every command and option. - [`apigenie-server`](/docs/reference/server): stubs, scenarios, the dashboard and record and replay. - [Changelog](/changelog): what changed in each release. --- # How-to guides Source: https://apigenie.pl/docs/guides Each guide takes one job from the first command to CI. New to API Genie? Start with the [Quickstart](/docs/quickstart.md). - [Lint and format API descriptions](/docs/guides/lint-and-format-api-descriptions.md): Give every API description of a repository the same rules and the same style, locally and in every pull request. - [Catch breaking changes in CI](/docs/guides/catch-breaking-changes-in-ci.md): Fail the pull request that would break your clients, retire old operations on a schedule, and keep a changelog from git. - [Generate a client and a server](/docs/guides/generate-a-client-and-a-server.md): Generate a typed client and a server from one OpenAPI document, in TypeScript, Java, Go, Python, C# or Elixir, keep your code out of the generated files, and check them in CI. - [Mock and contract-test an API](/docs/guides/mock-and-contract-test-an-api.md): Serve an API from its contract before the server exists, then check the real server against the contract in CI. - [Publish API documentation](/docs/guides/publish-api-documentation.md): Build a documentation site from your API descriptions, translate it, add the changelog of each API, or put a reference into a page of your own. - [Edit an API in forms](/docs/guides/edit-an-api-in-forms.md): Open an OpenAPI or AsyncAPI file in the editor, change it in forms, and review the change like any other. - [Catalog the APIs of a repository](/docs/guides/catalog-the-apis-of-a-repository.md): List every API specification of a repository, give each a stable name and an owner, keep the catalog current in CI, and release a specification as a Git tag. - [Work with AI agents](/docs/guides/work-with-ai-agents.md): Put the linter, the diff and the formatter in a coding agent's loop, so that what it changes in a contract is checked the way a person's change is. ## Coming from another tool Each guide moves a repository from one tool to API Genie: what changes, what stays, and what has no counterpart. - [Migrate from Spectral](/docs/guides/migrate-from-spectral.md): Move a repository from Spectral to apigenie lint: the ruleset, your custom rules and functions, the CI step, and what has no counterpart. - [Migrate from Prism](/docs/guides/migrate-from-prism.md): Move a repository from Prism to apigenie-server: the mock, the Prefer header, request validation, the validation proxy, the CI step, and what has no counterpart. - [Migrate from OpenAPI Generator](/docs/guides/migrate-from-openapi-generator.md): Move a repository from OpenAPI Generator to apigenie-generator: the generators by name, the options, the files you own, the CI step, and what has no counterpart. - [Migrate from Buf](/docs/guides/migrate-from-buf.md): Move the linting, breaking-change checks and formatting of Protobuf files from Buf to apigenie: the rules by name, buf.yaml, the CI step, and what stays with Buf. - [Migrate from Redocly CLI](/docs/guides/migrate-from-redocly.md): Move a repository from Redocly CLI to apigenie: the rules by name, redocly.yaml, configurable rules, decorators as overlays, the bundle, the CI step, and what stays with Redocly. - [Migrate from oasdiff](/docs/guides/migrate-from-oasdiff.md): Move the breaking-change check of a repository from oasdiff to apigenie diff: the checks as rules, the exit status, sunset dates, the formats, the CI step, and what has no counterpart. ## By industry Each guide sets up a repository that follows an industry's own API rules. - [Lint CAMARA APIs](/docs/guides/industry/lint-camara-apis.md): Check the APIs of a CAMARA repository with CAMARA's own rules, locally and in every pull request, without a copy of its ruleset or a Node toolchain. --- # Lint and format API descriptions Source: https://apigenie.pl/docs/guides/lint-and-format-api-descriptions This guide sets up `apigenie lint` and `apigenie format` for a repository of API descriptions: a shared configuration, the first clean run, your own rules, and a check on every pull request. It uses an OpenAPI file, `openapi.yaml`; AsyncAPI, Swagger 2.0, Protobuf and GraphQL files work the same way. You need the CLI installed; the [Quickstart](/docs/quickstart) shows how. ## Run the linter Without configuration the linter applies the `recommended` ruleset: ```sh apigenie lint openapi.yaml ``` ```text 764:6 warning Unused shared component unused-shared-component 781:8 error Schema with integer type does not define proper format schema-format-defined 2 issues (1 error, 1 warning) 0 errors, 1 warning are potentially auto-fixable ``` Each line gives the position, the severity, the message and the rule. Every rule has a page in the [linter rules](/docs/linter) that says what it checks and why. Errors make the command exit with status 1; warnings and hints are reported but don't fail it. Let the linter fix what has a safe fix. The files keep their comments: ```sh apigenie lint --fix openapi.yaml ``` ## Write down your rules Put an `apigenie.yaml` at the root of the repository. Every command finds it in the current directory or a parent, up to the root of the Git repository, so the whole team and CI use the same rules. The first line lets editors that use the YAML language server complete and check the file. ```yaml # yaml-language-server: $schema=https://apigenie.pl/schemas/apigenie-config/latest.json version: '1.0' commands: lint: extends: [recommended] rules: info-defined: off paths-max-count: [error, 30] tags-unique: error ``` `extends` picks the rulesets to start from: `recommended`, `strict`, `all`, or a ruleset of the [catalog](/docs/linter/openapi) such as `privacy`. `rules` changes the severity of a rule (`error`, `warning`, `hint` or `off`), or its severity and options. `apigenie config` prints the settings in effect, and `apigenie config check` checks the file. When a part of a document has a good reason to break a rule, disable the rule there, as close to the problem as you can: ```yaml info: x-apigenie-lint-disable: - contact-defined ``` ## Add a rule of your own House rules that no ruleset has are written the way [Spectral](https://docs.stoplight.io/docs/spectral) rules are: a JSONPath expression selects the values, and a function checks each of them. ```yaml commands: lint: extends: [recommended] rules: operation-summary: description: Operations must have a summary message: "{{property}} is missing at {{path}}" severity: error given: "$.paths[*][get,put,post,delete,patch]" then: field: summary function: truthy ``` The core functions of Spectral are built in, and JavaScript functions written for Spectral mostly work unchanged; see [custom rules](/docs/reference/cli/lint#custom-rules). ## Format the files The formatter puts the files in one style without changing what they mean: indentation, line endings, the order of properties and the YAML styles of values. It writes the files in place: ```sh apigenie format openapi.yaml ``` Its settings go in the same `apigenie.yaml`. Start from the `recommended` preset and override what your team does differently: ```yaml commands: format: extends: [recommended] openapi: newline: crlf style_overrides: - fields: [description] string: literal ``` `--check` writes nothing and exits with status 1 when a file would change, which is what CI needs: ```sh apigenie format --check openapi.yaml ``` ## Check every pull request The [GitHub Action](/docs/ci/github-action) runs both commands and shows the issues as annotations on the lines of the pull request: ```yaml on: pull_request jobs: api: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: mykulyak/api-genie-action@v0 with: command: lint files: api/**/*.yaml - uses: mykulyak/api-genie-action@v0 with: command: format files: api/**/*.yaml ``` On other CI systems, run the commands and read their exit statuses. For dashboards, `lint --formatter` writes SARIF (GitHub code scanning), JUnit, checkstyle, TAP, JSON or HTML; see [formatting results](/docs/reference/cli/lint#formatters). ## Next steps - [Linter rules](/docs/linter): every rule and ruleset of the five linters. - [lint](/docs/reference/cli/lint) and [format](/docs/reference/cli/format): every option and setting. - [Catch breaking changes in CI](/docs/guides/catch-breaking-changes-in-ci): the next check for the same pull requests. --- # Catch breaking changes in CI Source: https://apigenie.pl/docs/guides/catch-breaking-changes-in-ci A breaking change is one that makes a working client fail: a removed operation, a new required parameter, a response field that went away. This guide makes `apigenie diff` stop such changes in pull requests, shows how to remove things without breaking anyone, and builds a changelog from the history of the file. It uses an OpenAPI file, `openapi.yaml`; Swagger 2.0, AsyncAPI, Protobuf and GraphQL files are compared the same way, each by what its clients depend on. You need the CLI installed; the [Quickstart](/docs/quickstart) shows how. ## Compare two versions `apigenie diff` takes the version clients use today and the new one: ```sh git show main:openapi.yaml > main.yaml apigenie diff main.yaml openapi.yaml ``` Every change is rated **breaking**, **non-breaking** or **non-functional** (a description, an example). The command exits with status 1 when any change is breaking, so a script or a CI job can stop there. `--report` picks what it prints: `changelog` (the default), `status` (one word) or `detailed` (every property that changed); `--formatter` writes it as JSON, Markdown, HTML or a format editors understand. Both files must be of the same standard. Here is the report for two versions of a Protobuf file: ```text shop.proto 19 1 breaking Modified message 'Customer' 19 1 non-breaking Removed field 'fax' 25 3 breaking Modified field 'full_name' 25 3 breaking Modified field name ``` ## Check every pull request The [GitHub Action](/docs/ci/github-action) compares each file with its version at the base of the pull request and shows the changes as annotations: ```yaml on: pull_request jobs: api: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: mykulyak/api-genie-action@v0 with: command: diff files: api/openapi.yaml ``` The step fails on breaking changes. Set `base` to compare with another branch or tag, such as the last release, and `fail-on: never` to report without failing. A failing step only blocks the merge once the check is required. In the repository's settings, under *Branches*, add a branch protection rule for the base branch (or a ruleset under *Rules*), turn on *Require status checks to pass before merging* and pick the `api` job. From then on a pull request with a breaking change waits until the change is withdrawn, or its severity is [reconsidered](#decide-what-breaks-your-clients). ## Decide what breaks your clients The `recommended` rules fit most APIs. When yours differ, change them in `apigenie.yaml`: each property of each kind of node takes a severity (`breaking`, `non_breaking`, `non_functional` or `none`), or one each for `add`, `remove` and `modify`. List `recommended` in `extends` to change only some of its rules: ```yaml version: '1.0' commands: diff: extends: [recommended] rules: operation: tags: none ``` [Rules and severities](/docs/reference/cli/diff/rules) lists the `recommended` rules of each standard, with the reason behind each one, and the ways to make a breaking change acceptable; the [diff configuration](/docs/reference/cli/diff#configuration) lists the node types and their properties, and how to set different rules for requests and responses. ## Retire an operation on a schedule Removing an operation is breaking, unless clients were told in advance. Deprecate it with a sunset date first, and ship that: deprecating is not breaking. ```yaml paths: /v1/orders: get: deprecated: true x-sunset: 2027-01-31 ``` Once the date has passed, the `recommended` rules treat the removal as non-breaking, and the same CI job lets it through. `--today` sets the date of the comparison, to try it out before then. For changes bigger than one operation, `apigenie evolve plan` does the planning. It takes the document clients use and the one you want, and writes an expand wave (the new shape next to the old one, deprecated, safe to ship now) and a contract wave (the target, to ship after the sunset): ```sh apigenie evolve plan main.yaml openapi.yaml --out evolve-out/ ``` `evolve` is [experimental](/docs/reference/cli#experimental-commands); see [evolve](/docs/reference/cli/evolve) for its recipes. ## Set the version and keep a changelog `--update-version` writes the smallest `info.version` the changes allow, a new major version for breaking changes, minor for non-breaking and patch for non-functional ones, and keeps the rest of the file as it is: ```sh apigenie diff main.yaml openapi.yaml --update-version ``` `apigenie changelog` compares the committed versions of a file and describes what changed for clients, per commit or per release tag: ```sh apigenie changelog openapi.yaml --revisions tags --tag-pattern 'v*' --unreleased ``` ## Next steps - [diff](/docs/reference/cli/diff): every option, the rules of each standard and the JSON report. - [Rules and severities](/docs/reference/cli/diff/rules): why a change is breaking, and how to accept it. - [changelog](/docs/reference/cli/changelog): revisions, tags and output formats. - [Publish API documentation](/docs/guides/publish-api-documentation): the changelog of each API on its documentation site. --- # Generate a client and a server Source: https://apigenie.pl/docs/guides/generate-a-client-and-a-server This guide generates both sides of an API from its OpenAPI document, `openapi.yaml`: a TypeScript client for the Fetch API and an Express server, then the same pair in [Java, Go, Python, C# and Elixir](#start-in-your-language). The steps work for the other targets of [`apigenie-generator`](/docs/reference/generator) too, and for AsyncAPI, GraphQL and Protobuf documents. You need the CLI installed; the [Quickstart](/docs/quickstart) shows how. Lint the document first ([Lint and format API descriptions](/docs/guides/lint-and-format-api-descriptions)): a clean contract gives cleaner code. ## Generate the client ```sh apigenie-generator client fetch openapi.yaml -o client --package-name shipping-client ``` The output is an npm package with no runtime dependencies: requests go through the global `fetch()`, so the client runs in browsers and in Node.js 18 or later. Each operation is an `async` function named after its `operationId`, with its parameters and its result typed from the document: ```ts import { configure, ApiError, listShipments, getShipment } from "shipping-client"; configure({ baseUrl: "https://api.example.com/v2", auth: { apiKey: "ce_live_123" }, }); try { const page = await listShipments({ status: ["in_transit"], limit: 20 }); const shipment = await getShipment({ shipmentId: "shp_01J9Z" }); } catch (error) { if (error instanceof ApiError) { console.error(error.status, error.body); } } ``` To compile the client as part of your own project instead of as a package, set `layout: sources` for `client_fetch` in the configuration (see [Configure the generators](#configure-the-generators) below): the generator then writes only the sources. ## Generate the server ```sh apigenie-generator server express openapi.yaml -o server --package-name shipping-server ``` The generator writes typed handler interfaces and a router that decodes and validates every request. Your code implements the handlers in files of its own, so regenerating never overwrites it: ```ts import express from "express"; import { BASE_PATH, createRouter, HttpError, type ShipmentsHandlers } from "shipping-server"; const shipments: Partial = { async getShipment(request) { const shipment = await db.shipments.find(request.params.shipmentId); if (shipment === undefined) { throw new HttpError(404, "No such shipment"); } return { status: 200, body: shipment }; }, }; const app = express(); app.use(BASE_PATH, createRouter({ shipments })); app.listen(8080); ``` Operations are grouped by their first tag (`ShipmentsHandlers`), and the status, body and headers a handler returns are typed per status from the document. A change to the contract that the handlers don't follow is a compile error. ## Start in your language Every language has the same pair: a client that needs the language's usual toolchain and little else, and a server that validates every request and leaves the implementation to files it never overwrites. The commands below generate from the same `openapi.yaml`, whose title is Shipping API, whose operations are tagged `shipments`, and whose security scheme is an API key named `apiKey`; `--package-name` names the package where the language has one. Each target's page lists its options and what it generates. ### Java ```sh apigenie-generator client java openapi.yaml -o client-java --package-name shipping apigenie-generator server spring openapi.yaml -o server-java --package-name shipping ``` The client is a Maven project for Java 17 or later, with `ApiClient` on Spring's `RestClient` (`--library` picks `resttemplate`, `feign` or `http-interface` instead) and one class per tag: ```java ApiClient client = new ApiClient(); client.setBasePath("https://api.example.com/v2"); client.setApiKey("ce_live_123"); ShipmentsApi shipments = new ShipmentsApi(client); Shipment shipment = shipments.getShipment("shp_01J9Z"); ResponseEntity> page = shipments.listShipmentsWithHttpInfo(List.of(ShipmentStatus.IN_TRANSIT), 20); ``` The server is a Spring Boot 3 project with the layout and the options of openapi-generator's `spring` generator: an interface per tag (`ShipmentsApi`) and a controller implementing it (`ShipmentsApiController`), which is written only when it is missing, so the implementation goes there and survives regeneration. See [client java](/docs/reference/generator/client-java) and [server spring](/docs/reference/generator/server-spring). ### Go ```sh apigenie-generator client go openapi.yaml -o client-go --package-name shipping apigenie-generator server go openapi.yaml -o server-go --package-name shipping -p layout=module ``` Both use the standard library only. The client has a `NewClient` with an option per server and security scheme, and a method per operation whose response has a typed field per status and media type: ```go client, err := shipping.NewClient( shipping.WithBaseURL("https://api.example.com/v2"), shipping.WithAPIKey(os.Getenv("API_KEY")), ) if err != nil { return err } res, err := client.GetShipment(ctx, "shp_01J9Z") if err != nil { return err } fmt.Println(res.JSON200.Status) ``` The server follows oapi-codegen's names: implement `ServerInterface`, whose methods get the bound and validated parameters, or `StrictServerInterface`, whose methods return typed responses such as `GetShipment200JSONResponse`, and mount it with `HandlerWithOptions` on an `http.ServeMux`. `-p layout=module` writes a `go.mod`; without it the output is a package of your module. See [client go](/docs/reference/generator/client-go) and [server go](/docs/reference/generator/server-go). ### Python ```sh apigenie-generator client python openapi.yaml -o client-python --package-name shipping_client apigenie-generator server fastapi openapi.yaml -o server-python --package-name shipping ``` The client needs Python 3.10 or later, pydantic 2.11 or later and httpx, and has a resource per tag with a method per operation, on `Client` and on `AsyncClient`: ```python from shipping_client import Client, NotFoundError with Client(api_key="ce_live_123") as client: page = client.shipments.list_shipments(status=["in_transit"], limit=20) try: shipment = client.shipments.get_shipment("shp_01J9Z") except NotFoundError as error: print(error.body) ``` The server has the layout and the options of openapi-generator's `python-fastapi` generator, for FastAPI 0.115 or later: the routes validate the requests and call the methods of `BaseShipmentsApi`, which answer 501 until a subclass in the `impl` package implements them. `uvicorn shipping.main:app --reload --port 8080` runs it. See [client python](/docs/reference/generator/client-python) and [server fastapi](/docs/reference/generator/server-fastapi). ### C# ```sh apigenie-generator client csharp openapi.yaml -o client-csharp apigenie-generator server aspnet openapi.yaml -o server-csharp ``` The names come from the document's title: the client is a `net8.0` class library in the `Shipping.Client` namespace, referencing only `Microsoft.Extensions.Http`, with a typed client per tag registered for dependency injection: ```csharp services.AddShippingClient(options => { options.BaseUrl = new Uri("https://api.example.com/v2"); options.ApiKey = ApiCredential.Static(configuration["Shipping:ApiKey"]!); }); // inject ShippingClient, or the client of a tag, IShipmentsClient var shipment = await client.Shipments.GetShipmentAsync("shp_01J9Z", cancellationToken); ``` The server targets .NET 8 with the shared framework alone: an interface per tag (`IShipmentsApi`) whose methods return the declared responses as `Results, ...>`, so the compiler accepts only those, its implementation in `Apis/ShipmentsApi.cs` and the host in `Program.cs`, both written only when missing, and `app.MapShippingApi()` to map the endpoints. `dotnet run` starts it. See [client csharp](/docs/reference/generator/client-csharp) and [server aspnet](/docs/reference/generator/server-aspnet). ### Elixir ```sh apigenie-generator client elixir openapi.yaml -o client-elixir --package-name shipping apigenie-generator server phoenix openapi.yaml -o server-elixir --package-name shipping ``` Both are Mix projects for Elixir 1.18 or later. The client depends on Req, and has a module per tag with a function per operation, returning `{:ok, value}` or `{:error, error}`, and a `!` variant that raises: ```elixir client = Shipping.new(base_url: "https://api.example.com/v2", auth: [api_key: "ce_live_123"]) {:ok, shipment} = Shipping.Api.Shipments.get_shipment(client, shipment_id: "shp_01J9Z") shipment = Shipping.Api.Shipments.get_shipment!(client, shipment_id: "shp_01J9Z") ``` The server is a Phoenix 1.7 application whose router matches the operations, checks the credentials and decodes the parameters and bodies before calling a behaviour per tag, `ShippingWeb.Api.Shipments`. Implement it in a module of your own, name that module in `config/config.exs` (`config :shipping, ShippingWeb.Api.Shipments, impl: MyApp.Shipments`), and run `mix phx.server`; operations without an implementation answer 501. See [client elixir](/docs/reference/generator/client-elixir) and [server phoenix](/docs/reference/generator/server-phoenix). ## Configure the generators Generator settings go in the `commands.generate` section of `apigenie.yaml`, one entry per target, so the command lines stay short and the settings are reviewed like code ([how the file is found and read](/docs/concepts/where-the-configuration-is-found#the-generators)). Here the client's imports suit a bundler, and an overlay adjusts the document for the server: ```yaml version: '1.0' commands: generate: client_fetch: import_extension: '' server_express: overlay: - overlays/express.overlay.yaml ``` Each target's page lists its settings and the vendor extensions it reads, such as [client fetch](/docs/reference/generator/client-fetch) and [server express](/docs/reference/generator/server-express). Extensions that matter to one generator only can live in an [OpenAPI Overlay](/docs/reference/cli/overlay) of that generator, listed under `overlay` or given with `--overlay`, instead of in the API description. ## Check the generated code in CI Generate into the repository and commit the output with the description, so that reviewers see the change to the API and its effect on the code in the same diff. Give every option on the command line or in `apigenie.yaml`, so that CI runs exactly what you run. Then let every pull request check that the generated files still match the description. `--check` runs the generator without writing anything, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). After a value is added to an enum of the document, for example a `t` unit in the `Weight` schema of the [Carpet Express document](/samples/carpet-express.openapi-31.yaml), the check fails until you regenerate: ```sh apigenie-generator client fetch openapi.yaml -o client --package-name shipping-client --check ``` ```text client/src/types.ts 1 generated file(s) would change and 0 would be created. ``` Run the same command without `--check`, review the diff and commit it. When the generated code is up to date, `--check` lists no file and exits with 0. Files a target writes only when they are missing, such as the `README.md` of `server express`, belong to you once they exist. `--check` leaves them out. Files the generator doesn't write at all are not compared either, so a file left behind by a removed operation stays until you delete it. On GitHub, the [API Genie Action](/docs/ci/github-action) without a `command` installs the CLI and puts `apigenie-generator` on the `PATH`. A step after it runs the check for each target and fails the job when any of them finds a difference: ```yaml on: pull_request jobs: generated: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: mykulyak/api-genie-action@v0 with: version: 0.12.0 - name: Generated code matches the API description run: | status=0 apigenie-generator client fetch openapi.yaml -o client --package-name shipping-client --check || status=1 apigenie-generator server express openapi.yaml -o server --package-name shipping-server --check || status=1 exit $status ``` The generated files hold no date and no path of your machine, so the check gives the same result on any Linux or macOS runner. A new generator version can change them: pin the version in CI and in your package manager, and regenerate in the pull request that upgrades it. Other CI systems run the same commands once the CLI is installed ([Installing the CLI in a job](/docs/ci#installing-the-cli-in-a-job)); the npm package installs `apigenie-generator` next to `apigenie`. Once the server runs, check that it keeps the contract with a validating proxy: [Mock and contract-test an API](/docs/guides/mock-and-contract-test-an-api). ## Next steps - [`apigenie-generator`](/docs/reference/generator): every target, by standard. - [Overlays](/docs/reference/generator#overlays): settings outside the API description. - [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date): `--check` and its output. - [GitHub Action](/docs/ci/github-action): the inputs of the Action. - [Generate code](/use-cases/code-generation): what the generator covers. --- # Mock and contract-test an API Source: https://apigenie.pl/docs/guides/mock-and-contract-test-an-api A contract is only useful while both sides keep it. This guide serves an API from its OpenAPI document, `openapi.yaml`, so that client teams can start before the server exists, and then checks the real server's traffic against the same document, locally and in CI. `apigenie-server` does the same for AsyncAPI documents (WebSocket, HTTP and MQTT), `.proto` files (gRPC) and GraphQL schemas; see the [server reference](/docs/reference/server). You need the CLI installed; the [Quickstart](/docs/quickstart) shows how. ## Serve a mock ```sh apigenie-server openapi.yaml ``` ```text Listening on http://127.0.0.1:4010/v1 (spec: openapi.yaml, 12 operations) Admin API: http://127.0.0.1:4010/__apigenie Dashboard: http://127.0.0.1:4010/__apigenie/ui ``` The mock serves the paths of the document under the path of its first server (`/v1` here), checks every request against the document, and answers with the document's examples. Operations without examples get a body generated from their schemas; `--dynamic` generates every answer. `--watch` reloads the mock when the document changes, so it follows the contract as you write it. Open the dashboard to see each request, what answered it and what was wrong with it. ## Ask for the answers you need A client has to handle more than the happy path. The `Prefer` header, or a query parameter, picks the answer of one request: ```sh curl http://127.0.0.1:4010/v1/orders -H 'Prefer: code=404' curl http://127.0.0.1:4010/v1/orders -H 'Prefer: example=empty' curl http://127.0.0.1:4010/v1/orders -H 'Prefer: delay=1500' ``` For answers that should hold for a while, such as an outage of one service, define scenarios in the document or in the configuration, and switch them on with `--scenario` or in the dashboard: ```yaml paths: /orders: get: x-apigenie-mock: scenarios: empty: {body: []} broken: {status: 500, drop: {probability: 0.5, mode: reset}} ``` `--latency`, `--jitter` and `--drop-rate` make every answer slow or unreliable, and `--seed` repeats the same run. ## Check the real server Once the server runs, put `apigenie-server` in front of it with `--proxy-to`. Every request goes to the real server, and the request and the server's response are both checked against the document: ```sh apigenie-server openapi.yaml --proxy-to http://localhost:8080 ``` Point your tests, your front end or a load test at the proxy instead of the server, and their traffic becomes a contract test. Each response carries the problems found in its exchange in the `X-Apigenie-Mock-Violations` headers, and the dashboard's Contract screen shows the coverage and the violations by check. To send the requests yourself rather than through your tests, `apigenie test` runs `.http` files, or one generated request per operation, against the server with the same checks: ```sh apigenie test --spec openapi.yaml --generate --base-url http://localhost:8080 ``` ## Fail CI when the contract breaks In CI, start the proxy, run the test suite through it, and stop it. On stopping it writes the report and exits with status 5 when the contract failed: ```sh apigenie-server openapi.yaml --proxy-to http://localhost:8080 --port 4010 \ --report contract.json --report-junit contract.xml --fail-on errors --min-coverage 80 & API_URL=http://localhost:4010 npm test curl -X POST http://localhost:4010/__apigenie/shutdown wait $! ``` `--fail-on errors` fails on any error-level violation, and `--min-coverage 80` when the tests leave more than a fifth of the document untested. Most CI systems show the JUnit report, one test case per operation, next to the other test results. ## Record once, replay in tests Integration tests that call other services are slow and flaky. `--record DIR` writes every exchange of a session to a directory, and `--replay DIR` answers from it later, so the tests run without the real services: ```sh apigenie-server openapi.yaml --proxy-to https://api.example.com --record sessions/checkout apigenie-server openapi.yaml --replay sessions/checkout ``` See [session recording](/docs/reference/server/recording#session-recording) for what is recorded and how secrets are kept out of the files. ## Next steps - [Server reference](/docs/reference/server): stubs, scripts, the document store, several services and TLS. - [`apigenie test`](/docs/reference/cli/test): `.http` files, assertions and scripts. - [Mock and test](/use-cases/mock-and-test): what the server covers. --- # Publish API documentation Source: https://apigenie.pl/docs/guides/publish-api-documentation Documentation written by hand falls behind the API it describes. Built from the contract, it changes when the API does. This guide builds a documentation site from an OpenAPI document and an AsyncAPI one, adds translations and changelogs, publishes it, and shows how to put a reference into an existing page instead. Swagger 2.0, GraphQL and Protobuf files work the same way. You need the CLI and Node.js installed; the [Quickstart](/docs/quickstart) shows how. ## Build a site Use your own files, or download the Carpet Express [OpenAPI definition](/samples/carpet-express.openapi-31.yaml) as `openapi.yaml` and [AsyncAPI definition](/samples/carpet-express.asyncapi.yaml) as `events.asyncapi.yaml`. These describe a fictional service; their sample endpoints aren't live. ```sh apigenie-generator docs openapi.yaml events.asyncapi.yaml -o docs cd docs npm install npm run build ``` The first command writes a *docs bundle* into `docs/`: the resolved documents and a manifest, with an npm project that depends on the [doc components](/tools/doc-components). The build renders it into `docs/dist/`: a page per API, operation and schema, with navigation, search and Try it out. Every page is prerendered, so it reads without JavaScript and search engines see all of it. Each page also has a Markdown copy next to it (`operation/getPet.md` beside `operation/getPet/`), indexed in `llms.txt` and collected in `llms-full.txt` at the root of the site, for coding agents and for pasting into a chat. `npm run build -- --no-markdown` leaves them out. Serve `docs/dist/` from any static host. To host the site under a path of your domain, pass the path and the origin to the build, which also writes them into the sitemap: ```sh npm run build -- --base /docs/ --origin https://example.com ``` ## Describe the site in the configuration Instead of listing the files on the command line, list them in `apigenie.yaml`, with a title for the site and for each API: ```yaml version: '1.0' commands: generate: docs: title: Acme APIs documents: - file: api/openapi.yaml id: shop title: Shop API - file: api/events.asyncapi.yaml id: events ``` ```sh apigenie-generator docs -o docs ``` The `id` of a document is its path on the site, so links to it survive when the file moves. ## Add the changelog of each API With `--changelog`, each API gets a page of the changes its consumers care about, built from the git history of its file as [`apigenie changelog`](/docs/reference/cli/changelog) builds it. Configure the revisions to list releases instead of commits: ```yaml commands: generate: docs: changelog: revisions: tags tag_pattern: 'v*' unreleased: true ``` ## Translate the documentation `apigenie i18n` extracts the texts of a document for translators, and the generator builds a copy of the site per locale, with a locale switcher: ```sh apigenie i18n extract openapi.yaml --output i18n-en.json # translators turn i18n-en.json into i18n-pl.json, keeping the keys apigenie i18n check openapi.yaml --translations i18n-pl.json apigenie-generator docs openapi.yaml --i18n pl=i18n-pl.json -o docs ``` `i18n check` fails until every text is translated, which suits CI. When the document changes, `i18n sync` keeps the translations of the texts that didn't change and lists the new ones; see [i18n](/docs/reference/cli/i18n). ## Or put a reference into your own page When the API documentation belongs inside a portal or a product site, use the doc components directly. They are standard custom elements, so they work in plain HTML, a CMS or any framework: ```sh npm install @mykulyak/apigenie-docs ``` ```html ``` `` renders a whole reference. For a page of your own design, use its parts: ``, ``, `` and the others, inside an `` that loads the document once. The [doc components reference](/docs/reference/doc-components) lists every element with its attributes, events, slots and CSS parts, and their look follows CSS custom properties and `::part()` ([Theming](/docs/reference/doc-components/theming)). ## Next steps - [`apigenie-generator docs`](/docs/reference/generator/docs): every option and setting, and the format of the bundle. - [Doc components reference](/docs/reference/doc-components): every element, its attributes, events and slots, and how to theme them. - [Publish API docs](/use-cases/api-docs): what the documentation covers. --- # Edit an API in forms Source: https://apigenie.pl/docs/guides/edit-an-api-in-forms Not everyone who shapes an API wants to write the YAML of its standard. The API Genie editor shows OpenAPI 3.0, OpenAPI 3.1 and AsyncAPI 3.0 documents as forms, and changes only the lines an edit has to, so a change made in a form reviews like one made by hand. This guide edits an API in the web editor, which runs in the browser with nothing to install. ## Open a spec To try the editor without using your own API, download the [Carpet Express OpenAPI 3.1 example](/samples/carpet-express.openapi-31.yaml). Open [the web editor](/editor/) and choose *Open spec…* on the file, such as the `openapi.yaml` of a clone of the repository. The editor reads the files its `$ref`s name with it. In Chrome and Edge, choose *Allow access to their folder…* under the file list to let it read them, and the changes are saved in place. In other browsers, drop the spec on the page with the files it refers to, and the changes are saved as downloads. The spec is the file you edit. The files it refers to are shown read-only, so that a change meant for one API doesn't change every API that shares them; *Edit this file* on one lets you change it. The editor works on the files on your computer. There is no account and no server, and nothing leaves your machine unless you send a request with Try it out. ## Find your way around - The **API tree** on the left shows the operations, channels, schemas and other parts of the API, with search, filters and a badge where a part has problems. - The **form** in the middle edits the selected part. What a form doesn't model is shown as raw YAML in its Raw section, never dropped. - The **Code** tab shows the text of the file, and follows the selection. - The **Preview** shows the documentation of the selected part as readers will see it, with Try it out for OpenAPI operations. References are followed into every file the spec refers to. Renaming or moving a schema, extracting a part into a component or inlining it updates the files that refer to it. ## Fix the problems as you go The editor checks the document as you type: the problems appear under the fields they belong to and in the tree. Besides the standard's own checks, it applies the [linter rules](/docs/linter), with a quick fix where a rule has a safe one. The linters read `commands.lint` of the project's `apigenie.yaml`, and `commands.lint.asyncapi` for AsyncAPI documents. The editor takes the file nearest to the spec, as `apigenie lint` finds it when run in the spec's folder ([where the file is found](/docs/concepts/where-the-configuration-is-found)). The editor reads only what it opened the spec from: the spec's folder in the desktop app, the files you dropped with the spec in a browser, and the workspace folder in VS Code. *Allow access to their folder…*, where the editor offers it, widens that to a folder above the spec. In VS Code an edit to the configuration file applies as you type, and so does a file you add or delete; in the desktop app and a browser a change applies when you open the spec again. [The editor's hosts](/docs/reference/editor/hosts) gives the details for each host. When the editor finds no file, the default rules apply, and nothing says so. Custom JavaScript functions don't run in the editor yet. The rules that call them are left out, and the bottom panel's Problems tab says so under the configuration file. A configuration the linter refuses is an error there, and the editor applies the default rules, while `apigenie lint` stops with exit status 2. The editor checks only `version` and the lint section: run `apigenie config check apigenie.yaml` ([config](/docs/reference/cli/config)) to check the whole file against its schema. ## Review the change before you save The **Changes** panel lists the API changes since the last save, each rated breaking, non-breaking or non-functional as [`apigenie diff`](/docs/reference/cli/diff) rates them, and shows the text diff. Save when the change is what you meant; the unsaved files are counted in the toolbar. Comments, key order, anchors and quoting stay as they were. Opening and saving a file without an edit gives back the same bytes, so the pull request shows only what you changed. ## Bring in older documents *Import* converts Swagger 2.0 documents, AsyncAPI 2.x documents and Postman collections, and shows the conversion as a diff before it is written. ## Other hosts The same editor runs on the desktop, with a Git panel and a mock server started from the toolbar, and in VS Code, where *Open with API Genie Editor* opens any OpenAPI or AsyncAPI file. Since 0.12.0, each CLI release on [GitHub](https://github.com/mykulyak/api-genie/releases) carries the desktop editor's installers; the extension ships with 1.0.0. [The editor's hosts](/docs/reference/editor/hosts) lists what each host offers. ## Next steps - [Editor](/tools/editor): what the editor does. - [Lint and format API descriptions](/docs/guides/lint-and-format-api-descriptions): the rules the editor applies. - [Catch breaking changes in CI](/docs/guides/catch-breaking-changes-in-ci): the check that follows the pull request. --- # Catalog the APIs of a repository Source: https://apigenie.pl/docs/guides/catalog-the-apis-of-a-repository A repository with more than a few APIs raises questions nobody can answer quickly: which APIs are there, which version is which, and who to ask about each. `apigenie-catalog` answers them from the repository itself, with nothing to host and nothing to upload. This guide lists the APIs of a repository, records their names and owners, keeps the catalog current and releases a specification as a Git tag. You need the CLI installed; the [Quickstart](/docs/quickstart) shows how. `apigenie-catalog` is [experimental](/docs/reference/cli#experimental-commands): pinned consumers and catalogs that span several repositories will add options. ## List the specifications Run it anywhere in the repository; no configuration is needed: ```sh apigenie-catalog list ``` ```text NAME FORMAT VERSION PATH COMMIT order-events AsyncAPI 3.0.0 2.0.0 apis/events.json 96175d8 2026-10-12 orders-api OpenAPI 3.1.0 1.2.0 apis/orders/openapi.yaml 4d0c2e1 2026-10-14 schema GraphQL - graphql/schema.graphql 96175d8 2026-10-12 acme-pricing-v1 Protobuf proto3 - proto/pricing.proto 96175d8 2026-10-12 ``` It looks at the files Git tracks, so build output and ignored files stay out, and finds OpenAPI, AsyncAPI and Swagger documents by their content, every `.proto` file, and GraphQL files with type definitions. Each row has a name derived from the specification (its title, its Protobuf package or its file name), its format and version, its path and its last commit. Give a directory to list part of the repository: `apigenie-catalog list apis/`. ## Give each API a name and an owner A derived name changes when the title or the file does, and an owner can't be derived at all. `apigenie-catalog init` writes a `catalog` section into `apigenie.yaml`, with one entry per specification: ```sh apigenie-catalog init ``` ```yaml catalog: specs: - name: order-events path: apis/events.json owner: null - name: orders-api path: apis/orders/openapi.yaml owner: null ``` Fill in the owners, and change a name where the derived one isn't right. From then on the name stays when the file moves: change the `path` and keep the `name`. Commit the file: a new owner is now a change that is reviewed like any other. Leave files out of the catalog, such as test fixtures, with patterns under `catalog.exclude`; see [the catalog section](/docs/reference/cli/configuration#catalog) of the configuration. ## Keep it current Run `init` again after adding specifications. New ones are added, the entries you edited stay as they are, and the entries whose files are gone are reported; `--prune` removes them: ```text $ apigenie-catalog init Updated /home/me/specs/apigenie.yaml: 2 added, 4 kept, 1 not found added apis/billing.yaml added apis/orders-v2.yaml not found legacy/swagger.yaml Remove the entries of the files that are gone with --prune. ``` To catch a specification added without an entry, let CI run `init --dry-run`, which prints the file instead of writing it, and compare the result with the committed `apigenie.yaml`. ## Release a specification `apigenie-catalog release` (since 0.12.0) makes a release a Git tag, so everyone who clones the repository has it. Bump `info.version` in the pull request that changes the API, merge it, then tag: ```text $ apigenie-catalog release orders-api 1.1.0 --push Tagged orders-api-1.1.0 at b2e21b5 Release 1.1.0 of the Orders API (previous release: 1.1.0-rc.1, tag orders-api-1.1.0-rc.1) Pushed orders-api-1.1.0 to origin ``` The command refuses to tag when the version is not above the latest release, the file has changes that are not committed, or its `info.version` is not `1.1.0`. The tag and the `info.version` of an OpenAPI, AsyncAPI or Swagger document then name the same version. `apigenie-catalog versions` lists the releases: ```text $ apigenie-catalog versions orders-api VERSION TAG COMMIT 1.1.0 orders-api-1.1.0 b2e21b5 2026-11-02 1.1.0-rc.1 orders-api-1.1.0-rc.1 c121c1b 2026-10-28 1.0.0 orders-api-1.0.0 12e9f3d 2026-10-12 ``` The tags are revisions, so `apigenie changelog apis/orders/openapi.yaml --from orders-api-1.0.0 --to orders-api-1.1.0` lists the changes between two releases ([changelog](/docs/reference/cli/changelog)). Teams that tag `orders-api/v1.4.0` set `catalog.tags.pattern` to `{name}/v{version}`. Mark an API that is on its way out in the catalog section, so that the catalog says so and a retired one can't be released by mistake: ```yaml catalog: specs: - name: legacy-billing path: apis/legacy/billing.yaml owner: team-finance lifecycle: deprecated sunset: 2027-03-31 ``` ```text $ apigenie-catalog list NAME FORMAT VERSION OWNER LIFECYCLE PATH COMMIT legacy-billing OpenAPI 3.0.3 4.2.0 team-finance deprecated (2027-03-31) apis/legacy/billing.yaml a510f31 2026-11-02 orders-api OpenAPI 3.1.0 1.1.0 team-commerce active apis/orders/openapi.yaml b2e21b5 2026-11-02 acme-pricing-v1 Protobuf proto3 - - active proto/pricing.proto 12e9f3d 2026-10-12 ``` Once `lifecycle: retired` replaces `deprecated`, `apigenie-catalog release legacy-billing 4.2.0` prints `legacy-billing is retired (catalog section); a retired specification is not released` and `legacy-billing 4.2.0 is not released` on the standard error, and exits with status 2. ## Use the catalog in your tools `--json` prints the catalog with a [published schema](https://apigenie.pl/schemas/apigenie-catalog-report.json): the name, title, format, version, path, owner and lifecycle of each specification, its last commit, and whether the catalog section lists it. Scripts can lint or diff every API of the repository from it, or feed a dashboard of owners: ```sh apigenie-catalog list --json > catalog.json ``` ## Next steps - [`apigenie-catalog`](/docs/reference/catalog): every option and the JSON report. - [changelog](/docs/reference/cli/changelog): the history of each specification from git. - [Lint and format API descriptions](/docs/guides/lint-and-format-api-descriptions): the same rules for every API the catalog lists. --- # Work with AI agents Source: https://apigenie.pl/docs/guides/work-with-ai-agents A coding agent edits an API description the way it edits code: quickly, and without the context a reviewer has. The checks that protect a repository from a hurried person protect it from an agent too, provided the agent can run them and read their answers. This guide puts `apigenie lint`, `apigenie format` and `apigenie diff` in an agent's loop, tells the agent about them, and keeps the same checks in CI for the pull request the agent opens. You need the CLI installed where the agent runs; the [Quickstart](/docs/quickstart) shows how. The commands below work with OpenAPI, Swagger 2.0, AsyncAPI, Protobuf and GraphQL files. ## What an agent needs from a tool - **An exit status that means one thing.** The binaries share [one table](/docs/reference/cli#exit-status): 0 is success, 1 is findings (lint errors, breaking changes, files to reformat), 2 is a usage or input error. The 1.0 compatibility promise freezes it for `apigenie`, `apigenie-generator` and `apigenie-server`; `apigenie-catalog` and `apigenie-mcp` are experimental. - **Output it can parse.** Since 0.12.0 every command takes `--json` and then prints one JSON document: its report (`lint`, `diff`, `format`, `test`, `apigenie-catalog list`, ...) or the status of the run, with the exit status and the messages ([JSON output](/docs/reference/cli#json-output)). Each has a `formatVersion` and a published schema. - **Settings in a file it can check.** `apigenie.yaml` is validated against [its JSON Schema](/docs/reference/cli/configuration) before any command reads it, so a wrong key is an error with a line, not a silently ignored setting. - **Documentation it can read.** Guides, reference pages and linter rules have Markdown copies, indexed in [`llms.txt`](/llms.txt) and collected in [`llms-full.txt`](/llms-full.txt). So do the sites of your own APIs: the build of [`apigenie-generator docs`](/docs/guides/publish-api-documentation) writes a Markdown copy of each page with its own `llms.txt`, which an agent that calls your API can read. ## Tell the agent about the commands Most agents read an instructions file at the root of the repository: `AGENTS.md`, `CLAUDE.md`, `.github/copilot-instructions.md`, `.cursor/rules` or the equivalent of your tool. [`apigenie init`](/docs/reference/cli/init) adds this section to it (`AGENTS.md` unless you name another with `--agents-file`) and writes `apigenie.yaml` with the rules of the descriptions it finds. Or add the section by hand. Either way, say in its first sentence where your descriptions are: ```markdown ## API descriptions This repository keeps its API descriptions (OpenAPI, Swagger 2.0, AsyncAPI, GraphQL, Protobuf) under version control and checks them with the API Genie CLI (`apigenie`; install it with `npm install -g @mykulyak/api-genie`). The project's rules are in `apigenie.yaml`. After changing a description: 1. `apigenie lint --fix --json `, then fix what is left by hand and lint again. The JSON lists every issue with its line, rule and message; the command exits with 1 while errors remain. Fix the issues your change introduced, not the ones that were there before. 2. `apigenie format `. 3. Compare with the base branch: `git show origin/main: > /tmp/base` and `apigenie diff --json /tmp/base `. Exit status 1 means a breaking change: say so in the pull request and propose a compatible alternative. Do not remove the change, or weaken `apigenie.yaml` (turn a rule off, lower a severity), to make a check pass without asking. Every command takes `--json` and then prints one JSON document: its report, or `{"exitStatus", "messages", "output"}`. Exit statuses: 0 success, 1 findings, 2 a usage or input error. `apigenie --help` lists the options; generate code with `apigenie-generator --help`, mock with `apigenie-server `. ``` The sentence about weakening the checks matters: an agent told only to make a check pass will make it pass. ## The loop Each step prints something the agent can act on, and exits with a status it can test. ```sh apigenie lint apis/orders.yaml --fix --json > lint.json; echo $? ``` ```text 1 ``` With `--json`, each remaining issue has its file, line, column, severity, rule and message, and each rule links its page under [the linter rules](/docs/linter), which says why the rule exists and what a fix looks like. `--fix` has already applied the safe fixes and kept the comments of the file. ```sh apigenie format apis/orders.yaml ``` The formatter gives the same file for the same input, whoever ran it, so a formatted file is a small diff: only the lines the agent meant to change. The first formatting pass can change many lines; commit it on its own, before the API changes, so reviewers can tell the two apart. ```sh git show main:apis/orders.yaml > /tmp/orders.main.yaml apigenie diff /tmp/orders.main.yaml apis/orders.yaml --report status --json ``` ```json { "formatVersion": 1, "status": "non-breaking" } ``` `--report status` is the one-word answer; `--report changelog` lists every change with its rating, and `--report detailed` every property that changed, for the pull request's description. ## Keep the same checks in CI The agent's checks are advisory until CI runs them on the pull request. The [GitHub Action](/docs/ci/github-action) lints the changed files and compares each with the base of the pull request, and shows the issues on the changed lines, where the reviewer and the agent both see them. [Catch breaking changes in CI](/docs/guides/catch-breaking-changes-in-ci) sets it up. ## Serve the checks to the agent over MCP Agents that reach tools through the Model Context Protocol can call the checks directly. These are desktop and IDE clients, or an agent whose every shell command needs an approval. [`apigenie-mcp`](/docs/reference/cli/mcp) (since 0.12.0), installed with the CLI, serves `lint`, `check_breaking_changes`, `changelog`, `format`, `bundle` and `describe`. `lint` and `check_breaking_changes` run `apigenie` with the repository's `apigenie.yaml`. Their result starts with a sentence that says whether the check passed. In Claude Code, add it with: ```sh claude mcp add api-genie -- apigenie-mcp ``` Other clients take the command `apigenie-mcp` in their own MCP settings ([Usage](/docs/reference/cli/mcp#usage)). `apigenie-mcp` writes nothing unless started with `--allow-write` (`claude mcp add api-genie -- apigenie-mcp --allow-write`), which lets `lint` fix, `format` rewrite and `bundle` write files. Without it, `format` returns the formatted text for the agent to apply. It is [experimental](/docs/reference/cli#experimental-commands). ## Check the code the agent generates When an agent writes the server too, put `apigenie-server` in front of it as a validating proxy: every response is checked against the contract, and the run fails on a violation: ```sh apigenie-server apis/orders.yaml --proxy-to http://localhost:8080 --port 4010 \ --report contract.json --fail-on errors & API_URL=http://localhost:4010 npm test curl -X POST http://localhost:4010/__apigenie/shutdown wait $! ``` [Mock and contract-test an API](/docs/guides/mock-and-contract-test-an-api) explains the report and the coverage gate. ## Give an agent the API as tools `apigenie-generator server mcp` writes an MCP server with a tool per operation of an OpenAPI document, so an agent can call the API through the Model Context Protocol instead of writing HTTP by hand. It is [experimental](/docs/reference/cli#experimental-commands): MCP and its SDK are still moving, and the tool names and result shapes can change with them. ```sh apigenie-generator server mcp apis/orders.yaml -o orders-mcp ``` ## Next steps - [Lint and format API descriptions](/docs/guides/lint-and-format-api-descriptions): the rulesets and your own rules. - [Exit statuses](/docs/reference/cli#exit-status) and [the compatibility promise](/docs/reference/cli/compatibility): what a script can rely on. - [`llms.txt`](/llms.txt): the documentation, for the agent to read. --- # Migrate from Spectral Source: https://apigenie.pl/docs/guides/migrate-from-spectral This guide moves a repository that lints its API descriptions with Spectral to `apigenie lint`: the built-in rules, your own rules and functions, the report in CI, and what has no counterpart. It starts from Spectral 6.17 with its `spectral:oas` and `spectral:asyncapi` rulesets and an OpenAPI file, `openapi.yaml`. You need the CLI installed; the [Quickstart](/docs/quickstart) shows how. Keep Spectral installed until the last step, so you can compare the two reports on the same files. ## What changes and what stays | | Spectral | API Genie | | --- | --- | --- | | Command | `spectral lint openapi.yaml` | `apigenie lint openapi.yaml` | | Configuration | `.spectral.yaml`, `.spectral.json` or `.spectral.js` | `apigenie.yaml`, section `commands.lint` ([Configuration](/docs/reference/cli/configuration)) | | Built-in rules | `spectral:oas` (57 rules), `spectral:asyncapi` (55) | rulesets per standard: `recommended`, `strict`, `all`; 67 rules for [OpenAPI](/docs/linter/openapi) (64 before 0.12.0), 48 for [Swagger 2.0](/docs/linter/swagger), 39 for [AsyncAPI](/docs/linter/asyncapi) (34 before 0.12.0) | | Severities | `error`, `warn`, `info`, `hint`, `off` | `error`, `warning`, `hint` (or `info`), `off`; a custom rule writes `warn` | | Custom rules | `given`, `then`, functions | the same format, under `commands.lint.rules` | | Custom functions | JavaScript, `functionsDir` | JavaScript in `functions/`, listed under `functions` | | Disabling a rule in one place | `overrides` by file in the ruleset | `x-apigenie-lint-disable` in the document | | Report formats | `-f json`, `junit`, `sarif`, `html`, ... | `--formatter json`, `junit`, `sarif`, `html`, ... | | Exit status | 1 at `--fail-severity` and above, `error` by default | 1 on an error, 0 on warnings only, 2 on a file it cannot read | | Fixes | none | `--fix` for the issues that have one | ## Run both on the same file ```sh spectral lint openapi.yaml apigenie lint openapi.yaml ``` ```text 764:6 warning Unused shared component unused-shared-component 781:8 error Schema with integer type does not define proper format schema-format-defined 2 issues (1 error, 1 warning) 0 errors, 1 warning are potentially auto-fixable ``` Each line gives the position, the severity, the message and the rule; every rule has a page in the [linter rules](/docs/linter) that says what it checks and why. The two reports differ, and not only in the names: without configuration API Genie applies the [recommended ruleset](/docs/linter/openapi/rulesets/recommended), 46 rules (43 before 0.12.0) of which some have no Spectral counterpart, and leaves out some of what `spectral:oas` reports. The next two sections say which. ## Replace the ruleset A `.spectral.yaml` that extends the built-in ruleset and adjusts a few rules: ```yaml extends: spectral:oas rules: operation-description: error info-contact: off oas3-server-not-example.com: warn ``` becomes, in `apigenie.yaml` at the root of the repository: ```yaml version: '1.0' commands: lint: extends: [recommended] rules: operation-description-defined: error contact-defined: off ``` - `extends` names API Genie's rulesets, not Spectral's: `spectral:oas` there is an error, with exit status 2. A Spectral ruleset file is named by its path ([Keep a shared ruleset file](#keep-a-shared-ruleset-file)). `recommended` is the default; `strict` turns on more rules with higher severities, `all` every rule. The rulesets of each standard are listed in the [linter rules](/docs/linter). - A rule takes its name from the table below. Spectral's `warn` is `warning` for a built-in rule; `hint` and `off` stay. - A rule with no counterpart, such as `oas3-server-not-example.com`, has no line. - An OpenAPI 3.x file, a Swagger 2.0 file and an AsyncAPI file are linted by three linters with rules of their own, so one configuration covers a repository that mixes them; Spectral picks the ruleset by the document's format. ## The rules of spectral:oas, by name The rules Spectral turns on by default, and their counterparts in the OpenAPI linter. A rule marked *not checked* has no counterpart today: drop its line from the configuration. | Spectral | API Genie | Note | | --- | --- | --- | | `operation-success-response` | [operation-success-response](/docs/linter/openapi/rules/operation-success-response) | | | `operation-operationId` | [operation-id-defined](/docs/linter/openapi/rules/operation-id-defined) | | | `operation-operationId-unique` | [operation-id-unique](/docs/linter/openapi/rules/operation-id-unique) | | | `operation-operationId-valid-in-url` | not checked | | | `operation-parameters` | [parameters-unique](/docs/linter/openapi/rules/parameters-unique) | | | `operation-tags` | [operation-tags-defined](/docs/linter/openapi/rules/operation-tags-defined) | | | `operation-tag-defined` | [operation-tags-declared](/docs/linter/openapi/rules/operation-tags-declared) | since 0.12.0 | | `operation-description` | [operation-description-defined](/docs/linter/openapi/rules/operation-description-defined) | also rejects descriptions under 10 characters | | `path-params` | [path-parameters-defined](/docs/linter/openapi/rules/path-parameters-defined) | [path-parameters-on-items](/docs/linter/openapi/rules/path-parameters-on-items) asks for them on the path item | | `path-declarations-must-exist`, `path-keys-no-trailing-slash` | [paths-well-formed](/docs/linter/openapi/rules/paths-well-formed) | | | `path-not-include-query` | not checked | | | `duplicated-entry-in-enum` | [schema-enum-no-duplicates](/docs/linter/openapi/rules/schema-enum-no-duplicates) | | | `typed-enum` | [schema-enum-types](/docs/linter/openapi/rules/schema-enum-types) | | | `array-items` | not checked | | | `no-$ref-siblings` | [ref-no-siblings](/docs/linter/openapi/rules/ref-no-siblings) | since 0.12.0; extensions, a Path Item's fields and a `$ref` key inside data (examples, defaults, Link values) are not reported | | `info-contact` | [contact-defined](/docs/linter/openapi/rules/contact-defined) | asks for `name`, and `url` or `email`, as Spectral's `contact-properties` does | | `info-description` | [info-defined](/docs/linter/openapi/rules/info-defined) | asks for `summary`, `description` and `version` | | `no-eval-in-markdown`, `no-script-tags-in-markdown` | [safe-markdown](/docs/linter/openapi/rules/safe-markdown) | | | `openapi-tags-uniqueness` | [tags-unique](/docs/linter/openapi/rules/tags-unique) | | | `oas3-api-servers` | [servers-defined](/docs/linter/openapi/rules/servers-defined) | | | `oas3-server-trailing-slash` | [server-urls-no-trailing-slash](/docs/linter/openapi/rules/server-urls-no-trailing-slash) | since 0.12.0 | | `oas3-server-variables` | not checked | | | `oas3-operation-security-defined` | [operation-security-defined](/docs/linter/openapi/rules/operation-security-defined) | a different check: every operation has a security requirement; Spectral checks that the named schemes exist | | `oas3-schema` | [openapi-json-schema-validation](/docs/linter/openapi/rules/openapi-json-schema-validation) | | | `oas3-unused-component` | [unused-shared-component](/docs/linter/openapi/rules/unused-shared-component) | follows references transitively, so a component used only by an unused one is reported too | | `oas3-examples-value-or-externalValue`, `oas3-valid-media-example`, `oas3-valid-schema-example` | not checked | examples are not validated against their schema | | `oas3-callbacks-in-callbacks`, `oas3_1-servers-in-webhook`, `oas3_1-callbacks-in-webhook`, `oas3_2-no-deprecated-xml-attribute` | not checked | | The rules Spectral leaves off by default: | Spectral | API Genie | | --- | --- | | `contact-properties` | [contact-defined](/docs/linter/openapi/rules/contact-defined) | | `info-license` | [license-defined](/docs/linter/openapi/rules/license-defined) | | `license-url` | not checked | | `openapi-tags` | not checked | | `openapi-tags-alphabetical` | [tags-sorted](/docs/linter/openapi/rules/tags-sorted) | | `operation-singular-tag` | not checked | | `tag-description` | [tag-description-defined](/docs/linter/openapi/rules/tag-description-defined) | | `oas3-parameter-description` | [parameter-description-defined](/docs/linter/openapi/rules/parameter-description-defined) | | `oas3-server-not-example.com` | not checked | The `oas2-*` rules apply to Swagger 2.0 files, which API Genie lints with the [Swagger 2.0 linter](/docs/linter/swagger): `oas2-schema` is [swagger-validation](/docs/linter/swagger/rules/swagger-validation), `oas2-api-host` is [host-defined](/docs/linter/swagger/rules/host-defined), `oas2-unused-definition` is [unused-shared-component](/docs/linter/swagger/rules/unused-shared-component), and the rules that share a name with an OpenAPI rule check the same thing. `operation-tag-defined` and `no-$ref-siblings` have no counterpart for Swagger 2.0 files. The AsyncAPI rules of `spectral:asyncapi` map onto the [AsyncAPI linter](/docs/linter/asyncapi) the same way: `asyncapi-info-contact` is [contact-defined](/docs/linter/asyncapi/rules/contact-defined), `asyncapi-channel-parameters` is [channel-parameters-defined](/docs/linter/asyncapi/rules/channel-parameters-defined), `asyncapi-unused-components-schema` is [unused-shared-component](/docs/linter/asyncapi/rules/unused-shared-component). ## What the recommended ruleset adds Rules of `recommended` that `spectral:oas` has nothing for; each has a page that says what it checks and why: - [schema-format-defined](/docs/linter/openapi/rules/schema-format-defined), [schema-format-type-mismatch](/docs/linter/openapi/rules/schema-format-type-mismatch) and [schema-format-deprecated](/docs/linter/openapi/rules/schema-format-deprecated): numbers and strings say their format, and the format fits the type. - [schema-constraints](/docs/linter/openapi/rules/schema-constraints) and [schema-no-additional-properties](/docs/linter/openapi/rules/schema-no-additional-properties): strings, numbers, arrays and objects have bounds. - [schema-no-contradictions](/docs/linter/openapi/rules/schema-no-contradictions), [schema-oneof-no-overlap](/docs/linter/openapi/rules/schema-oneof-no-overlap) and [schema-conditional-effective](/docs/linter/openapi/rules/schema-conditional-effective): schemas that reject every value, `oneOf` branches a value matches twice, `if` without effect. - [standard-response-codes](/docs/linter/openapi/rules/standard-response-codes), [unambiguous-response-codes](/docs/linter/openapi/rules/unambiguous-response-codes) and [no-content-response-defined](/docs/linter/openapi/rules/no-content-response-defined): the responses an operation declares. - [paths-max-depth](/docs/linter/openapi/rules/paths-max-depth), [paths-max-count](/docs/linter/openapi/rules/paths-max-count), [parameter-naming](/docs/linter/openapi/rules/parameter-naming) and [schema-datetime-suffix](/docs/linter/openapi/rules/schema-datetime-suffix): the shape of the URLs and the names. Outside `recommended`: [spell-check](/docs/linter/openapi/rules/spell-check) for the texts written for humans, [schema-keyword-support](/docs/linter/openapi/rules/schema-keyword-support) for the JSON Schema keywords the tools around the document ignore, and the [privacy ruleset](/docs/linter/openapi/rulesets/privacy) for credentials and personal data in URLs. `extends: [recommended, privacy]` adds the last one. ## Carry your custom rules over A custom rule keeps its definition. This rule of `.spectral.yaml`: ```yaml rules: operation-summary: description: Operations must have a summary message: "{{property}} is missing at {{path}}" severity: error given: "$.paths[*][get,put,post,delete,patch]" then: field: summary function: truthy ``` goes under `commands.lint.rules` of `apigenie.yaml` as it is: ```yaml version: '1.0' commands: lint: extends: [recommended] rules: operation-summary: description: Operations must have a summary message: "{{property}} is missing at {{path}}" severity: error given: "$.paths[*][get,put,post,delete,patch]" then: field: summary function: truthy ``` What carries over, as [custom rules](/docs/reference/cli/lint#custom-rules) documents it: - `given`, `then` with `field`, `function` and `functionOptions`, `message` with `{{error}}`, `{{description}}`, `{{path}}`, `{{property}}` and `{{value}}`, `description`, `severity`, `resolved` and `formats` (`oas2`, `oas3`, `oas3_0`, `oas3_1`, `oas3_2`, `aas3`, ...). - The core functions: `truthy`, `falsy`, `defined`, `undefined`, `enumeration`, `length`, `pattern`, `casing`, `alphabetical`, `or`, `xor`, `schema`, `typedEnum` and `unreferencedReusableObject`, with their options. - JSONPath as Spectral rulesets write it: member unions without quotes, `~` for member names, `^` for the parent, and filters written as JavaScript expressions with `@property`, `@parent`, `@path`, the string methods and `constructor.name` ([JSONPath](/docs/reference/cli/lint#jsonpath)). What does not: - `aliases` and the `#Name` references to them: write the path out. - Script expressions such as `[(@.length-1)]`. - `extends` with a URL or an npm package: copy the ruleset file into the repository and extend it by its path (see [Keep a shared ruleset file](#keep-a-shared-ruleset-file)). The one exception is `@stoplight/spectral-owasp-ruleset`, which API Genie ships: write [`owasp`](/docs/reference/cli/lint#the-owasp-ruleset) in `apigenie.yaml`, and a ruleset file you keep can extend the package by its name. - `overrides`, `parserOptions`, `documentationUrl` and `except`. - A custom rule named like a built-in rule: rename it. ## Keep a shared ruleset file Extend a ruleset file that several repositories share by its path, relative to `apigenie.yaml`, next to API Genie's rulesets: ```yaml version: '1.0' commands: lint: extends: [recommended, ./lint/team.spectral.yaml] rules: team-path-casing: warn ``` Say the shared file is this one: ```yaml # lint/team.spectral.yaml extends: [spectral:oas] rules: operation-tags: off info-contact: warn team-path-casing: given: "$.paths[*]~" then: { function: pattern, functionOptions: { match: "^(/[a-z-]+)+$" } } ``` Run `apigenie lint openapi.yaml`. The file's own `extends`, `functions` and `functionsDir` resolve against the file, and `apigenie.yaml` re-tunes its rules like any other. The warnings on the standard error name what was skipped: ```text warning: /work/api/lint/team.spectral.yaml: skipped "spectral:oas" in 'extends', which API Genie cannot load (only built-in and bundled rulesets and local ruleset files) warning: /work/api/lint/team.spectral.yaml: skipped the settings of rules API Genie does not have (2): operation-tags, info-contact ``` The counterparts of the skipped rules come from `recommended` and [the rules of spectral:oas](#the-rules-of-spectraloas-by-name). Files are read from the disk only, never from a URL. To lint with the file alone, run `apigenie lint --no-config --ruleset lint/team.spectral.yaml openapi.yaml`. A repository of the CAMARA project doesn't need its ruleset file: API Genie ships it, functions included, as [`camara`](/docs/reference/cli/lint#the-camara-ruleset). Start with `extends: [camara]`, which reports what CAMARA's Spectral run reports. Add `recommended` for the counterparts of the `spectral:oas` rules the file extends upstream. `camara` extends [`owasp`](/docs/reference/cli/lint#the-owasp-ruleset), the OWASP ruleset the file extends upstream, with CAMARA's settings of its rules. [Lint CAMARA APIs](/docs/guides/industry/lint-camara-apis) sets up a CAMARA repository step by step. ## Carry your functions over A JavaScript function written for Spectral works unchanged in most cases: it is an ES module whose default export receives the value, the options and a context, and `@stoplight/spectral-core` and `@stoplight/spectral-functions` are built in. Put the files in `functions/` next to `apigenie.yaml` (`functionsDir` changes the directory) and list them: ```yaml commands: lint: functions: [operationIdPrefix] rules: operation-id-prefix: given: "$.paths[*][*].operationId" then: function: operationIdPrefix functionOptions: { prefix: api } ``` Functions run in a sandbox with no file system, network, processes or timers, and a call must finish within 5 seconds. A function that reads a file or fetches a URL has to go; one that needs another module imports it from the functions directory. [JavaScript functions](/docs/reference/cli/lint#javascript-functions) has the contract. ## Disable a rule in one place Spectral turns a rule off for some files with `overrides` in the ruleset. API Genie turns it off where the issue is, in the document, with `x-apigenie-lint-disable` on the object and its descendants: ```yaml paths: /legacy/export: x-apigenie-lint-disable: - operation-id-defined get: summary: Export, as it was ``` Disable a rule as close to the issue as possible; [disabling rules](/docs/reference/cli/lint#disabling-rules-in-a-document) says more. ## The report in CI The formats that keep their name: `-f json`, `junit`, `sarif`, `html` and `stylish` become `--formatter json`, `junit`, `sarif`, `html` and `stylish`. API Genie adds `checkstyle`, `compact`, `tap`, `unix` and `visualstudio`; Spectral's `text`, `pretty`, `teamcity`, `github-actions`, `code-climate`, `gitlab` and `markdown` have no counterpart. For GitLab, `junit` is what the merge request reads; for GitHub code scanning, `sarif` ([formatting results](/docs/reference/cli/lint#formatters)). `--fail-severity` has no counterpart: the command exits with 1 when an error is reported and with 0 on warnings alone ([exit status](/docs/reference/cli/lint#exit-status)). To fail the build on a rule, give it `error` in the configuration. `-r .spectral.yaml` is `--ruleset .spectral.yaml`; without `apigenie.yaml` that runs only the rules the file defines, because `spectral:oas` is skipped and the file replaces `recommended`. Once its rules have moved, it is `--config apigenie.yaml`. On GitHub Actions, `stoplightio/spectral-action` becomes the [GitHub Action](/docs/ci/github-action), which installs the CLI and shows the issues on the lines of the pull request: ```yaml on: pull_request jobs: api: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: mykulyak/api-genie-action@v0 with: command: lint files: openapi.yaml ``` ## Remove Spectral When the two reports agree on what matters to you: delete `.spectral.yaml`, remove `@stoplight/spectral-cli` from the development dependencies, and replace the Spectral step of the pipeline with the one above. The fixes the linter offers are a `--fix` away: ```sh apigenie lint --fix openapi.yaml ``` --- # Migrate from Prism Source: https://apigenie.pl/docs/guides/migrate-from-prism This guide moves a repository that mocks its API with `prism mock` and checks it with `prism proxy` to `apigenie-server`: the addresses, the `Prefer` header, request validation, the validation proxy, the CI step, and what has no counterpart. It starts from Prism 5.x and an OpenAPI file, `openapi.yaml`. You need the CLI installed; the [Quickstart](/docs/quickstart) shows how. Keep Prism installed until the last step, so you can send the same requests to both. ## What changes and what stays | | Prism | API Genie | | --- | --- | --- | | Mock | `prism mock openapi.yaml` | `apigenie-server openapi.yaml` | | Validation proxy | `prism proxy openapi.yaml http://localhost:8080` | `apigenie-server openapi.yaml --proxy-to http://localhost:8080` | | Address | `http://127.0.0.1:4010`, CORS on | the same; `--host`, `--port`, `--cors off` | | Documents | OpenAPI 2.0 and 3.x, Postman collections | OpenAPI 3.0 to 3.2, Swagger 2.0, AsyncAPI 3, `.proto`, GraphQL | | Picking an answer | `Prefer: code=404`, `example=cat`, `dynamic=true`; `__code`, `__example`, `__dynamic` | the same, plus `delay=`, `drop=` and `scenario=` | | Static and dynamic | examples by default, `-d` generates | the same; `--dynamic` or `-d`, `--seed N` in both | | An invalid request | 422 with problem details | the same, with 400, 401, 415 for what they name | | An invalid answer of the mock | logged; a 500 with `--errors` | logged and counted in `X-Apigenie-Mock-Violations`; a 500 with `--strict` | | Violations of the proxy | `sl-violations` header; errors with `--errors` | `X-Apigenie-Mock-Violations` headers; errors with `--strict`; a report, and exit status 5 | | Reload on change | always | `--watch` | | Configuration | the command line | the command line, or `apigenie-server.yaml` ([Configuration](/docs/reference/server/configuration)) | | Docker | `stoplight/prism:5` | `mykulyak/apigenie-server` | | npm | `@stoplight/prism-cli` | `@mykulyak/api-genie` | ## Run both on the same document ```sh prism mock openapi.yaml apigenie-server openapi.yaml ``` ```text Listening on http://127.0.0.1:4010/v1 (spec: openapi.yaml, 12 operations) Admin API: http://127.0.0.1:4010/__apigenie Dashboard: http://127.0.0.1:4010/__apigenie/ui ``` Both listen on `127.0.0.1:4010` with CORS headers on, so a client keeps its base URL. Prism ignores the document's `servers` and serves `/pets`; `apigenie-server` serves the paths under the path of the first server, `/v1/pets`, and as they are, `/pets`, so both addresses answer. The dashboard shows every request, what answered it and what was wrong with it, which Prism prints to the terminal; `--log-level debug` and `--log-bodies` print it too. ```sh curl http://127.0.0.1:4010/pets ``` Both answer with the first example of the lowest 2xx response. Where a response has no example, Prism's static mode fills the schema with `"string"` and `0`; `apigenie-server` generates a value that fits the schema, its formats, patterns, ranges and enums, in static mode too ([Responses](/docs/reference/server/responses)). Prism's `--ignoreExamples` has `--dynamic` as its closest counterpart. ## Pick the answer of a request The `Prefer` header and the `__` query parameters keep their names: ```sh curl http://127.0.0.1:4010/pets -H 'Prefer: code=404' curl http://127.0.0.1:4010/pets -H 'Prefer: example=empty' curl 'http://127.0.0.1:4010/pets?__dynamic=true' ``` `apigenie-server` adds `delay=1500` (answer after 1.5 seconds), `drop=reset` (reset the connection; `close`, `timeout` and `truncate` too) and `scenario=outage` ([choosing a response per request](/docs/reference/server/responses#choosing-a-response-per-request)). For an answer that should hold for a while, such as an outage of one backend, a [scenario](/docs/reference/server/scenarios) in the document or in the configuration is switched on with `--scenario` or in the dashboard, instead of a `Prefer` header on every request. Prism's `__server` query parameter has no counterpart: the mock does not check which server a request is meant for. ## Request validation and security Both answer a request that does not match its operation with 422 and problem details. Prism answers with the operation's own 422 or 400 response when it declares one; `apigenie-server` answers with the problems it found: 422 for a parameter or a body that does not match its schema, 400 for a body it cannot parse, 415 for a media type the operation does not declare ([Validation and security](/docs/reference/server/validation)). Both answer 401 when a request carries no credentials for the operation's security requirements. Prism stops there; `apigenie-server` can check the credentials themselves: ```yaml # apigenie-server.yaml version: "1.0" security: mode: enforce credentials: {api_keys: {apiKey: [secret]}, bearer_tokens: [token]} ``` Prism's `--errors` on the mock, which turns an invalid answer of the mock into a 500, is `--strict`. Without it, the problems of an answer are logged and counted in the `X-Apigenie-Mock-Violations` header of that answer. ## Dynamic data and x-faker `-d` and `--seed` keep their names. `x-faker` on a property carries over, with one change: the providers are named like those of today's faker.js, `person.firstName` and `internet.email`, not `name.firstName` of the Faker 6 that Prism uses; the [Faker](/docs/reference/cli/faker) page lists them with their arguments: ```yaml Pet: type: object properties: name: {type: string, x-faker: person.firstName} owner: {type: string, x-faker: internet.email} ``` A property can get its provider from the configuration instead, without touching the document (`User.email: {faker: internet.email}` under `generation`), and string properties called like `email`, `first_name` or `city` get fitting values without any of this. Prism's `--json-schema-faker-fillProperties`, which adds properties the schema does not declare, has no counterpart. ## The validation proxy ```sh prism proxy openapi.yaml http://localhost:8080 apigenie-server openapi.yaml --proxy-to http://localhost:8080 ``` Every request goes to the real server, and the request and the server's answer are checked against the document. The violations of an exchange come back in headers, `sl-violations` in Prism, `X-Apigenie-Mock-Violations` and `X-Apigenie-Mock-Violations-Detail` here, and in the dashboard's Contract screen with the coverage of the document ([Contract testing](/docs/reference/server/contract-testing)). - `--errors` is `--strict`: a request that does not match the document is answered with 422 without reaching the server, and a server answer that does not match is replaced by a 502. - `--validate-request false` is `validation: {request: off}` in the configuration. - Prism mocks an operation the server answers with 501. `--proxy-mode fallback` does the same, and also when the server answers 404, does not answer in time or cannot be reached. - Both add `Deprecation: true` to the answers of a deprecated operation. - `--upstream-proxy` has no counterpart: the server reaches the upstream directly. ## The report in CI With Prism, CI learns about a contract violation from a test that fails behind `--errors`. `apigenie-server` writes a report when it stops, and exits with status 5 when the contract failed: ```sh apigenie-server openapi.yaml --proxy-to http://localhost:8080 \ --report contract.json --report-junit contract.xml --fail-on errors --min-coverage 80 & API_URL=http://localhost:4010 npm test curl -X POST http://localhost:4010/__apigenie/shutdown wait $! ``` `--fail-on errors` fails the job on an error-level violation even when every test passed, and `--min-coverage 80` when the tests leave more than a fifth of the document untested. The JUnit report has one test case per operation, so the CI system shows it next to the test results. [Mock and contract-test an API](/docs/guides/mock-and-contract-test-an-api) has the whole flow, with `--record` and `--replay` for tests that run without the real services. ## Several APIs Prism runs one document per process, on a port each: ```sh prism mock -p 5000 pets.yaml prism mock -p 5001 orders.yaml ``` One `apigenie-server` serves them as [services](/docs/reference/server/services), each at its own mount, with a proxy or a scenario of its own: ```sh apigenie-server pets.yaml orders.yaml ``` ```text Listening on http://127.0.0.1:4010 (2 services) pets http://127.0.0.1:4010/pets/v1 (spec: pets.yaml, 12 operations) orders http://127.0.0.1:4010/orders (spec: orders.yaml, 5 operations) ``` ## What has no counterpart - **Callbacks.** Prism sends the callback requests an operation declares; `apigenie-server` does not mock callbacks, webhooks or links. - **Postman collections as the document.** The mock serves OpenAPI, Swagger 2.0, AsyncAPI, Protobuf and GraphQL documents. `apigenie test import` turns a Postman collection into `.http` files for [`apigenie test`](/docs/reference/cli/test). - **`-m`, the second process for the log.** The server is one native process. - **`__server`, `--upstream-proxy` and `--json-schema-faker-fillProperties`**, as noted above. ## Remove Prism When the same requests get the answers you expect from both: replace `prism mock` and `prism proxy` in the scripts, the Compose file and the CI pipeline, remove `@stoplight/prism-cli` from the development dependencies, and swap the Docker image: ```sh docker run --rm -p 4010:4010 -v "$PWD:/mnt/data" mykulyak/apigenie-server openapi.yaml ``` The image listens on every interface of the container, as `prism mock -h 0.0.0.0` did. --- # Migrate from OpenAPI Generator Source: https://apigenie.pl/docs/guides/migrate-from-openapi-generator This guide moves a repository that generates clients or servers with OpenAPI Generator to `apigenie-generator`: the generator names, the options, the files you own, the build and the CI step, and what has no counterpart. It starts from OpenAPI Generator 7.x, run as `openapi-generator-cli`, from its Maven or Gradle plugin or from the npm wrapper, and an OpenAPI file, `openapi.yaml`. You need the CLI installed; the [Quickstart](/docs/quickstart) shows how. Keep OpenAPI Generator until the last step: the two can generate into separate directories while you compare. ## What changes and what stays | | OpenAPI Generator | API Genie | | --- | --- | --- | | Command | `openapi-generator-cli generate -g spring -i openapi.yaml -o server` | `apigenie-generator server spring openapi.yaml -o server` | | Targets | 172 generators, in Java, Kotlin, Swift, Rust, PHP and more | 7 clients and 9 servers from OpenAPI, 14 targets from AsyncAPI, a documentation site, example data ([the list](/docs/reference/generator)) | | Input | OpenAPI 2.0 and 3.x | OpenAPI 3.0 to 3.2; Swagger 2.0 for the clients and servers (since 0.12.0); AsyncAPI 3, GraphQL, Protobuf, JSON Schema | | Options | `--additional-properties a=b,c=d`, `-c config.yaml` | `-p a=b -p c=d`, `commands.generate.` of `apigenie.yaml` | | Files you own | `.openapi-generator-ignore`, `--skip-overwrite` | the implementation files, written only when missing; `.openapi-generator-ignore` for Spring, Java and FastAPI | | Changing the output | Mustache and Handlebars templates, `-t` | an [overlay](/docs/reference/generator#overlays) and the `x-apigenie` extensions, no templates | | Checking the input | `--skip-validate-spec` to skip it | always; `apigenie lint` says what to fix | | Runtime | Java 11 or later | a native binary: archives, `.deb`, `.rpm`, npm, Homebrew, Docker | | Build plugins | Maven, Gradle | none; a step before the build, or generated code checked in and verified in CI | ## Run both on the same document ```sh openapi-generator-cli generate -g typescript-fetch -i openapi.yaml -o client-oag apigenie-generator client fetch openapi.yaml -o client --package-name shipping-client ``` The target comes first, as two words, and the input comes last; `-i` and `-g` are gone, `-o` stays. The output is an npm package with no runtime dependency: requests go through the global `fetch()`, and each operation is an `async` function named after its `operationId`, taking one object of parameters, as `useSingleRequestParameter` gives in OpenAPI Generator. [Generate a client and a server](/docs/guides/generate-a-client-and-a-server) shows the client in use. ## The generators by name | OpenAPI Generator | API Genie | Note | | --- | --- | --- | | `typescript-fetch`, `typescript-axios`, `typescript-node` | [client fetch](/docs/reference/generator/client-fetch) | one TypeScript client on the global `fetch()`, for browsers and Node.js 18 or later; `layout: sources` for a bundler | | `java` | [client java](/docs/reference/generator/client-java) | `--library restclient` (default), `resttemplate`, `feign` or `http-interface`: the client depends on Spring Framework, not on OkHttp or Jersey | | `spring` | [server spring](/docs/reference/generator/server-spring) | the same code and options, in place (below) | | `python` | [client python](/docs/reference/generator/client-python) | httpx and Pydantic 2 | | `python-fastapi` | [server fastapi](/docs/reference/generator/server-fastapi) | the same layout and options, in place (below) | | `go` | [client go](/docs/reference/generator/client-go) | `net/http`; `layout: module` writes `go.mod` | | `go-server`, `go-gin-server` | [server go](/docs/reference/generator/server-go) | `net/http` | | `csharp` | [client csharp](/docs/reference/generator/client-csharp) | `HttpClient` with `IHttpClientFactory` registration; `target_framework: net8.0` to `net10.0` | | `aspnetcore` | [server aspnet](/docs/reference/generator/server-aspnet) | Minimal APIs | | `elixir` | [client elixir](/docs/reference/generator/client-elixir) | Req | | `rust` | [client rust](/docs/reference/generator/client-rust) | reqwest 0.12 and serde, async; experimental | | `rust-axum` | [server axum](/docs/reference/generator/server-axum) | axum 0.8; experimental | | `nodejs-express-server` | [server express](/docs/reference/generator/server-express) | TypeScript, typed handlers, requests validated with Ajv or generated validators | | `html`, `html2`, `markdown`, `asciidoc`, `dynamic-html` | [docs](/docs/reference/generator/docs) | one site for several documents, with Try it out and search | | `openapi`, `openapi-yaml` | [`apigenie convert`](/docs/reference/cli/convert), [`apigenie bundle`](/docs/reference/cli/bundle) and [`apigenie format`](/docs/reference/cli/format) | | | `kotlin`, `swift6`, `dart`, `php`, `ruby`, `scala-*`, `cpp-*`, `kotlin-spring`, `java-*` servers, `python-flask`, `rust-server`, ... | no counterpart | keep OpenAPI Generator for these targets; both can run in one repository | Every API Genie client and server in the table runs in contract tests before a release, except `client rust` and `server axum`, which are experimental and have no Level 3 yet. The [conformance results](/docs/reference/generator/conformance) list each target's results and the features of the conformance fixture it doesn't support yet. Look up your target there before you switch: the same list is on the target's page, under Verification. The other commands: `openapi-generator-cli validate` is [`apigenie lint`](/docs/reference/cli/lint), `list` is the help of `apigenie-generator`, which names the targets, `config-help -g` is the Configuration section of the target's page, and `batch` is one `apigenie.yaml` with a section per target and one command per target. `meta`, which starts a generator of your own, has no counterpart. ## Option by option | OpenAPI Generator | API Genie | | --- | --- | | `-i openapi.yaml` | the last argument | | `-g NAME` | the target, `client fetch`, `server spring`, ... | | `-o DIR` | `-o DIR` | | `-c config.yaml` | `-c apigenie.yaml`, section `commands.generate.` | | `--additional-properties a=b,c=d` | `-p a=b -p c=d`, or the keys of that section | | `--package-name`, `npmName`, `packageName` | `--package-name`: the npm package, the Python distribution, the Go package, the C# namespace, the Java base package, the Mix application, the Rust crate | | `--artifact-version`, `npmVersion`, `packageVersion` | `--package-version` | | `--library` | `--library` of `client java`; `library` of `server spring` | | `--invoker-package`, `--api-package`, `--model-package`, `--group-id`, `--artifact-id` | `basePackage`, `apiPackage`, `modelPackage`, `groupId`, `artifactId` of `client_java` and `server_spring` | | `--type-mappings`, `--import-mappings` | `typeMappings` and `importMappings` (Java, Spring), `type_mappings` (Go, Rust) | | `--model-name-prefix`, `--model-name-suffix` | `model_suffix` (C#, ASP.NET), `modelNamePrefix` (FastAPI) | | `--global-property apis` or `models` | `include_tags` and `exclude_tags` (Go, Elixir, Phoenix, Rust), `generate: [types]` (`server go`) | | `--inline-schema-name-mappings` | `class_overrides` (Python), `module_overrides` (Elixir, Phoenix) | | `--openapi-normalizer` | an overlay, for the changes that fit one | | `useTags` | `useTags` (Java, Spring), `grouping: tag` (C#, ASP.NET, Express), `group_by: tag` (Python) | | `--skip-validate-spec`, `-t`, `--engine`, `--minimal-update`, `--dry-run`, `-s`, `--server-variables`, `--remove-operation-id-prefix`, `--git-*`, `--release-note`, `--http-user-agent`, `--enable-post-process-file` | no counterpart | An option a target does not know is an error, not ignored, so a copied configuration says at once what did not carry over. ## Keep your code out of the generated files OpenAPI Generator protects your files with `.openapi-generator-ignore` and `--skip-overwrite`. Each server target of `apigenie-generator` has a place for your code that regenerating never touches: - `server spring`: the controllers, written only when missing, or the delegates with `delegatePattern: true`; `.openapi-generator-ignore` is read. - `server fastapi`: the `impl` package, the tests of the APIs and `tests/conftest.py`, written only when missing; `.openapi-generator-ignore` is read. - `server express`: the handlers, in files of your own, that the generated router calls. - `server aspnet`: `Program.cs` and the stub implementations, written only when missing. - `server go`: your implementation of the generated interfaces, and `main.go` with `main: true`, written only when missing. - `server phoenix`: your implementations of the generated behaviours. `client java` writes `.openapi-generator-ignore` too. For the other targets, generate into a directory of its own: everything in it is generated, and your code lives next to it. ## Regenerate a Spring or FastAPI project in place `server spring` produces the code of OpenAPI Generator's `spring` generator and accepts the same options; `server fastapi` has the layout and the options of `python-fastapi`. A project generated by OpenAPI Generator is generated again by `apigenie-generator`, in the same directory, with the same `.openapi-generator-ignore`. The `config.yaml` of OpenAPI Generator: ```yaml basePackage: com.acme.pets delegatePattern: true useBeanValidation: true ``` goes under the target in `apigenie.yaml`, as it is or under an `additionalProperties` key: ```yaml version: '1.0' commands: generate: server_spring: basePackage: com.acme.pets delegatePattern: true useBeanValidation: true ``` ```sh apigenie-generator server spring openapi.yaml -o server git diff --stat server ``` The differences each page lists under "Differences from openapi-generator" show up in that diff: for Spring, `useSpringBoot3` is `true` by default and the files are marked `@Generated(value = "API Genie")`; for FastAPI, routes declare their status code and response class, the models are Pydantic 2 models without `to_dict()` and `from_dict()`, and `oneOf` is a union. Both read OpenAPI 3.0 to 3.2 and, since 0.12.0, Swagger 2.0 ([Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); a document that references other files is bundled first with `apigenie bundle`. ## The build and CI The Maven plugin's `generate-sources` execution and the Gradle `openApiGenerate` task become a command before the build, since `apigenie-generator` is a binary rather than a plugin: an `exec-maven-plugin` execution, a Gradle `Exec` task, or an npm script with the CLI from the `@mykulyak/api-genie` package, which pins its version in `package.json` as `openapitools.json` did. In Docker, `mykulyak/apigenie` runs it with `--entrypoint apigenie-generator`. Or generate into the repository and let CI check that the generated code matches the contract (since 0.12.0): ```sh apigenie-generator client fetch openapi.yaml -o client --package-name shipping-client --check apigenie-generator server spring openapi.yaml -o server --check ``` Each command writes nothing, prints the generated files that would be created or changed, and exits with 1 when there are any ([`--check`](/docs/reference/generator#check-that-generated-code-is-up-to-date)): someone edited them by hand or forgot to regenerate. ## What has no counterpart - **The targets listed above as such.** Kotlin, Swift, Dart, PHP, Ruby, Scala and C++ clients, and the servers other than Spring, FastAPI, Express, ASP.NET Core, Go, Phoenix and axum. - **Templates and custom generators.** `-t`, `--engine` and `meta`: the output changes through the options, an overlay and the `x-apigenie` extensions each target's page lists. - **Maven and Gradle plugins**, replaced by a step before the build. - **`--skip-validate-spec`.** A document the generator cannot use stops it with exit status 2. ## Remove OpenAPI Generator When the generated projects build and their tests pass: remove `@openapitools/openapi-generator-cli` and `openapitools.json`, or the plugin from `pom.xml` and `build.gradle`, delete the `.openapi-generator/` directories and the `.openapi-generator-ignore` files of the targets that do not read them, and replace the generation step in CI. --- # Migrate from Buf Source: https://apigenie.pl/docs/guides/migrate-from-buf This guide moves what `buf lint`, `buf breaking` and `buf format` do for a repository of Protobuf files to `apigenie lint`, `apigenie diff` and `apigenie format`: the rules by name, the `buf.yaml` settings, the CI step, and what stays with Buf, since `buf generate` and the Buf Schema Registry have no counterpart. It starts from Buf 1.75 with a v2 `buf.yaml` and the files under `proto/`. You need the CLI installed; the [Quickstart](/docs/quickstart) shows how. Keep Buf installed until the last step, so you can compare the two reports on the same files, and keep it after that if your code is generated with `buf generate`. ## What changes and what stays | | Buf | API Genie | | --- | --- | --- | | Lint | `buf lint` | `apigenie lint proto/**/*.proto` | | Breaking changes | `buf breaking --against '.git#branch=main'` | `apigenie diff main.proto shop.proto`, file by file | | Format | `buf format -w`, `buf format --exit-code` | `apigenie format proto/**/*.proto`, `apigenie format --check` | | Configuration | `buf.yaml` | `apigenie.yaml`, sections `commands.lint.protobuf`, `commands.diff.protobuf` and `commands.format.protobuf` ([Configuration](/docs/reference/cli/configuration)) | | Lint rules | 45 in the `MINIMAL`, `BASIC`, `STANDARD`, `COMMENTS` and `UNARY_RPC` categories | 39 in the `recommended`, `strict` and `all` rulesets ([Protobuf rules](/docs/linter/protobuf)) | | Severities | every violation fails | `error` fails, `warning` does not; set per rule | | Ignoring one place | `// buf:lint:ignore RULE`, `ignore` and `ignore_only` by path | `// apigenie-lint-disable rule` on the declaration | | Imports | the module's directories, `deps` from the registry | `--proto-path`, `import_paths` in the configuration, the directories above the file; the well-known types built in | | Report formats | `--error-format text`, `json`, `msvs`, `junit`, `github-actions`, `gitlab-code-quality` | `--formatter stylish`, `json`, `visualstudio`, `junit`, `checkstyle`, `sarif`, ... | | Files | proto2, proto3, editions | proto3 | | Code generation | `buf generate`, `buf.gen.yaml` | stays with Buf; `apigenie-generator` writes Elixir gRPC clients and servers only | ## Run both on the same files ```sh buf lint apigenie lint proto/**/*.proto ``` ```text 12:1 warning Service name 'Shop' should end with 'Service' service-suffix 31:3 warning Enum zero value 'STATUS_NONE' should end with '_UNSPECIFIED' enum-zero-value-suffix 2 issues (0 errors, 2 warnings) 0 errors, 0 warnings are potentially auto-fixable ``` `apigenie lint` takes files, so the shell's `**` glob, or a list, stands in for Buf's module directory. Without configuration it applies the [recommended](/docs/linter/protobuf/rulesets/recommended) ruleset: the structural rules at `error`, the naming and style rules at `warning`, which the command reports without failing. Buf's `STANDARD` category fails on each of them. To fail the same way, extend `strict` or raise the rules you care about to `error` (below). Imports are looked up on the paths given with `--proto-path`, then in `import_paths` of the configuration, then in the directory of the importing file and the directories above it, and `google/protobuf/*.proto` are built in. A Buf module whose files import each other by their path from the module root needs that root on the path: ```sh apigenie lint --proto-path proto proto/**/*.proto ``` ## Replace buf.yaml ```yaml version: v2 lint: use: - STANDARD - COMMENTS except: - PACKAGE_VERSION_SUFFIX service_suffix: API ignore: - proto/vendor breaking: use: - FILE ``` becomes ```yaml version: '1.0' commands: lint: protobuf: extends: [strict] import_paths: [proto] rules: package-version-suffix: off service-suffix: [warning, API] field-comment-defined: error oneof-comment-defined: error enum-value-comment-defined: error diff: protobuf: extends: [recommended] ``` - `use` names categories; `extends` names a ruleset: `recommended` (29 rules), `strict` (34: it adds the comments of messages, enums, services and RPCs, sorted imports, the version suffix and spelling) or `all` (39: every comment, and no streaming). The table below maps each rule. - `except` is `off` on the rule; a rule's options follow its severity in a list. - `ignore` by path has no counterpart: leave the directory out of the files you pass, or disable the rules in the files with `// apigenie-lint-disable`. - `breaking.use` has no equivalent list: the `recommended` rules of the differ rate every change (below). ## The lint rules by name | Buf | API Genie | | --- | --- | | `DIRECTORY_SAME_PACKAGE`, `PACKAGE_DEFINED`, `PACKAGE_DIRECTORY_MATCH`, `PACKAGE_NO_IMPORT_CYCLE`, `PACKAGE_SAME_DIRECTORY` | [directory-same-package](/docs/linter/protobuf/rules/directory-same-package), [package-defined](/docs/linter/protobuf/rules/package-defined), [package-directory-match](/docs/linter/protobuf/rules/package-directory-match), [package-no-import-cycle](/docs/linter/protobuf/rules/package-no-import-cycle), [package-same-directory](/docs/linter/protobuf/rules/package-same-directory) | | `ENUM_PASCAL_CASE`, `ENUM_VALUE_UPPER_SNAKE_CASE`, `FIELD_LOWER_SNAKE_CASE`, `MESSAGE_PASCAL_CASE`, `ONEOF_LOWER_SNAKE_CASE`, `PACKAGE_LOWER_SNAKE_CASE`, `RPC_PASCAL_CASE`, `SERVICE_PASCAL_CASE`, `FILE_LOWER_SNAKE_CASE` | [enum-naming](/docs/linter/protobuf/rules/enum-naming), [enum-value-naming](/docs/linter/protobuf/rules/enum-value-naming), [field-naming](/docs/linter/protobuf/rules/field-naming), [message-naming](/docs/linter/protobuf/rules/message-naming), [oneof-naming](/docs/linter/protobuf/rules/oneof-naming), [package-naming](/docs/linter/protobuf/rules/package-naming), [rpc-naming](/docs/linter/protobuf/rules/rpc-naming), [service-naming](/docs/linter/protobuf/rules/service-naming), [file-naming](/docs/linter/protobuf/rules/file-naming) | | `ENUM_NO_ALLOW_ALIAS` | [enum-no-allow-alias](/docs/linter/protobuf/rules/enum-no-allow-alias) | | `ENUM_VALUE_PREFIX`, `ENUM_ZERO_VALUE_SUFFIX` | [enum-value-prefix](/docs/linter/protobuf/rules/enum-value-prefix), [enum-zero-value-suffix](/docs/linter/protobuf/rules/enum-zero-value-suffix) (the suffix is an option) | | `IMPORT_NO_PUBLIC`, `IMPORT_USED` | [import-no-public](/docs/linter/protobuf/rules/import-no-public), [import-used](/docs/linter/protobuf/rules/import-used); also [import-no-weak](/docs/linter/protobuf/rules/import-no-weak), [import-resolved](/docs/linter/protobuf/rules/import-resolved) and, in `strict`, [imports-sorted](/docs/linter/protobuf/rules/imports-sorted) | | `PACKAGE_SAME_CSHARP_NAMESPACE`, `PACKAGE_SAME_GO_PACKAGE`, `PACKAGE_SAME_JAVA_MULTIPLE_FILES`, `PACKAGE_SAME_JAVA_PACKAGE`, `PACKAGE_SAME_PHP_NAMESPACE`, `PACKAGE_SAME_RUBY_PACKAGE`, `PACKAGE_SAME_SWIFT_PREFIX` | [package-options-consistent](/docs/linter/protobuf/rules/package-options-consistent), one rule for the language options | | `PACKAGE_VERSION_SUFFIX` | [package-version-suffix](/docs/linter/protobuf/rules/package-version-suffix), in `strict` | | `RPC_REQUEST_RESPONSE_UNIQUE`, `RPC_REQUEST_STANDARD_NAME`, `RPC_RESPONSE_STANDARD_NAME`, `SERVICE_SUFFIX` | [rpc-request-response-unique](/docs/linter/protobuf/rules/rpc-request-response-unique), [rpc-request-standard-name](/docs/linter/protobuf/rules/rpc-request-standard-name), [rpc-response-standard-name](/docs/linter/protobuf/rules/rpc-response-standard-name), [service-suffix](/docs/linter/protobuf/rules/service-suffix) (the suffix is an option) | | `COMMENT_ENUM`, `COMMENT_MESSAGE`, `COMMENT_RPC`, `COMMENT_SERVICE` | [enum-comment-defined](/docs/linter/protobuf/rules/enum-comment-defined), [message-comment-defined](/docs/linter/protobuf/rules/message-comment-defined), [rpc-comment-defined](/docs/linter/protobuf/rules/rpc-comment-defined), [service-comment-defined](/docs/linter/protobuf/rules/service-comment-defined), in `strict` | | `COMMENT_ENUM_VALUE`, `COMMENT_FIELD`, `COMMENT_ONEOF` | [enum-value-comment-defined](/docs/linter/protobuf/rules/enum-value-comment-defined), [field-comment-defined](/docs/linter/protobuf/rules/field-comment-defined), [oneof-comment-defined](/docs/linter/protobuf/rules/oneof-comment-defined), in `all` | | `RPC_NO_CLIENT_STREAMING`, `RPC_NO_SERVER_STREAMING` | [rpc-no-client-streaming](/docs/linter/protobuf/rules/rpc-no-client-streaming), [rpc-no-server-streaming](/docs/linter/protobuf/rules/rpc-no-server-streaming), in `all` | | `ENUM_FIRST_VALUE_ZERO`, `FIELD_NOT_REQUIRED`, `SYNTAX_SPECIFIED` | not checked: the linter reads proto3 files, where protoc enforces the three | | `PROTOVALIDATE`, `STABLE_PACKAGE_NO_IMPORT_UNSTABLE` | not checked | Buf has nothing for [spell-check](/docs/linter/protobuf/rules/spell-check), which checks the comments with a dictionary (in `strict`, at `warning`). ## Breaking changes `buf breaking` compares a module with another input, a Git ref included. `apigenie diff` compares two files, so CI fetches the old version first: ```sh git show main:proto/shop/v1/shop.proto > main.proto apigenie diff main.proto proto/shop/v1/shop.proto ``` ```text shop.proto 19 1 breaking Modified message 'Customer' 19 1 non-breaking Removed field 'fax' 25 3 breaking Modified field 'full_name' 25 3 breaking Modified field name ``` The command exits with 1 on a breaking change, as `buf breaking` does. Fields and enum values are matched by number, so a renamed field is a modified one, and removing a field whose number the new file reserves is non-breaking, the way Protobuf retires fields. The files are compared on their own: to compare the declarations of imported files too, [bundle](/docs/reference/cli/bundle) both versions first. Buf's categories pick what counts: `FILE` and `PACKAGE` protect the generated code, `WIRE` and `WIRE_JSON` the encoded messages. The `recommended` rules of the differ rate as breaking what breaks either: a removed or renamed declaration, a changed type, label or oneof, the types or the streaming of a method, the package, an option that names the generated code such as `go_package`. For a `WIRE` policy, where names and compatible types may change, the differ's rules say so, with a `wire_compatible` condition: ```yaml version: '1.0' commands: diff: protobuf: extends: [recommended] rules: field: name: non_breaking type: modify: if: wire_compatible then: non_breaking else: breaking ``` [diff.protobuf](/docs/reference/cli/diff#diffprotobuf) lists the properties of every node type, the conditions, and `overrides` for a part of the file, which stand in for Buf's `ignore` and `ignore_only`. ## Format `buf format -w` is `apigenie format` on the files, and `buf format --exit-code` is `apigenie format --check`, which writes nothing and exits with 1 when a file is not formatted. The formatter writes one statement per line, normalizes the spacing and keeps every comment. With the recommended settings it also sorts imports and option statements; `extends: [original]` under `commands.format` keeps every order, and [the Protobuf settings](/docs/reference/cli/format/protobuf) sort declarations, fields or methods when you want that. proto2 and editions files are reported and left untouched. ## The report in CI `--error-format junit` is `--formatter junit` for `apigenie lint`; `msvs` is `visualstudio`; `json` keeps its name; `github-actions` and `gitlab-code-quality` have no counterpart, and `apigenie diff` writes `json`, `markdown`, `html`, `stylish`, `unix` and `visualstudio`. On GitHub, the [GitHub Action](/docs/ci/github-action) runs the three commands with their results as annotations on the lines of the pull request, and `diff` compares each file with its version at the base of the pull request on its own: ```yaml on: pull_request jobs: proto: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: mykulyak/api-genie-action@v0 with: command: lint files: proto/**/*.proto - uses: mykulyak/api-genie-action@v0 with: command: format files: proto/**/*.proto - uses: mykulyak/api-genie-action@v0 with: command: diff files: proto/**/*.proto ``` ## What stays with Buf - **Code generation.** `buf generate` with `buf.gen.yaml` and its plugins has no counterpart. `apigenie-generator` reads `.proto` files for an [Elixir gRPC client](/docs/reference/generator/client-elixir-protobuf) and an [Elixir gRPC server](/docs/reference/generator/server-elixir-grpc) only. - **The Buf Schema Registry.** `deps` and `--against-registry` have no counterpart; the imported files have to be in the repository, on an import path. - **proto2 and editions.** The linter, the differ and the formatter read proto3 files. What Buf lacks: a [gRPC mock](/docs/reference/server/grpc) of the `.proto` file, served with stubs, reflection and recording, and [`apigenie test`](/docs/reference/cli/test) for `GRPC` requests in `.http` files, checked against the file. ## Remove Buf from the checks When the two reports agree on the files you have: replace `buf lint`, `buf breaking` and `buf format` in the scripts and the pipeline, keep `buf generate` and its `buf.gen.yaml`, and keep `buf.yaml` for it, without the `lint` and `breaking` sections. --- # Migrate from Redocly CLI Source: https://apigenie.pl/docs/guides/migrate-from-redocly This guide moves a repository that lints and bundles its OpenAPI descriptions with Redocly CLI to `apigenie`: the ruleset and the rules by name, `redocly.yaml`, your configurable rules, the decorators, the bundle, the report in CI, and what stays with Redocly. It starts from Redocly CLI 2.72 with its `recommended` ruleset and an OpenAPI file, `openapi.yaml`. You need the CLI installed; the [Quickstart](/docs/quickstart) shows how. Keep Redocly CLI installed until the last step, so you can compare the two reports on the same files. ## What changes and what stays | | Redocly CLI | API Genie | | --- | --- | --- | | Lint | `redocly lint openapi.yaml` | `apigenie lint openapi.yaml` | | Configuration | `redocly.yaml`: `extends`, `rules`, `apis` | `apigenie.yaml`, section `commands.lint` ([Configuration](/docs/reference/cli/configuration)) | | Built-in rulesets | `minimal`, `recommended`, `recommended-strict`, `all`, `spec` | `recommended`, `strict`, `all`, per standard; 67 rules for [OpenAPI](/docs/linter/openapi) (64 before 0.12.0) | | Severities | `error`, `warn`, `off` | `error`, `warning`, `hint`, `off` | | Configurable rules | `rule/` with `subject` and `assertions` | custom rules in Spectral's format, `given` and `then` | | Plugins | JavaScript rules, decorators and preprocessors | JavaScript functions, in a sandbox | | Ignoring a problem | `.redocly.lint-ignore.yaml` | `x-apigenie-lint-disable` in the document | | Decorators | `remove-x-internal`, `info-override`, `filter-in`, ... | OpenAPI Overlays, applied by `apigenie overlay` | | Bundle | `redocly bundle openapi.yaml -o dist/openapi.yaml` | `apigenie bundle openapi.yaml --output dist/openapi.yaml` | | Report formats | `--format codeframe`, `stylish`, `json`, `junit`, ... | `--formatter stylish`, `json`, `junit`, `sarif`, ... | | Exit status | 1 on an error, 0 on warnings alone | the same, and 2 on a file it cannot read | | Fixes | none | `--fix` for the issues that have one | | Configuration check | `redocly check-config` | `apigenie config check` | | Documentation | `redocly build-docs openapi.yaml` | `apigenie-generator docs openapi.yaml -o docs` | ## Run both on the same file ```sh redocly lint --format stylish openapi.yaml apigenie lint openapi.yaml ``` With its `recommended` ruleset, Redocly reports three problems in a small file whose operation has no security requirement, no error response and an unused schema: ```text openapi.yaml: 15:5 error security-defined Every operation should have security defined on it or on the root level. 19:7 warning operation-4xx-response Operation must have at least one `4XX` response. 33:5 warning no-unused-components Component: "Unused" is never used. ``` API Genie reports ten: ```text 3:3 error Info summary is missing or empty info-defined 3:3 error Info description is missing or empty info-defined 11:5 warning Tag 'pets' has no meaningful description defined tag-description-defined 16:7 error Operation has no meaningful description operation-description-defined 16:7 warning Security requirement is not defined operation-security-defined 21:11 warning Missing rate limiting header operation-rate-limiting-defined 27:19 error Object schema does not disable additional properties schema-no-additional-properties 30:23 error Schema with integer type does not define proper format schema-format-defined 34:7 warning String schema does not define constraints restricting its length schema-constraints 34:7 warning Unused shared component unused-shared-component 10 issues (5 errors, 5 warnings) 1 errors, 1 warnings are potentially auto-fixable ``` Each line gives the position, the severity, the message and the rule; every rule has a page in the [linter rules](/docs/linter) that says what it checks and why. The two reports differ, and not only in the names: without configuration API Genie applies the [recommended ruleset](/docs/linter/openapi/rulesets/recommended), 46 rules (43 before 0.12.0) that ask for descriptions, formats and bounds Redocly's `recommended` does not, and it leaves out some of what Redocly reports, such as the missing error response. The next two sections say which. ## Replace the configuration A `redocly.yaml` that extends the built-in ruleset, adjusts a few rules and names the APIs: ```yaml extends: - recommended rules: operation-4xx-response: off no-unused-components: error info-contact: warn apis: orders@v1: root: apis/orders/openapi.yaml ``` becomes, in `apigenie.yaml` at the root of the repository: ```yaml version: '1.0' commands: lint: extends: [recommended] rules: unused-shared-component: error contact-defined: warning ``` - `extends` names API Genie's rulesets, not Redocly's. `recommended` is the default; `strict` turns on more rules with higher severities, `all` every rule. Redocly's `recommended-strict` is `recommended` with every rule at `error`, which has no ruleset of its own: start from `recommended` and raise the rules that matter to `error`. `minimal` is `recommended` with most rules off, and `spec`, the `struct` rule alone, is [openapi-json-schema-validation](/docs/linter/openapi/rules/openapi-json-schema-validation) listed under `rules` without `extends`. - A rule takes its name from the tables below. Redocly's `warn` is `warning`; `error` and `off` stay. - A rule with no counterpart, such as `operation-4xx-response`, has no line. - `apis` has no counterpart: one `commands.lint` section applies to every file the command is given. A repository whose APIs need different rules keeps a configuration file per API and passes it with `--config`, or disables rules in the documents, as [below](#disable-a-rule-in-one-place). - `oas2Rules`, `oas3_0Rules`, `oas3_1Rules` and `async3Rules` become the `swagger` and `asyncapi` sections next to `rules`: an OpenAPI 3.x file, a Swagger 2.0 file and an AsyncAPI file are linted by three linters with rules of their own, from one configuration ([configuration of lint](/docs/reference/cli/lint#configuration)). `arazzo1Rules` have no counterpart: Arazzo files are not read. - `--skip-rule` on the command line is `off` in the configuration, and `--extends` is `--config` with another file. `--max-problems` has no counterpart. ## The rules of recommended, by name The rules Redocly's `recommended` ruleset reports as errors, and their counterparts in the OpenAPI linter. A rule marked *not checked* has no counterpart today: drop its line from the configuration. | Redocly | API Genie | Note | | --- | --- | --- | | `struct` | [openapi-json-schema-validation](/docs/linter/openapi/rules/openapi-json-schema-validation) | | | `no-unresolved-refs` | [openapi-json-schema-validation](/docs/linter/openapi/rules/openapi-json-schema-validation) | local schema `$ref` targets are checked; external references are not fetched | | `operation-operationId-unique` | [operation-id-unique](/docs/linter/openapi/rules/operation-id-unique) | | | `operation-parameters-unique` | [parameters-unique](/docs/linter/openapi/rules/parameters-unique) | | | `path-parameters-defined` | [path-parameters-defined](/docs/linter/openapi/rules/path-parameters-defined) | [path-parameters-on-items](/docs/linter/openapi/rules/path-parameters-on-items) asks for them on the path item | | `security-defined` | [operation-security-defined](/docs/linter/openapi/rules/operation-security-defined) | every operation has a security requirement | | `no-identical-paths` | [paths-unique](/docs/linter/openapi/rules/paths-unique) | | | `no-path-trailing-slash`, `path-declaration-must-exist` | [paths-well-formed](/docs/linter/openapi/rules/paths-well-formed) | also rejects `//` and upper-case letters outside the placeholders | | `path-not-include-query` | not checked | | | `no-enum-type-mismatch` | [schema-enum-types](/docs/linter/openapi/rules/schema-enum-types) | | | `no-schema-type-mismatch`, `no-example-value-and-externalValue` | not checked | | | `no-empty-servers` | [servers-defined](/docs/linter/openapi/rules/servers-defined) | | | `no-server-trailing-slash` | [server-urls-no-trailing-slash](/docs/linter/openapi/rules/server-urls-no-trailing-slash) | since 0.12.0; top-level `servers` only, where Redocly also checks those of path items and operations | | `no-server-variables-empty-enum`, `no-undefined-server-variable` | not checked | [server-urls](/docs/linter/openapi/rules/server-urls) checks the scheme and the case of the URL instead | | `operation-summary` | not checked | the custom rule [below](#carry-your-configurable-rules-over) | | `operation-operationId-url-safe`, `spec-components-invalid-map-name` | not checked | | The rules it reports as warnings: | Redocly | API Genie | Note | | --- | --- | --- | | `info-license`, `info-license-strict` | [license-defined](/docs/linter/openapi/rules/license-defined) | asks for `name`, and `url` or `identifier` | | `no-ambiguous-paths` | [paths-unique](/docs/linter/openapi/rules/paths-unique) | | | `no-duplicated-enum-values` | [schema-enum-no-duplicates](/docs/linter/openapi/rules/schema-enum-no-duplicates) | | | `no-duplicated-tag-names` | [tags-unique](/docs/linter/openapi/rules/tags-unique) | | | `no-required-schema-properties-undefined` | [schema-required-properties-defined](/docs/linter/openapi/rules/schema-required-properties-defined) | [schema-no-contradictions](/docs/linter/openapi/rules/schema-no-contradictions) adds the case of `additionalProperties: false` | | `no-unsafe-markdown` | [safe-markdown](/docs/linter/openapi/rules/safe-markdown) | | | `no-unused-components` | [unused-shared-component](/docs/linter/openapi/rules/unused-shared-component) | follows references transitively, so a component used only by an unused one is reported too | | `operation-2xx-response` | [operation-success-response](/docs/linter/openapi/rules/operation-success-response) | | | `operation-4xx-response` | not checked | [standard-response-errors](/docs/linter/openapi/rules/standard-response-errors) checks the format of the error responses that are there | | `operation-operationId` | [operation-id-defined](/docs/linter/openapi/rules/operation-id-defined) | | | `tag-description` | [tag-description-defined](/docs/linter/openapi/rules/tag-description-defined) | | | `no-invalid-media-type-examples`, `no-invalid-parameter-examples`, `no-invalid-schema-examples` | not checked | examples are not validated against their schema | | `no-illogical-composition-keywords`, `no-mixed-number-range-constraints` | not checked | [schema-no-contradictions](/docs/linter/openapi/rules/schema-no-contradictions) reports a schema that rejects every value, [schema-discriminator-defined](/docs/linter/openapi/rules/schema-discriminator-defined) a `oneOf` without discriminator | | `spec-ref-siblings` | [ref-no-siblings](/docs/linter/openapi/rules/ref-no-siblings) | since 0.12.0; OpenAPI 3.0 only, and extensions are not reported | | `no-server-example.com`, `security-scopes-defined` | not checked | | The rules Redocly leaves off by default: | Redocly | API Genie | | --- | --- | | `info-contact` | [contact-defined](/docs/linter/openapi/rules/contact-defined) | | `operation-tag-defined` | [operation-tags-declared](/docs/linter/openapi/rules/operation-tags-declared) (since 0.12.0); an operation without tags is [operation-tags-defined](/docs/linter/openapi/rules/operation-tags-defined) | | `operation-description` | [operation-description-defined](/docs/linter/openapi/rules/operation-description-defined) | | `parameter-description` | [parameter-description-defined](/docs/linter/openapi/rules/parameter-description-defined) | | `path-params-defined` | [path-parameters-defined](/docs/linter/openapi/rules/path-parameters-defined) | | `tags-alphabetical` | [tags-sorted](/docs/linter/openapi/rules/tags-sorted) | | `request-mime-type`, `response-mime-type` | [standard-media-types](/docs/linter/openapi/rules/standard-media-types), which checks that the media types are registered ones rather than a list of yours | | `required-string-property-missing-min-length` | [schema-constraints](/docs/linter/openapi/rules/schema-constraints) | | `scalar-property-missing-example` | [schema-example-defined](/docs/linter/openapi/rules/schema-example-defined) | | `operation-4xx-problem-details-rfc7807` | [standard-response-errors](/docs/linter/openapi/rules/standard-response-errors) | | `response-contains-header` | not checked; [operation-rate-limiting-defined](/docs/linter/openapi/rules/operation-rate-limiting-defined) asks for the rate-limiting headers | | `component-name-unique`, `no-http-verbs-in-paths`, `operation-singular-tag`, `paths-kebab-case`, `path-http-verbs-order`, `path-segment-plural`, `boolean-parameter-prefixes`, `array-parameter-serialization`, `response-contains-property`, `spec-strict-refs`, `spec-example-values` | not checked | The `oas2Rules` apply to Swagger 2.0 files, which API Genie lints with the [Swagger 2.0 linter](/docs/linter/swagger): `struct` is [swagger-validation](/docs/linter/swagger/rules/swagger-validation), which also reports the unresolved references, and the rules that share a name with an OpenAPI rule check the same thing. `operation-tag-defined` and `spec-ref-siblings` have no counterpart for Swagger 2.0 files. The `async3Rules` map onto the [AsyncAPI linter](/docs/linter/asyncapi) the same way. ## What the recommended ruleset adds Rules of `recommended` that Redocly's has nothing for; each has a page that says what it checks and why: - [info-defined](/docs/linter/openapi/rules/info-defined), [operation-description-defined](/docs/linter/openapi/rules/operation-description-defined), [parameter-description-defined](/docs/linter/openapi/rules/parameter-description-defined) and [tag-description-defined](/docs/linter/openapi/rules/tag-description-defined): the texts a reader of the documentation needs, and they have to say something. - [schema-format-defined](/docs/linter/openapi/rules/schema-format-defined), [schema-format-type-mismatch](/docs/linter/openapi/rules/schema-format-type-mismatch) and [schema-format-deprecated](/docs/linter/openapi/rules/schema-format-deprecated): numbers and strings say their format, and the format fits the type. - [schema-constraints](/docs/linter/openapi/rules/schema-constraints) and [schema-no-additional-properties](/docs/linter/openapi/rules/schema-no-additional-properties): strings, numbers, arrays and objects have bounds. - [schema-no-contradictions](/docs/linter/openapi/rules/schema-no-contradictions), [schema-oneof-no-overlap](/docs/linter/openapi/rules/schema-oneof-no-overlap) and [schema-conditional-effective](/docs/linter/openapi/rules/schema-conditional-effective): schemas that reject every value, `oneOf` branches a value matches twice, `if` without effect. - [standard-response-codes](/docs/linter/openapi/rules/standard-response-codes), [unambiguous-response-codes](/docs/linter/openapi/rules/unambiguous-response-codes) and [no-content-response-defined](/docs/linter/openapi/rules/no-content-response-defined): the responses an operation declares. - [operation-rate-limiting-defined](/docs/linter/openapi/rules/operation-rate-limiting-defined), [paths-max-depth](/docs/linter/openapi/rules/paths-max-depth), [paths-max-count](/docs/linter/openapi/rules/paths-max-count), [parameter-naming](/docs/linter/openapi/rules/parameter-naming) and [schema-datetime-suffix](/docs/linter/openapi/rules/schema-datetime-suffix): the headers, the shape of the URLs and the names. Outside `recommended`: [spell-check](/docs/linter/openapi/rules/spell-check) for the texts written for humans, [schema-keyword-support](/docs/linter/openapi/rules/schema-keyword-support) for the JSON Schema keywords the tools around the document ignore, and the [privacy ruleset](/docs/linter/openapi/rulesets/privacy) for credentials and personal data in URLs. `extends: [recommended, privacy]` adds the last one. ## Carry your configurable rules over A configurable rule of `redocly.yaml` names the nodes it checks with `subject` and what it asserts about them: ```yaml rules: rule/operation-summary: subject: type: Operation property: summary assertions: defined: true severity: error message: Operations must have a summary ``` It becomes a [custom rule](/docs/reference/cli/lint#custom-rules) under `commands.lint.rules`, in the format of Spectral: a JSONPath expression selects the nodes, a function checks each of them: ```yaml version: '1.0' commands: lint: extends: [recommended] rules: operation-summary: description: Operations must have a summary message: "{{property}} is missing at {{path}}" severity: error given: "$.paths[*][get,put,post,delete,options,head,patch,trace]" then: field: summary function: truthy ``` - `subject.type` becomes the `given` expression that selects the same nodes, `subject.property` the `field`, and `subject.filterInParentKeys` a member union in the expression. A `where` condition becomes a JSONPath filter ([JSONPath](/docs/reference/cli/lint#jsonpath)). - The assertions map onto the [core functions](/docs/reference/cli/lint#core-functions): `defined` is `truthy` or `defined`, `pattern` and `notPattern` are `pattern` with `match` or `notMatch`, `enum` is `enumeration`, `casing` is `casing`, `minLength` and `maxLength` are `length`, `mutuallyExclusive` is `xor`, `sortOrder` is `alphabetical`. `required`, `disallowed`, `requireAny`, `mutuallyRequired`, `nonEmpty` and `ref` have no function: write a [JavaScript function](/docs/reference/cli/lint#javascript-functions) of a few lines. - `severity` and `message` stay; `{{property}}`, `{{path}}` and `{{value}}` fill the message. A rule of a custom plugin is a JavaScript visitor over the document's node types; it is rewritten as a custom rule whose function is a JavaScript module in `functions/` next to `apigenie.yaml`. Functions run in a sandbox with no file system, network, processes or timers, and a call must finish within 5 seconds. The decorators and preprocessors of a plugin become overlays, next. ## Replace the decorators with overlays Decorators change the document on the way to the bundle and the documentation: `remove-x-internal` drops what is marked internal, `info-override` and `filter-in` or `filter-out` edit and select. API Genie writes these changes as an [OpenAPI Overlay](/docs/reference/cli/overlay), a file of actions that each select nodes with a JSONPath query and change them: ```yaml overlay: 1.0.0 info: title: Remove the internal operations version: 1.0.0 actions: - target: $.paths[*][?(@["x-internal"] == true)] remove: true - target: $.paths[?(@["x-internal"] == true)] remove: true - target: $.info update: title: Public API description: The public operations only. ``` ```sh apigenie overlay --overlay public.overlay.yaml openapi.yaml --output dist/openapi.yaml ``` The first two actions remove the operations and the path items marked `x-internal: true`, the third edits `info`; YAML comments of the input are kept. The code generators take an overlay directly, with `--overlay` or the `overlay` setting of a target ([Overlays](/docs/reference/generator#overlays)), so the public version of the document need not be written to disk for them. ## Bundle ```sh redocly bundle openapi.yaml -o dist/openapi.yaml apigenie bundle openapi.yaml --output dist/openapi.yaml ``` Both copy the schemas, parameters and responses of other local files into `components` and rewrite the references; the extension of the output file picks JSON or YAML. [bundle](/docs/reference/cli/bundle) says how API Genie names the copies. `apigenie bundle` does not keep YAML comments, and references by URL are not supported. `--dereferenced`, `--remove-unused-components`, `--keep-url-references`, `--ext` and `--metafile` have no counterpart, and decorators don't run during the bundle: apply the overlay to the bundled file in a second command. ## Disable a rule in one place Redocly keeps the problems to ignore in `.redocly.lint-ignore.yaml`, written by `--generate-ignore-file`. API Genie turns the rule off where the issue is, in the document, with `x-apigenie-lint-disable` on the object and its descendants: ```yaml paths: /legacy/export: x-apigenie-lint-disable: - operation-id-defined get: summary: Export, as it was ``` Disable a rule as close to the issue as possible; [disabling rules](/docs/reference/cli/lint#disabling-rules-in-a-document) says more. ## The report in CI The formats that keep their name: `--format stylish`, `json`, `checkstyle` and `junit` become `--formatter stylish`, `json`, `checkstyle` and `junit`. API Genie adds `sarif`, `html`, `compact`, `tap`, `unix` and `visualstudio`; Redocly's `codeframe` (its default), `codeclimate`, `summary`, `markdown` and `github-actions` have no counterpart. For GitLab, `junit` is what the merge request reads; for GitHub code scanning, `sarif` ([formatters](/docs/reference/cli/lint#formatters)). The exit status stays what it was: 1 when an error is reported, 0 on warnings alone ([exit status](/docs/reference/cli/lint#exit-status)). On GitHub Actions, the `run` step with `--format github-actions` becomes the [GitHub Action](/docs/ci/github-action), which installs the CLI and shows the issues on the lines of the pull request: ```yaml on: pull_request jobs: api: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: mykulyak/api-genie-action@v0 with: command: lint files: openapi.yaml ``` ## What stays with Redocly - `push`, `project`, `preview`, `login`, `eject` and `translate` work with the Redocly platform and its projects. `build-docs` becomes [`apigenie-generator docs`](/docs/reference/generator/docs), a static site with search and Try it out, built with npm and served from any static host. - `split` and `join` have no counterpart; `apigenie bundle` goes one way. - `generate-client` becomes [`apigenie-generator client fetch`](/docs/reference/generator/client-fetch), and `diff` becomes [`apigenie diff`](/docs/reference/cli/diff); [Migrate from oasdiff](/docs/guides/migrate-from-oasdiff) covers the move of a breaking-change check in detail. - `respect` and `generate-arazzo` run and write Arazzo workflows, which are not read; [`apigenie test`](/docs/reference/cli/test) checks a running server against the description with tests of its own format. - `proxy`, `drift` and `generate-spec` work on recorded traffic. The validating proxy of [`apigenie-server`](/docs/concepts/what-the-proxy-checks) checks live traffic against the description; inferring a description from traffic has no counterpart. - `stats`, `score` and `scorecard-classic` have no counterpart. ## Remove Redocly CLI When the two reports agree on what matters to you: delete `redocly.yaml` and `.redocly.lint-ignore.yaml`, remove `@redocly/cli` from the development dependencies, and replace the Redocly step of the pipeline with the one above. The fixes the linter offers are a `--fix` away: ```sh apigenie lint --fix openapi.yaml ``` --- # Migrate from oasdiff Source: https://apigenie.pl/docs/guides/migrate-from-oasdiff This guide moves a repository that checks the changes of its OpenAPI description with oasdiff to `apigenie diff`: the commands, the levels and the exit status, the checks as rules, deprecation and sunset dates, the report in CI, and what has no counterpart. It starts from oasdiff 1.35 and two versions of an OpenAPI file, `v1.yaml` and `v2.yaml`. You need the CLI installed; the [Quickstart](/docs/quickstart) shows how. Keep oasdiff installed until the last step, so you can compare the two reports on the same pair of files. ## What changes and what stays | | oasdiff | API Genie | | --- | --- | --- | | Breaking changes | `oasdiff breaking v1.yaml v2.yaml` | `apigenie diff v1.yaml v2.yaml` | | Changelog | `oasdiff changelog v1.yaml v2.yaml` | the same command: the changelog is the default report | | Every change | `oasdiff diff`, `oasdiff summary` | `--report detailed`, `--report status` | | Levels | `error`, `warning`, `info` | `breaking`, `non-breaking`, `non-functional` ([severities](/docs/reference/cli/diff/rules#severities)) | | Exit status | 0, unless `--fail-on ERR` or `--fail-on WARN` | 1 on a breaking change, 0 otherwise, 2 on a file it cannot read | | Checks | 780 checks by id, listed by `oasdiff checks changelog` | a rule per node type and property, such as `operation.parameters.add_item` ([rules](/docs/reference/cli/diff/rules)) | | Configuration | `.oasdiff.yaml`, `--severity-levels`, `--err-ignore`, `--warn-ignore` | `apigenie.yaml`, section `commands.diff` ([Configuration](/docs/reference/cli/diff#configuration)) | | Deprecation | `x-sunset`, `--deprecation-days-stable`, `--deprecation-days-beta` | `x-sunset`, the `sunset_passed` condition, `--today` | | Report formats | `--format text`, `markdown`, `html`, `json`, `junit`, `githubactions`, `yaml`, ... | `--formatter stylish`, `markdown`, `html`, `json`, `unix`, `visualstudio` | | Standards | OpenAPI 3.x | OpenAPI 3.x, Swagger 2.0, AsyncAPI 3.x, Protobuf and GraphQL, each with rules of its own | | Version | `api-major-version-not-bumped` reports a missing bump | `--update-version` writes the version the changes call for | | History | two files at a time | `apigenie changelog openapi.yaml` reads the versions from git ([changelog](/docs/reference/cli/changelog)) | ## Run both on the same pair Between `v1.yaml` and `v2.yaml`, `GET /orders` gets a required `status` parameter, the `Order` schema of the responses loses its `legacyCode` property, and `GET /legacy/export`, deprecated with `x-sunset: "2026-09-30"`, is removed after that date. ```sh oasdiff breaking v1.yaml v2.yaml apigenie diff v1.yaml v2.yaml ``` ```text 1 changes: 1 error, 0 warning, 0 info error [new-required-request-parameter] at v2.yaml in API GET /orders added the new required `query` request parameter `status` ``` ```text v2.yaml 45 7 non-breaking Removed operation GET /legacy/export 10 7 breaking Modified operation GET /orders 10 7 breaking Added parameter status in query 10 7 breaking Modified response code 200 33 7 breaking Modified operation GET /orders/{orderId} 33 7 breaking Modified response code 200 ``` Both rate the required parameter breaking, and both let the deprecated operation go: oasdiff leaves the removal out of its breaking report, API Genie lists it as non-breaking. The removed property is where they differ. oasdiff rates `response-optional-property-removed` as `info`; the [recommended rules](/docs/reference/cli/diff/rules#openapi) rate a property removed from a response as breaking, since a client may read it, unless the property was deprecated and its `x-sunset` date has passed. `--report detailed` names the rule behind each line, `schema.properties.remove_item` in the `response` layer here, so a disagreement is settled in the configuration, next. The exit status differs too: `apigenie diff` exits with 1 on any breaking change, where oasdiff needs `--fail-on`. ## Replace the configuration The severity of every change is a rule, so the flags and files that tune oasdiff become settings of `commands.diff` in `apigenie.yaml` at the root of the repository. Here a changed title is non-functional rather than breaking, and a removed response property is non-breaking, as oasdiff has it: ```yaml version: '1.0' commands: diff: extends: [recommended] rules: info: title: non_functional response: schema: properties: remove_item: non_breaking ``` - `--fail-on ERR` has no flag: the command exits with 1 on a breaking change. oasdiff's warnings are changes that may break a client, such as `request-parameter-removed`; the recommended rules rate most of them breaking already, so `--fail-on WARN` is the default exit status too. A change rated too low or too high gets another severity in `rules`, or in `request` and `response` for the schemas of parameters and bodies and those of responses ([direction](/docs/reference/cli/diff/rules#direction)). - `--severity-levels`, `--err-ignore` and `--warn-ignore` match the lines of a report; a rule names the property instead. `none` leaves a change out of the status and the changelog, `non_functional` keeps it in the changelog without failing the check. - `--match-path`, `--unmatch-path` and `--filter-extension` become `overrides`, a list of rules applied to the locations that match a JSON pointer pattern, where `*` matches a part of a segment and `**` any number of segments. These leave the internal paths out: ```yaml overrides: - where: location: /paths/~1internal~1*/** rules: pathItem: operations: none ``` - `--exclude-elements description,summary,examples,extensions` is close to the default: descriptions, summaries, examples and extensions are `non_functional`, in the changelog and never failing. `none` on the property, `operation: {description: none}`, leaves them out. - `--auto-upgrade` has no counterpart: a 3.0 and a 3.1 document are compared as they are, and the changed version is one more change, rated breaking by the `openapi` rule of the `openapi` node; `none` on it leaves it out. - `--flatten-allof`, `--flatten-params`, `--include-path-params`, `--composed`, `--prefix-base`, `--strip-prefix-base`, `--stability-level`, `--attributes`, `--lang` and `--template` have no counterpart. ## Deprecate, then remove Both tools read `x-sunset`, so the deprecations already in the document carry over. What is checked differs: - oasdiff reports deprecating an operation without a sunset date (`api-deprecated-sunset-missing`), a sunset date closer than `--deprecation-days-stable` or `--deprecation-days-beta` (`api-sunset-date-too-small`), and a removal before the date (`api-removed-before-sunset`). - API Genie rates deprecating as non-breaking, with or without a date, and the removal by the `sunset_passed` condition: a deprecated operation, path item, parameter, component schema, response property or request enum value may go once its `x-sunset` date is on or before the date of the comparison, and is breaking before it. How far ahead the date is set is for the reviewer of the pull request, not a rule. `--today 2027-02-01` runs the comparison as of another date, to see a removal pass before then, and [`apigenie evolve plan`](/docs/reference/cli/evolve) writes the deprecations and the removal in two waves. [Accepting a breaking change](/docs/reference/cli/diff/rules#accepting-a-breaking-change) lists the other ways forward. ## The checks, as rules The oasdiff checks most pull requests meet, and the rule that rates the same change; each rule is a line of the [OpenAPI tables](/docs/reference/cli/diff/rules#openapi), where the configuration changes it. Checks whose id differs only by the kind of element, such as `request-property-removed` and `response-property-removed`, follow the same rows. | oasdiff | Level | API Genie | Note | | --- | --- | --- | --- | | `api-removed-without-deprecation`, `api-path-removed-without-deprecation` | error | `pathItem.operations.remove_item`, `paths.remove_item` | breaking, unless `sunset_passed` | | `api-removed-before-sunset`, `api-path-removed-before-sunset` | error | the same | | | `api-path-removed-with-deprecation` | info | the same | non-breaking once the date has passed | | `api-deprecated-sunset-missing`, `api-sunset-date-too-small` | error | not checked | `operation.deprecated` is non-breaking | | `endpoint-added` | info | `pathItem.operations.add_item` | non-breaking | | `new-required-request-parameter` | error | `operation.parameters.add_item` | breaking when `required` | | `new-optional-request-parameter` | info | the same | non-breaking otherwise | | `request-parameter-removed` | warning | `operation.parameters.remove_item` | breaking, unless `sunset_passed` | | `request-parameter-became-required` | error | `parameter.required` | | | `request-parameter-type-changed`, `response-property-type-changed` | error | `schema.type` | breaking in both directions | | `request-property-became-required`, `request-property-became-required-with-default` | error | `schema.required.add_item` in `request` | the default does not matter | | `response-required-property-removed` | error | `schema.properties.remove_item` in `response` | breaking, unless `sunset_passed` | | `response-optional-property-removed` | info | the same | breaking too; the configuration above lowers it | | `response-property-became-optional` | error | `schema.required.remove_item` in `response` | | | `response-success-status-removed` | error | `responses.remove_item` | every removed response code is breaking | | `api-security-removed` | error | `operation.security.remove_item` | | | `api-operation-id-removed` | info | `operation.operationId` | breaking: generated clients name their functions after it | | `api-major-version-not-bumped` | info | `--update-version` | writes the version instead of checking it | ## The report in CI On GitHub Actions, the `oasdiff/oasdiff-action/breaking` step with its `base` and `revision` becomes the [GitHub Action](/docs/ci/github-action) with `command: diff`. It compares each file with its version at the base commit of the pull request and shows the changes on its lines; `base` picks another commit, branch or tag, `base-file` another file of the repository, and `report` one of the three reports: ```yaml on: pull_request jobs: api: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: mykulyak/api-genie-action@v0 with: command: diff files: openapi.yaml ``` Elsewhere, take the base version from git and compare the two files; the exit status fails the job on a breaking change: ```sh git show main:openapi.yaml > main.yaml apigenie diff main.yaml openapi.yaml ``` The formats that keep their name: `--format markdown`, `html` and `json` become `--formatter markdown`, `html` and `json`; `text`, the default, is `stylish`, the default. API Genie adds `unix` and `visualstudio`; `githubactions` is what the action's annotations do, and `junit`, `yaml`, `singleline` and `markup` have no counterpart. A script reads the status alone: ```sh apigenie diff --report status --formatter json main.yaml openapi.yaml ``` ```json { "formatVersion": 1, "status": "breaking" } ``` ## Release notes `oasdiff changelog v1.yaml v2.yaml --format markdown` becomes `apigenie diff --formatter markdown v1.yaml v2.yaml`, the changelog of two files. For the notes of a release, [`apigenie changelog`](/docs/reference/cli/changelog) reads the versions of the file from git instead, with an entry per commit that changes the API or, with `--revisions tags`, per release tag, each change rated with the same rules. ## What stays with oasdiff - `oasdiff diff` prints every difference as YAML or JSON, without a severity. `--report detailed --formatter json` is the nearest: every change with its position, the rule and the severity. - `oasdiff summary` counts the differences by kind; `--report status` says only whether a change is breaking. - `flatten`, `upgrade`, `breaking-files` and the git diff driver have no counterpart; `validate` is [`apigenie lint`](/docs/reference/cli/lint). - `--composed`, which compares every file matching two globs as one API, has no counterpart: compare the files one pair at a time, or [bundle](/docs/reference/cli/bundle) each version first. - `--lang` translates the messages; API Genie's reports are in English. ## Remove oasdiff When the two reports agree on what matters to you: delete `.oasdiff.yaml` and the ignore files, remove the oasdiff binary or image from the pipeline, and replace its step with the one above. Before the next release, let the differ write the version the changes call for: ```sh apigenie diff --update-version main.yaml openapi.yaml ``` --- # Lint CAMARA APIs Source: https://apigenie.pl/docs/guides/industry/lint-camara-apis This guide sets up `apigenie lint` for a repository of the [CAMARA project](https://camaraproject.org): the configuration, the first run on an API, and the check on every pull request. It uses the layout of a CAMARA API repository: the APIs in `code/API_definitions/`, and the common files they reference in `code/common/`. The [`camara`](/docs/reference/cli/lint#the-camara-ruleset) ruleset is in API Genie since 0.12.0. You need the CLI installed; the [Quickstart](/docs/quickstart) shows how. ## Configure the repository Put an `apigenie.yaml` at the root of the repository: ```yaml # yaml-language-server: $schema=https://apigenie.pl/schemas/apigenie-config/latest.json version: '1.0' commands: lint: extends: [camara] bundle: true ``` - `camara` is the ruleset CAMARA lints with for Commonalities r4, its `.spectral-r4.yaml` with its 41 rules and 14 JavaScript functions. It ships with API Genie, so the repository needs no copy. - [`bundle: true`](/docs/reference/cli/lint#configuration) brings the common files an API references, such as `../common/CAMARA_common.yaml`, into it before the rules run. An issue found in a common file is reported in that file, at its line. ## Lint an API Run the linter from the root of the repository, which is where it finds `apigenie.yaml`: ```sh apigenie lint code/API_definitions/quality-on-demand.yaml ``` ```text /home/me/QualityOnDemand/code/common/CAMARA_common.yaml 135:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 139:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 182:5 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted /home/me/QualityOnDemand/code/common/CAMARA_event_common.yaml 52:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 58:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 5 issues (0 errors, 5 warnings) ``` Each line gives the position, the severity, the message and the rule. The API passes every `camara-*` rule. The 5 warnings come from the OWASP rules CAMARA's file turns on, in the common files the API references. A CAMARA rule keeps its id, such as `camara-properties-descriptions`, so CAMARA's documentation of it still applies. Errors make the command exit with status 1. `--fix` ignores `bundle: true`: it lints and fixes each file as it is. Lint every API of the repository at once: ```sh apigenie lint code/API_definitions/*.yaml ``` ```text /home/me/QualityOnDemand/code/common/CAMARA_common.yaml 135:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 139:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 182:5 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted /home/me/QualityOnDemand/code/common/CAMARA_event_common.yaml 52:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 58:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 5 issues (0 errors, 5 warnings) /home/me/QualityOnDemand/code/common/CAMARA_common.yaml 135:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 139:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 182:5 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted /home/me/QualityOnDemand/code/common/CAMARA_event_common.yaml 52:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 58:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 5 issues (0 errors, 5 warnings) ``` The repository has two APIs, `quality-on-demand.yaml` and `qos-provisioning.yaml`, and both reference the same common files. Each API is linted on its own and gets its own report, so the 5 warnings in the common files appear twice, once for each API. ## Add API Genie's own checks CAMARA's file also extends Spectral's `spectral:oas` rules, which API Genie doesn't have. API Genie's `recommended` ruleset has counterparts of about two thirds of them, and checks of its own that CAMARA's run doesn't make: ```yaml commands: lint: extends: [recommended, camara] bundle: true ``` Expect more findings: on `quality-on-demand.yaml` this reports 141 issues, 64 of them errors, where `extends: [camara]` alone reports 5 warnings and no errors. Turn off under `rules` what your team doesn't follow. ## Change a rule `rules` changes a CAMARA rule as it changes any other, by its id. Turn one off, or change its severity: ```yaml commands: lint: extends: [camara] bundle: true rules: camara-operationid-casing-convention: off camara-path-param-id: error ``` `[camara, all]` in `extends` also applies the two rules CAMARA's file leaves off: the deprecated `camara-discriminator-use`, and `camara-language-avoid-telco`, which reports nothing. ## Add the check to pull requests The [GitHub Action](/docs/ci/github-action) installs the CLI and runs `apigenie lint` with the repository's `apigenie.yaml`. Add it to a workflow in `.github/workflows/`: ```yaml on: pull_request jobs: api: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: mykulyak/api-genie-action@v0 with: command: lint files: code/API_definitions/*.yaml ``` The step fails when an error is reported, and each issue shows as an annotation on its file in the pull request. With several APIs, a warning in a common file shows once for each API. On QualityOnDemand the step passes: it reports only the 5 warnings. The step runs CAMARA's Spectral rules with no Node.js and no ruleset fetched from [camaraproject/tooling](https://github.com/camaraproject/tooling/tree/main/linting/config). CAMARA's other checks, its Python checks, yamllint and Gherkin lint, stay where they are. To send the issues to GitHub code scanning instead, run the [GitHub Action](/docs/ci/github-action) without `command`, which only installs the CLI. Then write the report with the [SARIF formatter](/docs/reference/cli/lint#sarif) and upload it with `github/codeql-action/upload-sarif`. ## What differs from CAMARA's Spectral run On the two APIs of QualityOnDemand, Spectral 6.17.0 with `.spectral-r4.yaml` and API Genie with `extends: [camara]` report the same 5 warnings at the same lines. Both exit with status 0. They print them differently: - Spectral reports a column after the key, `135:14` for the first warning; API Genie reports the key's first column, `135:9`. - Spectral prints a common file once per run. API Genie prints a report for each API, so a common file appears once for each API that references it, as in the output of the second command. In a repository whose APIs trip the `spectral:oas` rules that CAMARA's file extends, Spectral reports those issues and API Genie doesn't: it doesn't have those rules, and says nothing about skipping them. The one exception is `operation-success-response`, which CAMARA's file turns on and API Genie has under that id. `recommended` has counterparts of about two thirds of the others. The editor and the VS Code extension don't run the ruleset's JavaScript functions. There, `extends: [camara]` is an error that begins `Unknown ruleset camara`, and the default rules apply. ## Next steps - [The `camara` ruleset](/docs/reference/cli/lint#the-camara-ruleset) and the [`owasp`](/docs/reference/cli/lint#the-owasp-ruleset) ruleset it extends. - [Migrate from Spectral](/docs/guides/migrate-from-spectral), for a repository with rules of its own. - [Catch breaking changes in CI](/docs/guides/catch-breaking-changes-in-ci), to rate what each version of an API changes for its clients. --- # CAMARA's rules, without the Spectral setup Source: https://apigenie.pl/for/industry/telecom API Genie for telecom. A CAMARA API repository lints in CI with Spectral, a Node toolchain and a ruleset fetched from another repository. With API Genie, two keys in apigenie.yaml run CAMARA's own rules. The camara ruleset and the bundle key come with API Genie 0.12.0, not released yet. ## The programmes, and what runs for each - [CAMARA](/docs/reference/cli/lint.md#the-camara-ruleset): The Linux Foundation project that defines network APIs for operators. `camara` is the 41 rules and 14 functions of its `.spectral-r4.yaml`, for Commonalities r4, shipped with API Genie. - GSMA Open Gateway: GSMA's programme through which operators expose CAMARA APIs to developers. Its APIs are defined in CAMARA, so `camara` checks the versions written for Commonalities r4. - [TM Forum Open APIs](/use-cases/lint-and-format): TM Forum's telecom business APIs, published as Swagger 2.0 and OpenAPI documents. API Genie lints, diffs and mocks them, and generates code from them (Swagger 2.0 since 0.12.0), as for any other. It has no TM Forum ruleset. ## A CAMARA repository, linted CAMARA's Quality on Demand API references `../common/CAMARA_common.yaml`, and `bundle: true` brings the common files in before the rules run. The API passes every `camara-*` rule; the 5 warnings come from the OWASP rules CAMARA's file turns on, and are reported in the common files, at their lines. ```yaml version: "1.0" commands: lint: extends: [camara] bundle: true ``` ```shellsession $ apigenie lint code/API_definitions/quality-on-demand.yaml /home/me/QualityOnDemand/code/common/CAMARA_common.yaml 135:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 139:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 182:5 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted /home/me/QualityOnDemand/code/common/CAMARA_event_common.yaml 52:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 58:9 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 5 issues (0 errors, 5 warnings) ``` ## Spectral's findings on Quality on Demand, line for line On the 2 API files of camaraproject/QualityOnDemand `6e21c48` (5 November 2026), Spectral 6.17.0 with `.spectral-r4.yaml` from camaraproject/tooling `e481489`, and API Genie at `bce7edb63` (before 0.12.0) with `extends: [camara]` and `bundle: true`, report the same 5 warnings at the same lines, and both exit with 0. API Genie prints a common file's warnings under each API that references it, so the 2 files show them twice, and its columns start at the key, where Spectral's start after it. `recommended` adds API Genie's own checks: 141 issues, 64 of them errors, on `quality-on-demand.yaml`. ## What it covers - [CAMARA's rule ids](/docs/reference/cli/lint.md#the-camara-ruleset): `camara-properties-descriptions` stays `camara-properties-descriptions`, so a team's notes and CAMARA's documentation still apply, and `rules` changes any of them. - [OWASP rules, as CAMARA sets them](/docs/reference/cli/lint.md#the-owasp-ruleset): `camara` extends the `owasp` ruleset: 32 rules for 8 of the 10 OWASP API Security Top 10 risks. CAMARA's settings apply as upstream: 15 rules off, 4 made warnings, the 401 rule made an error. - [The common files](/docs/reference/cli/lint.md#configuration): `bundle: true` follows the references to `CAMARA_common.yaml` and the other common files on every run except under `--fix`. - [In pull requests](/docs/ci/github-action.md): The GitHub Action runs `apigenie lint` with your `apigenie.yaml`, shows the issues as annotations on the pull request's files, and fails the step on an error. - [Reports for CI](/docs/reference/cli/lint.md#formatters): `--formatter sarif` for code scanning, and JUnit, checkstyle and JSON for the rest. - [Breaking changes](/use-cases/breaking-changes): `apigenie diff --bundle` rates what a new version of a CAMARA API, its common files included, does to its clients. ## What it doesn't do - Spectral's part only: API Genie replaces the Spectral step of CAMARA's validation. Its Python checks, yamllint and Gherkin lint aren't in API Genie. - [Spectral's OAS rules don't run](/docs/guides/migrate-from-spectral.md#the-rules-of-spectraloas-by-name): The `spectral:oas` rules that CAMARA's file extends don't run, and nothing reports that they're skipped; only `operation-success-response` turns on API Genie's rule of that id. `recommended` has API Genie's counterparts of about two thirds of them, mapped in Migrate from Spectral. - Fixed severities: `camara` uses the severities of CAMARA's file. CAMARA's Python validator sets them by the API's release status; API Genie doesn't, so an error here may not block a CAMARA release, and the other way round. - Pinned to one tooling commit: `camara` is CAMARA's file as of 4 November 2026, for Commonalities r4. For a newer file, or one for an earlier Commonalities release, copy it with its `lint_function` folder into the repository and name its path in `extends`. - The command line only: The ruleset's JavaScript functions run in the CLI and the GitHub Action. In the editor and the VS Code extension, `extends: [camara]` is an `Unknown ruleset camara` error, and the default rules apply. ## Step by step - [Lint CAMARA APIs](/docs/guides/industry/lint-camara-apis.md): Check the APIs of a CAMARA repository with CAMARA's own rules, locally and in every pull request, without a copy of its ruleset or a Node toolchain. --- # How the mock picks a response Source: https://apigenie.pl/docs/concepts/how-the-mock-picks-a-response `apigenie-server openapi.yaml` answers every request from the document, without a line of code. This page explains the decisions behind one answer, in the order the server takes them, so that you can predict what a request gets and change it where you need to. The [Responses](/docs/reference/server/responses) page of the reference states the same rules in short. The examples run against this document, saved as `pets.yaml` and served with `apigenie-server pets.yaml`; `curl -i` shows the headers that say what was decided. ```yaml openapi: 3.1.0 info: {title: Pets, version: 1.0.0} servers: - url: https://api.example.com/v1 paths: /pets/{id}: get: operationId: getPet parameters: - {name: id, in: path, required: true, schema: {type: integer}} responses: "200": description: The pet content: application/json: schema: {$ref: "#/components/schemas/Pet"} examples: cat: {value: {id: 1, name: Tom, kind: cat}} dog: {value: {id: 2, name: Rex, kind: dog}} "404": description: No such pet default: description: An error components: schemas: Pet: type: object required: [id, name] properties: id: {type: integer} name: {type: string} kind: {type: string, enum: [cat, dog]} ``` ## 1. The route The paths of the document are served under the path of its first server, `/v1` here, and as they are: `GET /v1/pets/1` and `GET /pets/1` both reach `getPet`. `--base-path` replaces the prefix, and `server.strict_base_path` in the configuration serves the paths only under it. When a literal path and a templated one both match, the literal one wins: `/pets/mine` over `/pets/{id}`. A path the document doesn't have is answered with 404, a method the path doesn't declare with 405 and an `Allow` header, both as [problem details](https://www.rfc-editor.org/rfc/rfc9457): ```text $ curl -i -X DELETE http://127.0.0.1:4010/v1/pets/1 HTTP/1.1 405 Method Not Allowed Content-Type: application/problem+json Allow: GET ``` ## 2. The request is checked Before an answer is chosen, the request is checked against its operation: the parameters, the body and the security requirements. A request that doesn't match gets 422 with the problems instead of an answer, and one without the credentials a security requirement asks for gets 401: ```text $ curl -i http://127.0.0.1:4010/v1/pets/abc HTTP/1.1 422 Unprocessable Content Content-Type: application/problem+json { "type": "https://apigenie.pl/mock/errors#invalid-request", "title": "The request does not match the specification", "status": 422, "detail": "path.id: expected type integer, found string", ... ``` `validation.request: log` in the configuration reports such a request and answers it anyway. The `__` query parameters of the next step are removed before the check, so `?__code=404` is not an unknown parameter. [Validation and security](/docs/reference/server/validation) lists what is checked. ## 3. Who answers Several sources can answer a request. From the one that wins to the last resort: 1. **A script.** The `onRequest` hook of a [script](/docs/reference/server/scripts) that returns a response answers before the document's operations. 2. **The request itself.** The `Prefer` header, or the `__` query parameters, ask for a status, a named example, a generated body, a delay or a dropped connection: `Prefer: code=404`, `?__example=dog`. 3. **Scenarios and overrides.** The rules of the scenarios that are on (`--scenario`, the configuration, `x-apigenie-mock` in the document, the admin API) and the `operations` overrides of the configuration set the status, an example, a body or headers for the requests they match. 4. **Stubs.** With `--stubs DIR`, a recorded exchange whose method, path, query and body match answers (see [Record and replay](/docs/reference/server/contract-testing)). 5. **The document.** Its examples, else values generated from its schemas. Each layer sets what it names and leaves the rest to the next. With this scenario on, `getPet` answers 503: ```yaml # apigenie-server.yaml version: "1.0" scenarios: outage: description: the backend is down rules: - match: {operationId: getPet} status: 503 headers: {Retry-After: "30"} ``` ```text $ apigenie-server pets.yaml --scenario outage $ curl -i http://127.0.0.1:4010/v1/pets/1 HTTP/1.1 503 Service Unavailable Retry-After: 30 X-Apigenie-Mock-Operation: getPet X-Apigenie-Mock-Source: scenario:outage ``` A request with `Prefer: code=200` still gets a 200 with the `cat` example, because the request's own ask comes first; one with `?__example=dog` gets the 503, because the scenario set a status that has no content, so there is no example to pick. ## 4. The status When nothing above sets the status, the operation's responses decide: the lowest 2xx response, else `2XX`, else the lowest declared status, else `default`. For `getPet` that is 200. An operation with `204`, `202` and `400` answers 202; one with `2XX` alone answers 200; one with `404` and `500` only answers 404. A status the request asks for has to be declared, by its code, a range such as `4XX`, or `default`: `Prefer: code=418` gets a 418 here, because `default` covers it, and a 500 from an operation without `default`, whose detail says which statuses the operation has. ## 5. The body The body is picked for the status, in this order: - **The media type.** Content negotiation follows the request's `Accept`; a request that accepts only `text/plain` gets 406. Without an `Accept`, or with `*/*`, the response takes the media type of the request's body when it has one. - **An example, else a generated value.** In the default static mode the media type's `example`, else its first named example (`cat` here), else the schema's `example` answer. What has none is generated from the schema, and `--dynamic` (or `responses.mode: dynamic`) generates every body. Generated values respect the types, the formats of the [format registry](/docs/reference/cli/formats), patterns, lengths, ranges, `enum`, `const`, `allOf`, `oneOf`, `readOnly` and `writeOnly`; `x-faker` on a property names the generator of its values ([Scenarios and extensions](/docs/reference/server/scenarios)). - **XML.** A value for `application/xml`, `text/xml` or a `+xml` media type is written as XML, as the schema's `xml` objects describe it ([XML bodies](/docs/reference/server/validation#xml-bodies)). ```text $ curl http://127.0.0.1:4010/v1/pets/1 {"id":1,"name":"Tom","kind":"cat"} $ curl 'http://127.0.0.1:4010/v1/pets/1?__example=dog' {"id":2,"name":"Rex","kind":"dog"} $ curl -H 'Prefer: dynamic=true' http://127.0.0.1:4010/v1/pets/1 {"id":179,"name":"necessitatibus sint qui q"} ``` A status without content answers with an empty body, whatever example the request asks for. ## 6. The headers The headers the response declares are filled in from their examples or schemas. Two headers of the mock's own say what was decided, so that a surprising answer can be traced: | Header | Says | | --- | --- | | `X-Apigenie-Mock-Operation` | The operation that answered: `getPet`. | | `X-Apigenie-Mock-Source` | Where the answer came from: `example:cat`, `schema-example`, `generated`, `scenario:outage`, `stub:getPet-1`, `empty` for a status without content, `proxy` for a real server's answer. | The log prints the same two facts on each line, and the [dashboard](/docs/reference/server/dashboard) shows them per operation. `headers.diagnostics: false` in the configuration leaves the two headers out. ## See also - [Responses](/docs/reference/server/responses): the rules in short, the `Prefer` header and the network simulation. - [Scenarios and extensions](/docs/reference/server/scenarios): the rules of a scenario, `x-apigenie-mock` and `x-faker`. - [Validation and security](/docs/reference/server/validation): what step 2 checks, and XML bodies. - [What the validating proxy checks](/docs/concepts/what-the-proxy-checks): the same server in front of a real one. - [Mock and contract-test an API](/docs/guides/mock-and-contract-test-an-api): the guide. --- # What the validating proxy checks Source: https://apigenie.pl/docs/concepts/what-the-proxy-checks With `--proxy-to`, `apigenie-server` mocks nothing: every request goes to the real server, and the request and the server's response are both checked against the document. Point a test suite, a frontend or a load test at the proxy, and the traffic becomes a contract test. This page explains what is checked and what happens with a problem; the [Contract testing](/docs/reference/server/contract-testing) page of the reference lists every check. ```sh apigenie-server pets.yaml --proxy-to http://localhost:8080 --report contract.json --fail-on errors ``` The examples use the `pets.yaml` of [How the mock picks a response](/docs/concepts/how-the-mock-picks-a-response) and a server on port 8080 that answers `GET /v1/pets/1` with `{"id":"1","name":"Tom"}`: an `id` that is a string where the schema says integer. ## What goes through The server gets the request as the client sent it, without the mock's `__` query parameters and `X-Apigenie-Mock-*` headers, with `Via` and the `X-Forwarded-*` headers added, and with `Accept-Encoding: identity` so that the body of the answer can be read. A path in the target (`http://localhost:8080/api`) goes before the request's path. Scenarios, examples and generated values play no part: the answer is the server's, with the proxy's findings in the headers. ## Three groups of checks Each problem is a **violation** with a check, a severity and a location. The checks fall into three groups: - **The request.** Is there an operation for the method and path (`request.path-or-method.unknown`)? Does each parameter match its schema (`request.path.incompatible`, `request.query.incompatible`, ...), and is every required one there? Is the body's media type declared, can the body be parsed, does it match its schema (`request.content-type.incompatible`, `request.body.malformed`, `request.body.incompatible`)? Are there credentials for a security requirement (`request.authorization.missing`)? Is a deprecated operation or parameter used (`request.operation.deprecated`)? - **The response's status and media type.** Does a response cover the status, by its code, a range or `default` (`response.status.unknown`, `response.status.default`)? Is the media type one of the declared ones (`response.content-type.incompatible`)? A 5xx from the server is noted (`response.status.server-error`). - **The response's body and headers.** Does the body match the schema of its status and media type (`response.body.incompatible`)? Is there a body where none is declared (`response.body.unexpected`)? Can it be checked at all (`response.body.unvalidatable`, for binary and compressed bodies)? Is every required header there and valid (`response.header.incompatible`)? The answer to the example request carries one violation: ```text $ curl -i http://127.0.0.1:4010/v1/pets/1 HTTP/1.1 200 OK X-Apigenie-Mock-Source: proxy X-Apigenie-Mock-Operation: getPet X-Apigenie-Mock-Violations: 1 X-Apigenie-Mock-Violations-Detail: [{"location":["response","body","/id"],"check":"response.body.incompatible","code":"type","severity":"error","message":"expected type integer, found string"}] {"id":"1","name":"Tom"} ``` A request for `GET /v1/health`, which the document doesn't describe, is forwarded too, with a `request.path-or-method.unknown` warning; `proxy.unknown_routes: reject` in the configuration answers 404 instead. ## Severities A violation is an **error**, a **warn** or an **info**, as the table of the reference sets it: a body that doesn't match its schema is an error, an undeclared query parameter a warning, a deprecated operation a note. Only errors can fail a run or block traffic. `contract.severity` in the configuration changes the severity of a check, or turns it off with `ignore`: ```yaml contract: severity: response.header.undefined: warn # off by default response.status.default: ignore ``` ## Report, or enforce By default the proxy reports and changes nothing: the server's answer goes back as it came, with the violations in `X-Apigenie-Mock-Violations` and `X-Apigenie-Mock-Violations-Detail`, in the log and in the report. Test suites send invalid requests on purpose, to see the server refuse them, and the proxy must not get in their way. `--strict` (or `enforce` in `validation.request` and `validation.response`) turns errors into answers. A request with an error doesn't reach the server: 400 for a body that can't be parsed, 401 or 403 for missing or rejected credentials, 415 for an undeclared media type, 422 otherwise, each with the problems. A response with an error is replaced by a 502 that says what was wrong and what the server answered: ```text $ curl -i http://127.0.0.1:4010/v1/pets/1 HTTP/1.1 502 Bad Gateway X-Apigenie-Mock-Source: mock X-Apigenie-Mock-Operation: getPet X-Apigenie-Mock-Upstream-Status: 200 ... "detail": "response.body/id: expected type integer, found string", ``` Warnings and notes never block anything. A server that can't be reached is a 502 of its own, one that doesn't answer in time a 504. In fallback mode (`--proxy-mode fallback`) the mock answers such requests itself, as it would without a server, and says so with `X-Apigenie-Mock-Upstream-Status`. ## How a run ends When the server stops (Ctrl+C, or `POST /__apigenie/shutdown` from the test script), it prints a summary, writes the `--report` JSON and the `--report-junit` XML, and exits with 5 when the gate isn't met: `--fail-on errors` (or `warnings`) for the violations, `--min-coverage PERCENT` for the part of the document the traffic exercised. ```text Contract: 2 requests (0 undocumented), 1 errors, 1 warnings Coverage: 33.3% of 9 branches, 1 of 2 operations not tested: POST /pets (createPet) error GET /pets/{id}: response.body/id: expected type integer, found string (type; response.body.incompatible) warn GET /pets/{id}: response.body: the 404 response declares no content, but has a body of 23 bytes (unexpected; response.body.unexpected) Contract failed: 1 error violations; coverage 33.3% is below 80.0% ``` **Coverage** counts, per operation, the operation itself, its request body (seen with a 2xx or 3xx answer) and each declared response. With a `POST /pets` operation added to `pets.yaml`, declaring a request body and the responses `201`, `400` and `default`, the document has nine branches: four for `getPet` (the operation, `200`, `404` and `default`) and five for `createPet`. Two requests to `getPet`, answered 200 and 404, cover three of them. An operation is `covered`, `partial` or `not-tested`. The JSON report has the summary, the operations with their requests, the responses seen and missing and their violations, the undocumented routes, and each distinct violation with its count; its `formatVersion` is under the [compatibility promise](/docs/reference/cli/compatibility#versioned-json-outputs). The JUnit file has one test case per operation, skipped when not tested and failed with error violations, and one for the coverage threshold, which CI systems show as test results. `GET /__apigenie/contract` returns the report while the server runs. ## The same checks elsewhere - [`apigenie test`](/docs/reference/cli/test) sends the requests itself, from `.http` files or generated from the document, and reports the same checks. - `--record-dir` writes the exchanges the server answered as stubs for the mock, and `--record-har` writes the session as a HAR file ([Record and replay](/docs/reference/server/contract-testing)). - A GraphQL schema and the WebSocket, MQTT and HTTP channels of an AsyncAPI document are checked the same way, with checks of their own ([GraphQL](/docs/reference/server/graphql#contract-testing-of-a-graphql-api), [AsyncAPI](/docs/reference/server/asyncapi#contract-testing-of-a-websocket-api)). ## See also - [Contract testing](/docs/reference/server/contract-testing): every check with its severity, the report's members, fallback mode, stubs and HAR. - [Server configuration](/docs/reference/server/configuration): `validation`, `proxy` and `contract`. - [How the mock picks a response](/docs/concepts/how-the-mock-picks-a-response): the same server without a real one behind it. - [Mock and contract-test an API](/docs/guides/mock-and-contract-test-an-api): the guide. --- # Where apigenie.yaml is found and how settings merge Source: https://apigenie.pl/docs/concepts/where-the-configuration-is-found One file, `apigenie.yaml`, configures `apigenie`, `apigenie-generator`, `apigenie-server` and `apigenie-catalog`: the rules of the linter and the differ, the layout of the formatter, the specifications of the catalog, the options of each code generator and the settings of the server. The `lint`, `check_breaking_changes`, `changelog` and `format` tools of [`apigenie-mcp`](/docs/reference/cli/mcp) read it through `apigenie`. This page explains how a command finds the file and how a setting ends up with its value; the [Configuration](/docs/reference/cli/configuration) page of the reference lists the settings. ## Which file is read Without `--config`, a command looks for the first of `apigenie.yaml`, `apigenie.yml`, `apigenie.json`, `.apigenie.yaml`, `.apigenie.yml` and `.apigenie.json` in the current directory, then in each parent, and stops at the root of the Git repository, the directory with `.git`. One file at the root of the repository is found from every directory of it: ```text shop/ .git/ apigenie.yaml <- read from shop/ and from shop/services/orders/ services/ orders/ openapi.yaml ``` ```sh cd services/orders apigenie lint openapi.yaml # reads shop/apigenie.yaml ``` Two options change the lookup: - `--config FILE` reads FILE and nothing else. The file of the repository is left alone, and the two are never merged. - `--no-config` reads no file: the command runs with its defaults, as it does when no file is found. `apigenie-server` has a file of its own, `apigenie-server.yaml` (or `apigenie-mock.yaml`, its former name), looked for in the current directory before the shared file. In it the settings are at the top level; in `apigenie.yaml` they are under `commands.mock` ([server configuration](/docs/reference/server/configuration)). ## What is checked before a setting is read Every file is checked against the JSON Schema of the configuration before any command reads it. A key the schema doesn't know, a value of the wrong type or one outside its allowed values stops the command with exit status 2, the position and the JSON pointer of the value, and a suggestion for a misspelled name: ```text $ apigenie lint openapi.yaml /home/me/shop/apigenie.yaml:4:12: /commands/lint/rulez: unknown property 'rulez'; did you mean 'rules'? ``` A broken file found in a parent directory stops every command run below it, not only the one whose section is wrong. [`apigenie config check FILE`](/docs/reference/cli/config) checks a file without running anything, and the `$schema` comment on the first line of the reference's example lets an editor check it while you type. `version` has to be the string `'1.0'`: in YAML, `version: 1.0` is a number, and refused. ## How settings merge Each command reads only its own section of `commands`, and every section is optional: without one, the command runs with its defaults, which for `lint`, `format` and `diff` is the `recommended` ruleset. Within a section, the rules combine in this order: 1. **The rulesets of `extends`**, in the order they are listed: when two set the same rule, the later one wins. 2. **The `rules` of the section**, over the rulesets: a severity, `off`, or `[severity, options]`. ```yaml version: '1.0' commands: lint: extends: [recommended, strict] # strict's settings win over recommended's rules: tags-unique: error # and these win over both info-defined: off ``` The `asyncapi`, `swagger`, `protobuf` and `graphql` sections of `lint`, `format` and `diff` configure the other linters, formatters and differs, each with rulesets and rules of its own: the settings for OpenAPI documents don't apply to them, and a linter whose section is missing runs with `recommended`. `apigenie config` prints the settings a command ends up with, and `--origin` says where each one comes from: ```text $ apigenie config --for lint --origin extends: # /home/me/shop/apigenie.yaml (repository file) - recommended rules: tags-unique: error # /home/me/shop/apigenie.yaml (repository file) ``` ### The server `apigenie-server` takes its settings from three places, and the first that sets a value wins: the command line, then the `APIGENIE_SERVER_*` environment variables (`APIGENIE_SERVER_PORT`, `APIGENIE_SERVER_PROXY_TO`, ...), then the file. ```text $ APIGENIE_SERVER_PORT=5000 apigenie config --for mock --origin server: host: 127.0.0.1 # default port: 5000 # environment APIGENIE_SERVER_PORT ``` ### The generators Each target of `apigenie-generator` has a section under `commands.generate`, named like `client_fetch` or `server_spring`, with the settings its reference page lists. The section's `overlay` list names the [overlays](/docs/reference/generator#overlays) applied to the document before generating, with paths relative to the file; the `--overlay` arguments of the command line apply after them. ### The catalog `catalog.specs` adds to what `apigenie-catalog` finds, it doesn't replace it: a specification the file doesn't list is still in the catalog, with a derived name, and `catalog.exclude` leaves files out ([What the catalog counts as a specification](/docs/concepts/what-the-catalog-counts-as-a-specification)). ## See also - [Configuration](/docs/reference/cli/configuration): every setting, by section. - [config](/docs/reference/cli/config): prints the effective settings, checks a file, prints the schema. - [lint](/docs/reference/cli/lint#configuration): `extends`, `rules`, custom rules and functions. - [Server configuration](/docs/reference/server/configuration): every setting of `apigenie-server`. --- # What the catalog counts as a specification Source: https://apigenie.pl/docs/concepts/what-the-catalog-counts-as-a-specification `apigenie-catalog list` turns a repository into the list of its API specifications, with nothing uploaded anywhere: the repository is the catalog. This page explains which files make the list and why, how each one gets its name, and what the root of the catalog is; the [`apigenie-catalog`](/docs/reference/catalog) page of the reference lists the options and the output. The examples use this repository: ```text shop/ .git/ .gitignore build/ apigenie.yaml apis/ orders/ openapi.yaml openapi: 3.1.0, info.title: Orders API schemas/order.yaml a schema the document references orders-v2.yaml openapi: 3.1.0, info.title: Orders API, not committed yet examples/sample.yaml openapi: 3.1.0, info.title: Example graphql/ schema.graphql type Query { ... } ping.graphql query Ping { ping } proto/pricing.proto package acme.pricing.v1 build/out.yaml ignored by git ``` ## Which files are looked at In a Git repository, the files Git tracks or would track: committed files, staged files, and new files that no ignore rule excludes. `apis/orders-v2.yaml` is looked at before it is committed; `build/out.yaml` never is. Outside Git, every file except those under a directory whose name starts with a dot and under `node_modules`. `catalog.exclude` in the configuration leaves more out, with glob patterns relative to the file: `*` matches within a directory, `**` across directories. ```yaml version: '1.0' catalog: exclude: - "**/examples/**" ``` ## Which of them are specifications A file is a specification by what is in it, not by its name: | Format | Files | | --- | --- | | OpenAPI, AsyncAPI, Swagger 2.0 | JSON and YAML files whose root has the `openapi`, `asyncapi` or `swagger` property | | Protobuf | every `.proto` file | | GraphQL | `.graphql`, `.graphqls` and `.gql` files with type definitions | So `apis/orders/schemas/order.yaml`, a file of a split document that holds a schema and no `openapi` property, is not listed: the document it belongs to is, by its root file. `graphql/ping.graphql`, an operation document, is not listed either. A file that can't be read is reported on the standard error and left out. ```text $ apigenie-catalog list NAME FORMAT VERSION PATH COMMIT orders-api OpenAPI 3.1.0 1.3.0 apis/orders-v2.yaml - orders-api OpenAPI 3.1.0 1.2.0 apis/orders/openapi.yaml 0d5d8a7 2026-10-29 schema GraphQL - graphql/schema.graphql 0d5d8a7 2026-10-29 acme-pricing-v1 Protobuf proto3 - proto/pricing.proto 0d5d8a7 2026-10-29 ``` ## How a specification is named A name is derived from the document: `info.title` in lower case with dashes (`Orders API` is `orders-api`), the Protobuf package (`acme.pricing.v1` is `acme-pricing-v1`), or the file name for a GraphQL schema. Two files with the same derived name are both listed, with a line on the standard error: ```text 2 specifications are named 'orders-api': apis/orders-v2.yaml, apis/orders/openapi.yaml; name them in the catalog section (apigenie-catalog init does) ``` A derived name changes with the title and says nothing about the owner. `apigenie-catalog init` writes an entry per specification in `catalog.specs`, with a name that stays when the file moves or its title changes, and an `owner` to fill in; a name two files would share gets a number: ```yaml catalog: specs: - name: orders-api path: apis/orders-v2.yaml owner: null - name: orders-api-2 path: apis/orders/openapi.yaml owner: null ``` The entries don't make the catalog: a specification the section doesn't list is still listed, with its derived name, and `listed: false` in the JSON output tells the two apart. ## The root of the catalog Paths are relative to the root of the catalog, in the output and in the configuration: the directory of the configuration file, else the root of the Git repository, else the directory given. The directory argument only narrows the search, and has to be inside the root: ```text $ cd apis && apigenie-catalog list NAME FORMAT VERSION PATH COMMIT orders-api OpenAPI 3.1.0 1.3.0 apis/orders-v2.yaml - orders-api OpenAPI 3.1.0 1.2.0 apis/orders/openapi.yaml 0d5d8a7 2026-10-29 ``` The paths stay `apis/...`, since the root is still `shop/`. ## What the catalog is not The catalog records what the repository holds. It doesn't check the specifications ([`apigenie lint`](/docs/reference/cli/lint) does), keep their versions (Git does, and [`apigenie changelog`](/docs/reference/cli/changelog) reads them) or serve them. `apigenie-catalog` is experimental: pinned consumers and a catalog across repositories are planned, and its options can change before 1.0 ([Compatibility](/docs/reference/cli/compatibility)). ## See also - [`apigenie-catalog`](/docs/reference/catalog): the options of `list`, `init`, `versions` and `release`, the columns and the JSON output. - [Configuration](/docs/reference/cli/configuration#catalog): the `catalog` section. - [Catalog the APIs of a repository](/docs/guides/catalog-the-apis-of-a-repository): the guide. --- # FAQ Source: https://apigenie.pl/docs/faq The questions teams ask before they adopt API Genie, with the answer and where the reference says it. For a command that misbehaves, see [Troubleshooting](/docs/troubleshooting). ## Does anything leave my machine? No. The command-line tools open no connection unless a command names a server: nothing is sent anywhere, and no telemetry file is written unless `APIGENIE_TELEMETRY_FILE` names one, in which case each run writes a local log of the version, the commands, the time taken by internal steps and the errors met, without usernames, API keys or the content of your files ([Telemetry](/docs/reference/cli#telemetry)). - `apigenie lint`, `format`, `diff`, `bundle` and `convert` read files: remote `$ref` URLs are not supported ([bundle](/docs/reference/cli/bundle)). - `apigenie-catalog` lists the specifications of the repository and writes names and owners into `apigenie.yaml`; the repository is the catalog, nothing is uploaded ([`apigenie-catalog`](/docs/reference/catalog)). - `apigenie test` and `apigenie-server --proxy-to` send requests to the server you name, and to no one else ([test](/docs/reference/cli/test), [contract testing](/docs/reference/server/contract-testing)). - The [editor](/tools/editor) opens a spec of your machine in the browser and writes back to it; its Try it out sends the requests you fire to the server of the document ([hosts](/docs/reference/editor/hosts#try-it-out)). - The documentation site `apigenie-generator docs` writes is built on your machine; its `npm install` fetches its dependencies from the npm registry ([docs](/docs/reference/generator/docs)). ## Which versions of the standards do the tools read? | Standard | Read | Not read | | --- | --- | --- | | OpenAPI | 3.0, 3.1 and 3.2 | | | Swagger | 2.0 | `apigenie-generator data` takes Swagger 2.0 after [`apigenie convert --to openapi32`](/docs/reference/cli/convert) | | AsyncAPI | 3 | AsyncAPI 2 documents are rejected | | Protobuf | proto3 | proto2 and editions files are rejected | | GraphQL | schemas and operations | | The [linter rules](/docs/linter) say per standard what each linter reads; the generators' pages say which documents each target takes ([`apigenie-generator`](/docs/reference/generator)). ## Does it replace Spectral? For linting, yes: `apigenie lint` has built-in rulesets per standard, takes custom rules in Spectral's format (`given`, `then`, the core functions and JavaScript functions), disables a rule in one place with `x-apigenie-lint-disable`, fixes what has a safe fix with `--fix`, and writes the same report formats for CI. [Migrate from Spectral](/docs/guides/migrate-from-spectral) maps the rules of `spectral:oas` by name, moves the custom rules and functions over, and lists what has no counterpart. Spectral has no formatter, differ, mock or generator, so nothing else moves. ## Does it run on Windows? Yes. [Downloads](/downloads) has a zip for Windows x64 with the five executables, and `npm install -g @mykulyak/api-genie` installs the same binaries wherever Node.js 18 or later runs. The other builds are Linux x64 (an archive, a `.deb` and an `.rpm`) and macOS on Apple silicon (also Homebrew, which serves Linux too). The [Quickstart](/docs/quickstart#install) has the commands for each channel. ## Is there a Docker image? Two, built for `linux/amd64`: `mykulyak/apigenie` with `apigenie` and `apigenie-generator`, and `mykulyak/apigenie-server` with the mock. Both work in `/mnt/data`, where you mount the directory of your files ([Quickstart](/docs/quickstart#docker)). ## Does it work behind a proxy, or with a private certificate authority? The commands that read files make no connection, so a proxy doesn't matter to them. `apigenie test` and `apigenie-server --proxy-to` connect to the server you name directly: the tools don't read `HTTP_PROXY` or `HTTPS_PROXY`. A private authority is given with `--ca-cert` (repeatable), a client certificate with `--client-cert` and `--client-key`, and `--insecure` skips the verification of the server's certificate while the traffic stays encrypted ([test](/docs/reference/cli/test#options), [server](/docs/reference/server#options), [TLS](/docs/reference/server/tls)). `apigenie-server` serves TLS itself with `--tls-cert` and `--tls-key`. ## What does it cost, and under which license? The command-line tools are free ([pricing](/pricing)). `apigenie license` prints the license text, and `apigenie license --list` the open source libraries the tools are built with ([credits](/credits)). ## Can scripts and CI rely on the output? From 1.0.0 the command names, the options, the configuration keys, the environment variables, the exit statuses, the `formatVersion` of each JSON report, the admin API and the `x-apigenie-*` extensions follow semantic versioning; the text of the messages, the wording of `--help`, the inside of generated code and the experimental commands don't. Versions below 1.0.0 make no such promise, and the changelog lists what each one broke. The [compatibility promise](/docs/reference/cli/compatibility) says what is covered and how deprecation works; read the JSON, SARIF, checkstyle, TAP or JUnit output in scripts, not the text formatters. ## Where do I ask a question or report a bug? In an issue at [github.com/mykulyak/api-genie/issues](https://github.com/mykulyak/api-genie/issues), with the output of `apigenie --version`, the command line, and the document or a reduced one that shows the behaviour. A break of something the compatibility promise covers is a bug, fixed in a patch release. --- # Troubleshooting Source: https://apigenie.pl/docs/troubleshooting One section per symptom, with what the message means and what to change. The questions teams ask before a command runs are on the [FAQ](/docs/faq). ## `apigenie` is not found after `npm install -g` The directory npm installs global commands in isn't on the `PATH`. `npm prefix -g` prints the prefix: the commands are in its `bin` directory on macOS and Linux, and in the prefix itself on Windows. Add it to the `PATH` and open a new terminal, or run the CLI without a global install with `npx @mykulyak/api-genie --version`. The other channels put the tools in a directory that is on the `PATH` already ([Quickstart](/docs/quickstart#install)). ## A command stops with "unknown property" or "Unsupported configuration version" The configuration file is checked against its schema before any command reads it, whichever command runs and whichever section is wrong, and the command stops with exit status 2: ```text apigenie.yaml:4:12: /commands/lint/rulez: unknown property 'rulez'; did you mean 'rules'? ``` The message names the file, the line, the JSON pointer of the value and, for a misspelled key, the closest known name. `version` has to be the string `'1.0'`: in YAML, `version: 1.0` is a number. The file is found in the current directory or a parent up to the root of the repository, so a broken file higher up stops the commands below it; `--no-config` runs the command without any file to tell the two apart, and [`apigenie config check FILE`](/docs/reference/cli/config) checks a file without running anything. [Where `apigenie.yaml` is found](/docs/concepts/where-the-configuration-is-found) has the details. ## A rule reports an issue in a document that is valid A rule is a convention, not the specification: a valid document can still miss a description or name a tag twice. Each issue names its rule, and the rule's page in the [linter rules](/docs/linter) says what it checks and why. If the convention isn't yours, change the rule's severity or turn it off under `commands.lint.rules`; if it holds everywhere but one place, disable it there with `x-apigenie-lint-disable` on the object ([disabling rules in a document](/docs/reference/cli/lint#disabling-rules-in-a-document)): ```yaml version: '1.0' commands: lint: rules: info-defined: off ``` If the rule is wrong about the document, open an issue with the document and the rule's id. ## The mock answers 404 or 405 The paths of the document are served under the path of its first server (`/v1` for `https://api.example.com/v1`) and as they are. A 404 is a path the document doesn't have, a 405 a method the path doesn't declare, and the problem details name the method and the path the mock looked for. Check the `servers` of the document and `--base-path`, which replaces the prefix; with `server.strict_base_path` the paths are served only under it. The [dashboard](/docs/reference/server/dashboard) lists the routes the mock serves. [How the mock picks a response](/docs/concepts/how-the-mock-picks-a-response) walks through the routing and what follows. ## The mock answers 422 to a request my client considers valid The request is checked against its operation before an answer is chosen, and the problem details list what failed, such as `path.id: expected type integer, found string`. The client and the document disagree, which is what the check is for; if the document is wrong, fix it. To see the finding without refusing the request, set `validation.request: log` in the configuration: the request is answered and the finding goes into the `X-Apigenie-Mock-Violations` headers and the log. A `format` the document uses beyond the [format registry](/docs/reference/cli/formats) is declared in `openapi.custom_formats` of the configuration, and `validation.formats: false` turns the format checks off ([Validation and security](/docs/reference/server/validation)). ## The validating proxy reports violations the team disputes Each violation names its check and its severity. A check can be re-rated or turned off in `contract.severity`; `response.header.undefined` is off unless you turn it on. By default the proxy reports and changes nothing, and `--fail-on errors` fails the run on errors only, not on warnings or notes. [What the validating proxy checks](/docs/concepts/what-the-proxy-checks) explains the checks and the severities; the [contract testing](/docs/reference/server/contract-testing) page lists them. ## `apigenie diff` rates a deliberate change as breaking The rating comes from the rules of the standard, and `--report detailed` shows the node type and the property that rated each change. To let a deliberate removal through, announce it first: mark the element `deprecated: true` with an `x-sunset` date and remove it after the date, which the recommended rules rate as non-breaking; in a Protobuf file, reserve the number of a removed field. To change a rating for good, set the rule's severity under `commands.diff.rules`. [Accepting a breaking change](/docs/reference/cli/diff/rules#accepting-a-breaking-change) has the four ways, and the tables of the recommended rules. ## Generated code doesn't compile - **The toolchain.** Each target's page names what the generated code needs: Java 17 and Maven for `client java`, Node.js 18 or later for `client fetch`, Python 3.10 or later with pydantic 2.11 or later for `client python`, .NET 8 for `client csharp` and `server aspnet`, Elixir 1.18 or later for the Elixir targets ([`apigenie-generator`](/docs/reference/generator)). - **The version.** The inside of generated code can change in a minor release, so a file generated by one version next to files generated by another can fail to compile. Regenerate everything with one version, and pin that version or commit the generated code ([compatibility](/docs/reference/cli/compatibility#what-it-doesnt-cover)). - **The document.** A document that references other files is bundled first with [`apigenie bundle`](/docs/reference/cli/bundle); the client and server generators read a Swagger 2.0 document directly ([Swagger 2.0 input](/docs/reference/generator#swagger-20-input)). Lint the document before generating: a clean contract gives cleaner code. - **Still failing.** Open an issue with the document, or a reduced one, the command line and the version: a document the generator accepts and then writes code that doesn't compile is a bug. ## `apigenie test` or the proxy can't reach an HTTPS server A certificate the system doesn't trust is given with `--ca-cert FILE` (repeatable), and a server that asks for a client certificate gets it with `--client-cert` and `--client-key`; `--insecure` skips the verification of the server's certificate, and the traffic stays encrypted. The tools connect directly and don't read `HTTP_PROXY` or `HTTPS_PROXY`, so a server reachable only through a proxy isn't reachable for them ([test](/docs/reference/cli/test#options), [TLS](/docs/reference/server/tls)). --- # apigenie Source: https://apigenie.pl/docs/reference/cli See also: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [format](https://apigenie.pl/docs/reference/cli/format.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md), [test](https://apigenie.pl/docs/reference/cli/test.md). `apigenie` is the API Genie command-line interface. Each command works on one or more API descriptions: OpenAPI, Swagger 2.0, AsyncAPI, Protobuf or GraphQL files, in JSON or YAML. Code generation, the mock server, the API catalog and the MCP server are separate executables installed next to it: [`apigenie-generator`](/docs/reference/generator), [`apigenie-server`](/docs/reference/server), [`apigenie-catalog`](/docs/reference/catalog) and [`apigenie-mcp`](/docs/reference/cli/mcp). From 1.0.0 the commands, options, configuration keys, exit statuses and JSON outputs follow semantic versioning; [Compatibility](/docs/reference/cli/compatibility) says what that covers. The site is built from the development version, so a page can describe what the last release does not have yet; that is marked with the version that brings it, "since 0.11.0". ## Usage ```sh apigenie COMMAND [OPTIONS] [FILES] ``` ## Commands | Command | What it does | | ------- | ------------ | | [`apigenie bundle`](/docs/reference/cli/bundle) | Combines an OpenAPI, Swagger 2.0 or AsyncAPI document, or a Protobuf file, and the files it references into one file | | [`apigenie changelog`](/docs/reference/cli/changelog) | Builds the changelog of an OpenAPI, Swagger 2.0, AsyncAPI, Protobuf or GraphQL file from its Git history | | [`apigenie config`](/docs/reference/cli/config) | Prints the configuration in effect, checks a configuration file and prints its JSON Schema | | [`apigenie convert`](/docs/reference/cli/convert) | Converts Swagger 2.0 to OpenAPI 3.2, WSDL 1.1 to OpenAPI 3.1, and JSON Schema 2019-09 or 2020-12 to draft-07, draft-04 or the OpenAPI 3.0 dialect (experimental) | | [`apigenie credits`](/docs/reference/cli/credits) | Lists the third-party libraries API Genie uses, with their licenses | | [`apigenie diff`](/docs/reference/cli/diff) | Compares two versions of an OpenAPI, Swagger 2.0 or AsyncAPI document, or of a Protobuf or GraphQL file, and rates each change by what it does to clients | | [`apigenie evolve`](/docs/reference/cli/evolve) | Splits a breaking OpenAPI change into an expand wave and a contract wave (experimental) | | [`apigenie format`](/docs/reference/cli/format) | Puts OpenAPI, Swagger 2.0, AsyncAPI, Protobuf and GraphQL files in one style | | [`apigenie i18n`](/docs/reference/cli/i18n) | Extracts the texts of OpenAPI, Swagger 2.0, AsyncAPI, Protobuf and GraphQL files for translation, and applies translations | | [`apigenie init`](/docs/reference/cli/init) | Sets a repository up: `apigenie.yaml` with the lint rules of the API descriptions found, and the section of `AGENTS.md` for coding agents | | [`apigenie license`](/docs/reference/cli/license) | Prints the license of API Genie and of the libraries it uses | | [`apigenie lint`](/docs/reference/cli/lint) | Checks OpenAPI, Swagger 2.0, AsyncAPI, Protobuf and GraphQL files against the [rules](/docs/linter) of their standard | | [`apigenie overlay`](/docs/reference/cli/overlay) | Applies OpenAPI Overlays to an OpenAPI document | | [`apigenie test`](/docs/reference/cli/test) | Runs the requests of `.http` files (HTTP, gRPC, WebSocket, MQTT) and generated requests against a live API, and checks them against its OpenAPI or AsyncAPI document or `.proto` file | Commands marked *experimental* are outside the [1.0 compatibility promise](/docs/reference/cli/compatibility); see [Experimental commands](#experimental-commands). ## The five binaries API Genie installs five executables side by side, always of the same version: | Binary | What it does | | ------ | ------------ | | `apigenie` | Lints, formats, compares, bundles, converts and tests API documents (the commands above) | | [`apigenie-generator`](/docs/reference/generator) | Generates clients, servers, documentation, data and validation schemas from OpenAPI, Swagger, AsyncAPI and JSON Schema documents | | [`apigenie-server`](/docs/reference/server) | Serves a document as a mock server, or proxies a live API and checks the traffic against the contract | | [`apigenie-catalog`](/docs/reference/catalog) | Lists the API specifications of a repository and keeps their names and owners in `apigenie.yaml` (experimental) | | [`apigenie-mcp`](/docs/reference/cli/mcp) | Serves the checks of `apigenie` to coding agents as tools of the Model Context Protocol (experimental) | The `--help` of each one ends with a line naming the others. `apigenie --version` prints the version on its first line and, below it, the versions of `apigenie-generator`, `apigenie-server`, `apigenie-catalog` and `apigenie-mcp` when they are installed next to it; scripts that compare the version should read the first line: ```sh apigenie --version | head -n 1 ``` Code generation was `apigenie generate` before 0.9.0: `apigenie generate ...` and `apigenie mock ...` now exit with status 2 and print the command to run instead, e.g. `run: apigenie-generator client fetch api.yaml -o client`, and so does `apigenie catalog ...`, which points to `apigenie-catalog`. ## Exit status The five binaries share one table of exit statuses. The [1.0 compatibility promise](/docs/reference/cli/compatibility) freezes it: scripts and CI jobs can rely on these numbers. | Status | Meaning | | ------ | ------- | | 0 | Success | | 1 | Findings: `lint` found errors, `diff` found breaking changes, `format --check` found files to reformat, `i18n apply --strict` found unknown keys, `overlay --validate` found problems in an overlay, `apigenie-generator --check` found generated files that would be created or changed | | 2 | A usage, input or unexpected error: bad or unknown options, an unknown command, a file that can't be read or isn't a valid document, a bad configuration file, or an internal error | | 3 | `apigenie-server`: the document can't be served | | 4 | `apigenie-server`: the address can't be used (the port is taken, ...) | | 5 | The contract or replay report failed: `apigenie-server` with `--fail-on` or `--min-coverage`, or with `--replay` when a recorded exchange was never replayed or a request matched none; `apigenie test` when a request or the contract gate failed | `apigenie-server` also exits with 130 when a second Ctrl+C stops it at once, as shells do for a process interrupted by a signal. An unknown command or subcommand prints the help of the command above it on the standard error. In 0.9 and earlier, errors exited with 255 or 1 depending on the command; see the Upgrading section of the changelog. ## JSON output Since 0.12.0, every command takes `--json`: the standard output then holds one JSON document and nothing else, for scripts and coding agents. Commands with a report print it: `lint`, `diff` and `changelog` the same report as `--formatter json`, `format` the files and whether each changed, `test` its test report, `evolve plan` and `i18n check` their reports, `config` the effective configuration, `apigenie-catalog list` the catalog. The other commands print the status of the run: ```sh apigenie config check --json missing.yaml ``` ```json { "formatVersion": 1, "command": "apigenie config check", "exitStatus": 2, "messages": [ "No such file: missing.yaml" ] } ``` `output` holds what the command would have printed without `--json`, such as the document `apigenie convert` writes to the standard output. A command line that can't be parsed prints the status too. `--json` may also come before the subcommand (`apigenie i18n --json check`), and it changes only the standard output: `changelog --output` still writes the file with the formatter asked for, and prints the status. `--help` prints the help as text. The exit status is the same as without `--json`, and the messages are still printed on the standard error. The JSON document is UTF-8: text that isn't (a path, say) gets U+FFFD for each ill-formed byte sequence in it. The schemas are listed under [Versioned JSON outputs](/docs/reference/cli/compatibility#versioned-json-outputs). `apigenie-server` serving a document has `--log-format json` instead. ## Experimental commands These commands are outside the [1.0 compatibility promise](/docs/reference/cli/compatibility): their options and output can still change. Their `--help` and the first line they print (on the standard error, so that their output stays usable) say "(experimental, outside the 1.0 compatibility promise)". `apigenie-mcp`, whose standard output carries the protocol, says it only in its `--help`. | Command | Why | | ------- | --- | | [`apigenie-catalog`](/docs/reference/catalog) | The first part of a catalog kept in Git; pinned consumers and multi-repository catalogs will add settings | | [`apigenie-mcp`](/docs/reference/cli/mcp) | MCP is still moving; tool names, arguments and results can change with it | | [`apigenie-generator client rust`](/docs/reference/generator/client-rust) | The generated crate isn't yet checked against a live API (conformance Level 3) | | [`apigenie convert`](/docs/reference/cli/convert) | Three sources (`--to openapi32` for Swagger 2.0, `--to openapi31` for WSDL 1.1, `--to draft7|draft4|openapi30` for JSON Schema); more sources and targets may change its options | | [`apigenie evolve plan`](/docs/reference/cli/evolve) | The first version of the planner: its recipes and `plan.yaml` will grow, and `evolve status` and `evolve next` will join it | | [`apigenie-generator client swift`](/docs/reference/generator/client-swift) | The generated packages aren't yet built and run against a live API by the conformance suite | | [`apigenie-generator schema zod`](/docs/reference/generator/schema-zod) | The generated schemas aren't yet checked against a live API (conformance Level 3) | | [`apigenie-generator server axum`](/docs/reference/generator/server-axum) | The generated crate doesn't yet receive requests in contract tests (conformance Level 3) | | [`apigenie-generator server hummingbird`](/docs/reference/generator/server-hummingbird) | Levels 2 and 3 of the conformance suite are wired but haven't passed a run yet | | [`apigenie-generator server mcp`](/docs/reference/generator/server-mcp) | MCP and its SDK are still moving; tool names and result shapes can change with them | | [`apigenie-generator server vapor`](/docs/reference/generator/server-vapor) | Levels 2 and 3 of the conformance suite are wired but haven't passed a run yet | ## Continuous integration The [GitHub Action](/docs/ci/github-action) installs the CLI on GitHub Actions runners and lints, checks the formatting of, or diffs your files on every pull request. On other CI systems, run the commands and read their [exit statuses](#exit-status). ## Configuration files Most commands read their settings from a configuration file: the rules of `lint`, the style of `format`, the severities of `diff`, the options of each generator and the catalog. `apigenie`, `apigenie-generator`, `apigenie-server` and `apigenie-catalog` find the file themselves: `apigenie.yaml` (or `.yml`, `.json`, or the same names with a leading dot) in the current directory or a parent directory, up to the root of the Git repository. `--config FILE` uses another file instead, and `--no-config` none. The file is checked against its JSON Schema before any command reads it, so a misspelled setting is an error that names its line and JSON pointer. [`apigenie config`](/docs/reference/cli/config) prints the settings in effect and checks a file. [Configuration](/docs/reference/cli/configuration) lists every setting. ### Editor support The JSON Schema of the file is published at `https://apigenie.pl/schemas/apigenie-config/latest.json`, and the schema of each release at `https://apigenie.pl/schemas/apigenie-config/.json`. Editors that use the YAML language server (VS Code with the Red Hat YAML extension, Neovim, JetBrains IDEs, Zed) complete and check the file when it starts with: ```yaml # yaml-language-server: $schema=https://apigenie.pl/schemas/apigenie-config/latest.json version: '1.0' commands: lint: extends: [recommended] ``` A standalone mock server file (`apigenie-server.yaml`) has its own schema, `https://apigenie.pl/schemas/apigenie-server-config/latest.json`. The API Genie extension for VS Code associates both schemas with `apigenie.yaml`, `apigenie-server.yaml` and their variants on its own. To pin the schema to the version you run, use `apigenie config schema --out apigenie.schema.json` and point the comment at that file. ## Telemetry Nothing is sent anywhere, and no telemetry file is written unless you ask for one. With `APIGENIE_TELEMETRY_FILE` set to a file path, each run writes a local log to that file: the version, the commands run, the time taken by internal steps (parsing a YAML file, for example) and the errors met, without usernames, API keys or the content of your files. A relative path is resolved against the current directory; the file is created or truncated on each run, and its parent directory must exist. When the variable is unset or empty, no file is created or truncated. --- # apigenie bundle Source: https://apigenie.pl/docs/reference/cli/bundle Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md). Its other pages: [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [format](https://apigenie.pl/docs/reference/cli/format.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md), [test](https://apigenie.pl/docs/reference/cli/test.md). Bundles an OpenAPI, Swagger 2.0 or AsyncAPI document and the local files it references, or a Protobuf file and the files it imports, into one file that stands on its own: for tools that read a single document, and before [diff](/docs/reference/cli/diff) and [i18n](/docs/reference/cli/i18n), which compare and extract one file at a time. ## Usage ```sh apigenie bundle [OPTIONS] --output OUTPUT INPUT ``` ```sh apigenie bundle api/openapi.yaml --output build/openapi.json apigenie bundle api/orders.proto -I shared -I api --output build/orders.proto ``` ## What the command does A file with the `.proto` extension is a Protobuf file. Any other file is read as JSON or YAML and recognized as an OpenAPI, Swagger or AsyncAPI document by the `openapi`, `swagger` or `asyncapi` field of its root; a file with none of them is reported (`'FILE' is not an OpenAPI, Swagger or AsyncAPI document.`) and nothing is written. Unlike `format`, `overlay` and `lint --fix`, `bundle` does not keep the YAML comments of OpenAPI, Swagger and AsyncAPI inputs: the output is a new document built from several files. In YAML output, strings that YAML 1.1 parsers would read as booleans or numbers, such as `yes`, `off`, `0755` or `1:30`, are written in double quotes. ### OpenAPI External references (`$ref` to other local files) are copied into the `components` object of the output, and the references are rewritten to point there. A copy is named after the last segment of the reference (`Address` for `models.yaml#/$defs/Address`), and a copy of a whole file after the file (`pet` for `pet.yaml`). When the name is taken, a numeric suffix is added (`_2`, `_3`, and so on). Since 0.12.0, a component that is only a reference to the same name in another file takes the referenced content instead. `PhoneNumber: {$ref: common.yaml#/components/schemas/PhoneNumber}` becomes the `PhoneNumber` schema of `common.yaml`, and no `PhoneNumber_2` is added. A reference to a whole file is still copied (`pet: {$ref: pet.yaml}` gives `pet_2`). Remote references (URLs) are not supported. The output format, JSON or YAML, follows the extension of the output file. ### Swagger Swagger 2.0 documents are bundled like OpenAPI ones. Schemas, parameters and responses referenced in other local files are copied into the `definitions`, `parameters` and `responses` objects of the output, and the references are rewritten to point there. The copies are named as OpenAPI components are. A definition, parameter or response that is only a reference to the same name in another file takes the referenced content (since 0.12.0). A reference to a whole file is still copied. A path item that is a reference to another file takes the content of that file. Remote references (URLs) are not supported. The output format, JSON or YAML, follows the extension of the output file. ### AsyncAPI AsyncAPI 3.x documents are bundled with the local files they reference. Root servers, channels and operations kept in other files take the content of those files; other referenced objects become components. A component that is only a reference to another local file takes the referenced content. Schemas in other formats, such as Avro, are copied as they are, and references by URL are kept. The output format, JSON or YAML, follows the extension of the output file. ### Protobuf The input file and the files it imports, directly or indirectly, are combined into one proto3 file, which can be compiled without the imported files: - All declarations of the input file are kept, in their order, with their comments. The output is written in the layout of the `format` command. - Of the imported files, only the messages, enums and extensions that the input file uses, directly or through other imported declarations, are copied. They follow the declarations of the input file. Imported services, unused declarations and the file options of imported files (such as `go_package` or `java_package`) are left out. - The output has the package of the input file. Declarations from files with another package are renamed with a prefix made from their package: top-level messages and enums get the package in PascalCase, and top-level extensions get it in snake case. Declarations nested in them keep their names. When a name is already taken, a numeric suffix is added (`_2`, `_3`, and so on). Type names and option names that refer to renamed declarations are rewritten. Declarations from files with the same package keep their names. - The well-known types (`google/protobuf/*.proto`) are not bundled: their imports are kept, and the imports needed by the copied declarations are added. For example, with `shop.proto`: ```proto syntax = "proto3"; package shop.v1; import "common/money.proto"; message Order { common.v1.Money total = 1; } ``` and `common/money.proto`: ```proto syntax = "proto3"; package common.v1; message Money { string currency = 1; int64 units = 2; } ``` `apigenie bundle shop.proto --output bundle.proto` writes: ```proto syntax = "proto3"; package shop.v1; message Order { CommonV1Money total = 1; } message CommonV1Money { string currency = 1; int64 units = 2; } ``` Renaming changes the full names of the moved declarations, e.g. `common.v1.Money` becomes `shop.v1.CommonV1Money`, and an option such as `(google.api.http)` becomes `(google_api_http)`. Field numbers and the wire format do not change, but tools that depend on full names, such as JSON encoding of `Any` values or code generators matching option names, see the new names. Type names inside string option values are not rewritten. Imports are searched in the proto paths given with `--proto-path`, like `protoc` does, never relative to the importing file. Without `--proto-path`, the directory of the input file is searched. Nothing is written when there are errors. The command reports, with the file, line and column: - imports that are not found or cannot be read, including proto2 files and files with editions, which are not supported - import cycles - type names and option names that are not defined, or not visible from the file that uses them - enum values that clash after the merge; enum values are in the scope of the package, so they cannot be renamed ## Options ### --output OUTPUT The bundled file; `-o OUTPUT` for short. Required. For an OpenAPI, Swagger or AsyncAPI document the extension, `.json` or `.yaml`, chooses the format. ### --proto-path DIR Directory in which Protobuf imports are searched. The option can be repeated; the directories are searched in the given order. Write it as `-I DIR` or `--proto-path=DIR`. Defaults to the directory of the input file. ```sh apigenie bundle api/orders.proto -I shared -I api --output bundle.proto ``` ## Exit status | Status | When | | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | 0 | The bundled file was written. | | 2 | The input is not a supported document, cannot be read (`Errors reading OpenAPI file 'FILE':` and the positions), or, for a Protobuf file, has the errors listed above; nothing is written. | See the [exit statuses](/docs/reference/cli#exit-status) shared by the five binaries. ## See also - [diff](/docs/reference/cli/diff): Compares two bundled versions, imported declarations included. - [i18n](/docs/reference/cli/i18n): Extracts the texts of a bundled document, referenced files included. - [format](/docs/reference/cli/format): The layout a bundled Protobuf file is written in. --- # apigenie changelog Source: https://apigenie.pl/docs/reference/cli/changelog Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md). Its other pages: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [format](https://apigenie.pl/docs/reference/cli/format.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md), [test](https://apigenie.pl/docs/reference/cli/test.md). Builds the changelog of an OpenAPI, Swagger, AsyncAPI, Protobuf or GraphQL file from its Git history. ## Usage ```sh apigenie changelog [OPTIONS] FILE ``` ## Description This command compares the consecutive versions of an OpenAPI, Swagger, AsyncAPI, Protobuf or GraphQL file stored in a Git repository, and describes what changed for API consumers: added, removed, deprecated and changed operations, servers and metadata, for AsyncAPI the channels, for Protobuf the methods, messages, enums and services, and for GraphQL the fields of the root operation types and the types and directives of the schema. Each change is rated as breaking, non-breaking or non-functional, with the same rules as the `diff` command. The command runs `git`, which must be installed. The file must be in a git repository, and only its committed versions are compared. ### Revisions By default, the changelog has an entry for every commit that changes the file or one of the files it references. Commits that change neither, and commits whose changes don't affect the API (e.g. reformatting), are left out. With `--revisions tags`, the changelog has an entry for every release tag instead, comparing each release with the previous one. ```sh # every commit apigenie changelog api/openapi.yaml # every release tagged v1.0.0, v1.1.0, ..., and the changes made since the last one apigenie changelog api/openapi.yaml --revisions tags --tag-pattern 'v*' --unreleased ``` Only the first parent of merge commits is followed, so a merged branch appears as a single entry: its merge commit. The first version of the file starts the changelog, and lists the operations the API had then. With `--from`, the changelog starts after the given revision instead, e.g. the last release. `--to` sets the last revision, which is `HEAD` by default. ```sh apigenie changelog api/openapi.yaml --from v2.0.0 ``` ### Files split into many documents References to other files (e.g. `$ref: 'schemas/pet.yaml'`) are followed in each version, so a change of a referenced file is a change of the API. By default, the commits changing the file or the files it references in the last revision are compared. `--path` selects the commits changing other paths instead, e.g. files that were referenced in older versions only: ```sh apigenie changelog api/openapi.yaml --path api ``` References to URLs and to files outside the repository aren't supported. ### Changes of operations With `--by operation`, the changes are grouped by operation, with the history of each one, newest first. `--operation` selects the operations to show, by method and path, by path or by operation id, and can be repeated: ```sh apigenie changelog api/openapi.yaml --by operation --operation 'GET /pets' --operation createPet ``` Operations are identified by their method and path, so moving an operation to another path shows as removing it and adding a new one. ### Swagger files Swagger 2.0 files are recognized by their `swagger` field in the last revision. Their changelog lists the added, removed, deprecated and changed operations, by method and path like OpenAPI ones, with the rules of the `commands.diff.swagger` section of the configuration. Changes of the host, the base path, the schemes, the media types and the security of the whole API are metadata. A change of a path item other than of its operations, e.g. of the parameters its operations share, is shown under each of its operations. Changes of definitions, shared parameters and responses are shown under the operations using them. Files the specification references are bundled in each version, as for OpenAPI files. ```sh apigenie changelog api/swagger.yaml --by operation --operation 'GET /pets' ``` ### AsyncAPI files AsyncAPI 3.x files are recognized by their `asyncapi` field in the last revision. Their changelog lists the added, removed and changed operations, channels and servers, and the changed metadata, with the rules of the `commands.diff.asyncapi` section of the configuration. An operation is shown by its action and the address of its channel, followed by its id, e.g. `send user/signedup` (sendUserSignedUp). Messages belong to channels, so a change of a message, e.g. of its payload, is a change of its channel, and also of the operations using the channel. Operations are identified by their id: renaming one shows as removing it and adding a new one. `--operation` selects operations by id, by action and address (e.g. `'send user/signedup'`), or by the address of their channel: ```sh apigenie changelog api/asyncapi.yaml --by operation --operation 'receive user/signedup' ``` ### Protobuf files Protobuf (proto3) files are recognized by their `.proto` extension. Their changelog lists the added, removed and changed methods of the services, named by their service and their own name (e.g. `Customers.GetCustomer`), then the messages, enums, services and extended messages declared at the top level of the file, with the rules of the `commands.diff.protobuf` section of the configuration. A change of the package is shown like a version change (e.g. `shop.v1 → shop.v2`), and changes of the imports, the file options and the comment of the syntax statement as metadata. The file is compared on its own, as by `diff`: the files it imports aren't read, and the types they declare are compared by their names. So by default, only the commits changing the file are compared. A method is identified by the names of its service and its own: renaming either shows as removing the method and adding a new one. A change of a service other than of its methods, e.g. of its options, is listed under the service. `--operation` selects methods by their full name, by their own name or by the name of their service: ```sh apigenie changelog api/shop.proto --by operation --operation Customers.GetCustomer ``` See [Protobuf files](/docs/reference/cli/diff#protobuf-files) of the `diff` command for how changes are rated. ### GraphQL files GraphQL schema files are recognized by their `.graphql`, `.graphqls` or `.gql` extension. Their operations are the fields of the root operation types, named by their type and their own name (e.g. `Query.books` or `Mutation.addBook`). The changelog lists the added, removed and changed operations, then the scalars, object types, interfaces, unions, enums, input objects and directive definitions of the schema, with the rules of the `commands.diff.graphql` section of the configuration. Changes of the root operation types, of the description of the schema and of its directives are shown as metadata. A schema has no version, so none is shown. The file is compared on its own, as by `diff`: types defined in other files are compared by their names. So by default, only the commits changing the file are compared. The root operation types are those named by the schema definition, or the types named `Query`, `Mutation` and `Subscription`. An operation is identified by the names of its type and its field: renaming either shows as removing the operation and adding a new one. A change of a root operation type other than of its fields, e.g. of its description, is listed under the object types. `--operation` selects operations by their full name, by their field name, by the name of their type, or by their operation type (`query`, `mutation` or `subscription`): ```sh apigenie changelog api/schema.graphql --by operation --operation Query.books ``` See [GraphQL files](/docs/reference/cli/diff#graphql-files) of the `diff` command for how changes are rated. ### Invalid versions Versions that can't be read, e.g. because of a YAML, Protobuf or GraphQL syntax error, are skipped with a warning, and the next version is compared with the last valid one. ## Options | Option | Description | | ------------------------------ | -------------------------------------------------------------------------------------------------------- | | `--revisions commits\|tags` | Compares every commit that changes the file (default), or every release tag. | | `--tag-pattern PATTERN` | Glob pattern of the release tags, e.g. `v*`. All tags by default. | | `--tag-sort version\|date` | Orders the release tags by version numbers in their names (default), or by date. | | `--unreleased` | With `--revisions tags`, adds an entry with the changes made after the last release. | | `--from REVISION` | The revision the changelog starts after, e.g. a tag. | | `--to REVISION` | The last revision, `HEAD` by default. | | `--path PATH` | With `--revisions commits`, compares the commits changing these paths. Can be repeated. By default, the file and the files it references; for Protobuf and GraphQL, the file only. | | `--by revision\|operation` | Groups the changes by revision (default), or by operation (for Protobuf, by method; for GraphQL, by field of a root operation type). | | `--operation OPERATION` | Shows the changes of an operation only: `'GET /pets'`, a path or an operation id (OpenAPI and Swagger); for AsyncAPI, `'send ADDRESS'`, a channel address or an operation id; for Protobuf, `Service.Method`, a method name or a service name; for GraphQL, `Query.books`, a field name, a root operation type name, or `query`, `mutation` or `subscription`. Can be repeated. | | `--formatter FORMATTER` | `stylish` (default), `markdown`, `html` or `json`. | | `--config FILE` | Configuration file; its `diff` settings (`diff.swagger` for Swagger, `diff.asyncapi` for AsyncAPI, `diff.protobuf` for Protobuf, `diff.graphql` for GraphQL) decide the severity of the changes. | | `--git PATH` | Path to the git program. | | `-o`, `--output FILE` | Writes the changelog to a file instead of printing it. | ## Output The `markdown` formatter prints a changelog that can be published as is: ```markdown ## v2.0.0 (2026-01-05) Release 2.0 (a25ac8d, Jane Doe) **Contains breaking changes.** Version: 1.1.0 → 2.0.0 ### Removed - `GET /pets/{id}` (getPet) **breaking** ### Deprecated - `GET /pets` (listPets) **breaking** ``` The `json` formatter prints the full data, including every change of the modified operations, for further processing: an object with `formatVersion` (the version of the format, which changes only when a member is removed or changes meaning, see [Compatibility](/docs/reference/cli/compatibility)), `spec`, `warnings`, and `entries` (one per revision, newest first) or, with `--by operation`, `operations` (`methods` for Protobuf) with the history of each one. Its JSON Schema is [`apigenie-changelog-report.json`](https://apigenie.pl/schemas/apigenie-changelog-report.json). ```json5 { "formatVersion": 1, "spec": "petstore.yaml", "entries": [ { "revision": { "id": "a25ac8d…", "shortId": "a25ac8d", "label": "v2.0.0", "tag": "v2.0.0", "author": "Jane Doe", "date": "2026-01-05", "subject": "Release 2.0" }, "initial": false, "version": "2.0.0", "severity": "breaking", … metadata, servers, operations … } ], "warnings": [] } ``` ## Exit status The command exits with 0 when it prints the changelog, even if it has breaking changes, and with 2 when git can't be run, the file isn't in a Git repository, a revision doesn't exist, or no revision changes the file. See the [exit statuses](/docs/reference/cli#exit-status) shared by the three binaries. --- # apigenie config Source: https://apigenie.pl/docs/reference/cli/config Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md). Its other pages: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [format](https://apigenie.pl/docs/reference/cli/format.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md), [test](https://apigenie.pl/docs/reference/cli/test.md). Prints the effective configuration, checks a configuration file, and prints the JSON Schema of the configuration file. ## Usage ```sh apigenie config [--config FILE | --no-config] [--json] [--origin] [--for SECTION] apigenie config check [FILE] apigenie config schema [--for SECTION | --standalone-server] [--out FILE] ``` ## Description The commands of `apigenie`, `apigenie-generator`, `apigenie-server` and `apigenie-catalog` read their settings from the [configuration file](/docs/reference/cli/configuration): `apigenie.yaml` in the current directory or a parent up to the root of the repository, or the file given with `--config`. Every file is checked against a JSON Schema (draft-7) when it is loaded. The schema is made of one part per section, so it covers the settings of `apigenie`, `apigenie-generator`, `apigenie-server` and `apigenie-catalog`. ### `apigenie config` Prints the settings the commands use: the values of the file, those set by environment variables, and the defaults of the settings the file leaves out. Sections without any setting are left out. | Option | Description | | ----------------- | ----------- | | `--config FILE` | Uses FILE instead of the file found in the repository. | | `--no-config` | Uses no file: prints the defaults. | | `--json` | Prints JSON instead of YAML. | | `--origin` | Annotates each value with where it comes from. | | `--for SECTION` | Prints one section only: `catalog`, `lint`, `format`, `diff`, `generate`, `generate.` (for example `generate.client_go`) or `mock`. | With `--origin`, the YAML output has a comment after each value: ```yaml commands: lint: extends: - recommended # apigenie.yaml (repository file) mock: server: host: 127.0.0.1 # default port: 8080 # environment APIGENIE_SERVER_PORT ``` The origins are: | Origin | Meaning | | ------ | ------- | | ` (repository file)` | the file found in the current directory or a parent | | `--config ` | the file given with `--config` | | `environment ` | an environment variable of `apigenie-server` (`APIGENIE_SERVER_PORT` and the others listed in [mock server](/docs/reference/server)), which wins over the file | | `default` | the value used when the file leaves the setting out | With `--json --origin`, the output is an object with the configuration under `config` and the origin of each value, keyed by its JSON pointer, under `origins`. Below a section with `extends` (such as `extends: [recommended]` in `lint`, `format` or `diff`), only the values of the file are shown: the presets set the others. Settings given on the command line of a command (such as `--port` of `apigenie-server`) are not part of the configuration and are not shown. ### `apigenie config check` Validates FILE, or the file found in the repository, against the schema. It prints `: ok` and exits with 0 when the file is valid. Otherwise it prints each error with its position and the JSON pointer of the value, and exits with 2: ```text $ apigenie config check apigenie.yaml apigenie.yaml:4:11: /commands/fromat: unknown property 'fromat'; did you mean 'format'? apigenie.yaml:9:15: /commands/format/openapi/indent: expected type integer, found string apigenie.yaml:12:20: /commands/generate/server_express/validation: "zod" is not one of "ajv", "generated", "none" ``` Every unknown setting is reported at once. Of the other errors, the first one found is reported. ### `apigenie config schema` Prints the JSON Schema of the configuration file, of one section with `--for`, or of a standalone `apigenie-server` file (`apigenie-server.yaml`, whose root holds the settings of `commands.mock`) with `--standalone-server`. `--out FILE` writes it to FILE. The schema of each release is also published on the website, at `https://apigenie.pl/schemas/apigenie-config/.json` and `https://apigenie.pl/schemas/apigenie-server-config/.json`, with `latest.json` for the last release. See [editor support](/docs/reference/cli#editor-support). ## Exit status | Status | Meaning | | ------ | ------- | | 0 | Success; `config check`: the file is valid. | | 2 | `config check` found errors in the file, the configuration file can't be loaded, or a usage error: an unknown section, no file to check. | These are the statuses of every command ([exit status](/docs/reference/cli#exit-status)). ## See also - [Configuration](/docs/reference/cli/configuration): the sections of the file. - [Mock server configuration](/docs/reference/server/configuration). --- # apigenie convert Source: https://apigenie.pl/docs/reference/cli/convert Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md). Its other pages: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [format](https://apigenie.pl/docs/reference/cli/format.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md), [test](https://apigenie.pl/docs/reference/cli/test.md). Convert a Swagger 2.0 document to OpenAPI 3.2, a WSDL 1.1 document to OpenAPI 3.1, or a JSON Schema document of a newer draft to draft-07, draft-04 or the Schema Object dialect of OpenAPI 3.0. > **(experimental, outside the 1.0 compatibility promise)** `convert` has three sources, Swagger > 2.0, WSDL 1.1 and JSON Schema, and its options and output can still change. It says so in its > `--help` and on the first line it prints, on the standard error. See the > [experimental commands](/docs/reference/cli#experimental-commands). ## Usage ```sh apigenie convert --to openapi32 [...OPTIONS] SWAGGER_FILE apigenie convert --to openapi31 [...OPTIONS] WSDL_FILE apigenie convert --to draft7|draft4|openapi30 [...OPTIONS] SCHEMA_FILE ``` ## Description The command reads a Swagger 2.0 document, a WSDL 1.1 document or a JSON Schema document and writes the converted document, to the standard output or to the file given with `--output`. A Swagger document becomes OpenAPI 3.2 (`--to openapi32`), a WSDL document OpenAPI 3.1 (`--to openapi31`), and, since 0.11.0, a JSON Schema document a draft-07 (`--to draft7`), draft-04 (`--to draft4`) or OpenAPI 3.0 schema (`--to openapi30`). The source is the one `--from` names; without `--from`, an input that starts with `<` (an XML document) is WSDL, a document with a `swagger` member Swagger 2.0, and any other input a JSON Schema. ## Swagger 2.0 input The command reads a Swagger 2.0 document (`swagger: "2.0"`, JSON or YAML) and writes the equivalent OpenAPI 3.2 document. OpenAPI 3.x documents are not accepted as input: they are read as Swagger documents and rejected (`Missing required property 'swagger'`). The document is checked first. When it isn't a valid Swagger 2.0 document, the command lists the problems with their lines and columns and writes nothing. The conversion changes the structure of the document, not only its references: - `body` and `formData` parameters become request bodies, with a media type per entry of `consumes` (file uploads as `multipart/form-data`). Global body parameters become `components.requestBodies`. - Other parameters get a `schema` built from their keywords, and `collectionFormat` becomes `style` and `explode`. - Response schemas, headers and examples move into `content`, with a media type per entry of `produces`. - `host`, `basePath` and `schemes` become `servers`: one URL per scheme, `https` when no scheme is given, and a relative URL from `basePath` alone when there is no `host`. - `definitions`, `parameters`, `responses` and `securityDefinitions` move into `components`, and references follow them (`#/definitions/Pet` becomes `#/components/schemas/Pet`). - `basic` security schemes become `http` schemes with `scheme: basic`; the `flow`, URLs and scopes of `oauth2` schemes move into `flows` (`accessCode` becomes `authorizationCode`, `application` becomes `clientCredentials`). - Schemas switch dialect: `type: file` becomes a binary string, discriminators become objects, boolean `exclusiveMinimum` and `exclusiveMaximum` become numeric bounds, and `x-nullable: true` adds `null` to the type. - Specification extensions (`x-...`) and everything else without a counterpart to convert are copied as they are. Some parts of a Swagger 2.0 document have no exact counterpart in OpenAPI 3.2 and are approximated or dropped: a `collectionFormat` of `tsv` (or one other than `csv` in a path or a header, or other than `multi` in a form field), `allowEmptyValue` of a form field, an operation's own `schemes`, form parameters next to a body parameter, and `x-nullable` without a `type`. A reference to another document is copied unchanged, so that document has to be converted too; bundle the document first with [`apigenie bundle`](/docs/reference/cli/bundle) to convert it as a whole. The `convert` command doesn't report these approximations yet; [`apigenie-server`](/docs/reference/server#swagger-20-documents), [`apigenie test`](/docs/reference/cli/test) and the [generators](/docs/reference/generator#swagger-20-input) do (see below). The output keeps the order of the input's keys. Comments of a YAML input are not kept. ### Swagger 2.0 in `apigenie-server`, `apigenie test` and the generators `apigenie-server`, its validating proxy (`--proxy-to`), and `apigenie test --spec` take Swagger 2.0 documents directly: they convert them to OpenAPI 3.2 in memory, as `convert --to openapi32` does, each time the document is read, and write no file. Locations stay those of the Swagger file: the lines of warnings, the lines and JSON pointers of `x-apigenie-mock` problems, and the `pointer` of each operation in the contract reports. What the conversion can only approximate is told once at startup as `info:` lines with the Swagger file's line and JSON pointer (`{"event":"info",...}` with `apigenie test --formatter json`). See [Swagger 2.0 documents](/docs/reference/server#swagger-20-documents). Since 0.12.0, the client and server [generators](/docs/reference/generator#swagger-20-input) of OpenAPI documents read Swagger 2.0 documents directly too, converted in memory with polymorphism as unions. The other commands that need an OpenAPI document read only OpenAPI 3.x: convert Swagger 2.0 documents first. ## JSON Schema input Since 0.11.0, the command reads a JSON Schema document written against draft 2019-09 or 2020-12 (JSON or YAML) and writes the same schema in an older dialect: draft-07 (`--to draft7`), draft-04 (`--to draft4`), or the Schema Object of OpenAPI 3.0 (`--to openapi30`), to paste into `components.schemas` of an OpenAPI 3.0 document. A draft-07 document goes through the same pass on its way to draft-04: the rewrite is driven by the keywords the document uses, not by its `$schema`. The document is not validated first. ### Composition: allOf and unevaluatedProperties The older dialects have no `unevaluatedProperties`, and `additionalProperties: false` next to an `allOf` would reject every property the members declare. So a schema that extends others with `allOf` and closes itself with `unevaluatedProperties` becomes one flat object schema: ```yaml # 2020-12 $defs: Base: {type: object, properties: {id: {type: string}}, required: [id]} type: object allOf: - $ref: '#/$defs/Base' - properties: {name: {type: string}} unevaluatedProperties: false ``` ```yaml # draft-07 $schema: http://json-schema.org/draft-07/schema# definitions: Base: {type: object, properties: {id: {type: string}}, required: [id]} type: object properties: id: {type: string} name: {type: string} required: [id] additionalProperties: false ``` The members are the `allOf` elements, the schemas that local `$ref` members point to (chains of references and nested `allOf` followed, each schema merged once), and the schema itself (a `$ref` with siblings counts as a member too). Their `properties`, `required`, `patternProperties`, `propertyNames`, `minProperties`, `maxProperties` and `dependentRequired` are merged; a member's `additionalProperties` schema becomes the result's, since it evaluates the extra properties; otherwise `unevaluatedProperties` does. The members' titles and descriptions are not carried over, and the definitions stay for the other schemas that reference them. A property two members define differently is kept as an `allOf` of both definitions, and reported. A member that can't be merged keeps the `allOf` as it is, drops `unevaluatedProperties` (the result then accepts more than the source, which is the lesser loss) and says why on the standard error: `additionalProperties: false` or `unevaluatedProperties` of its own, `anyOf`, `oneOf`, `not`, `if`, `dependentSchemas`, `enum`, `const`, a `type` other than `object`, a `discriminator`, a reference to another document or to an anchor, or a cycle. ### The other keywords | Source keyword | draft-07 | draft-04 | OpenAPI 3.0 | | --- | --- | --- | --- | | `$schema` | the draft-07 URI | the draft-04 URI | dropped | | `$defs` and `#/$defs/` references | `definitions` | `definitions` | `definitions`, reported: move them to `components.schemas` | | `$id` | kept | `id` | dropped | | `unevaluatedProperties` alone | `additionalProperties` | same | same | | `unevaluatedItems` after a tuple | `additionalItems` | same | dropped | | `prefixItems` + `items` | tuple `items` + `additionalItems` | same | `items` accepting any element schema, `maxItems` for a closed tuple | | `dependentRequired`, `dependentSchemas` | `dependencies` | same | dropped | | `$dynamicRef`, `$recursiveRef` | `$ref` | same | same | | `const` | kept | `enum` | `enum` | | numeric `exclusiveMinimum` / `exclusiveMaximum` | kept | `minimum` / `maximum` + boolean | same | | `true` / `false` schemas | kept | `{}` / `{not: {}}` | same | | `contains`, `propertyNames`, `if` / `then` / `else` | kept | dropped | dropped | | `examples` | kept | dropped | the first as `example` | | `contentEncoding: base64`, `contentMediaType` | kept | dropped | `format: byte` / `binary` | | `type: [T, 'null']`, a `{type: 'null'}` alternative | kept | kept | `type: T`, `nullable: true` | | `type` with several names | kept | kept | `anyOf` of single-type schemas | | `patternProperties` | kept | kept | `^name$` patterns become `properties`, others dropped | | `$ref` with siblings | kept | kept | wrapped in `allOf` | `$anchor`, `$dynamicAnchor`, `$vocabulary`, `minContains`, `maxContains` and `contentSchema` have no counterpart in any target. Everything dropped or approximated is reported on the standard error, one line per keyword with its JSON pointer in the source, so that the document on the standard output stays usable. Specification extensions (`x-...`), annotations and the keywords the target has are copied as they are, in the order of the input. ## WSDL 1.1 input The command reads a WSDL 1.1 document whose SOAP 1.1 or SOAP 1.2 bindings are document/literal over HTTP, with the XML Schemas of its types, and writes an OpenAPI 3.1 document. The result lints without errors with the `recommended` ruleset (see [Linting](#linting-the-result)). It serves in [`apigenie-server`](/docs/reference/server), which validates SOAP requests and answers SOAP envelopes. [`diff`](/docs/reference/cli/diff) and the [generators](/docs/reference/generator) read it like any other OpenAPI document. The WSDL documents it imports (`wsdl:import`) and the schemas (`xs:import` and `xs:include` with a `schemaLocation`) are read from files, relative to the document that names them. Remote documents (`http:` and `https:`) are not fetched: download them and point the `location` or `schemaLocation` at the copies. A schema that isn't fetched is reported, and the elements, types and attributes of its namespace then accept any value. ### Operations Each operation of a SOAP binding becomes a `POST` operation: - **Path:** the path of the port's `soap:address`, followed by the operation's name. The operations of a port share one address in SOAP, but an OpenAPI path has one `POST`, so each operation gets a path of its own. For `https://api.example.com/soap/greeter`, the operation `Greet` is `POST /soap/greeter/Greet`. The address's origin is the server. A binding that no port uses gets `/{binding}/{operation}` and no server. - **Extensions:** `x-soap-address` is the port's address, and `x-soap-action` the operation's SOAPAction. - **Tag and operationId:** the tag is the port type. The operationId is the operation's name, prefixed with the port type (or the port) when several operations have that name. - **Description:** the operation's `wsdl:documentation`, or a sentence naming the operation when it has none. - **SOAP 1.1 and 1.2:** a binding of each version for one port type at one address makes one operation, with a `text/xml` body (the SOAP 1.1 envelope) and an `application/soap+xml` body (the SOAP 1.2 envelope). `apigenie-server` answers in the media type of the request. ### Bodies and responses Request and response bodies are SOAP envelopes. Their schemas carry the [`xml` objects](/docs/reference/server/validation#xml-bodies) that map the envelope's XML to the schema and back: - **Envelope:** the root is `soap:Envelope`. Its `Body` holds an element per body part of the message, and its `Header` the `soap:header` parts. The Header also accepts header blocks that the WSDL doesn't declare, such as WS-Addressing's. - **Responses:** the output message is the `200` response. A one-way operation answers `202` without content. - **Faults:** the `500` response is a SOAP Fault, with the faults of the operation in its `detail` (SOAP 1.1) or `Detail` (SOAP 1.2). The global elements and types the messages use become schemas in `components`: - **Elements and types:** an element and a type of the same name are `X` and `XType`. - **Content models:** `xs:sequence` and `xs:all` become objects with `additionalProperties: false`. `minOccurs` gives `required`, and a repeated element becomes an array whose items repeat in the parent element. A required `xs:choice` of required elements becomes `oneOf` of its alternatives. - **Attributes and text:** an attribute is a property with `xml: {attribute: true}`. The text of an element with simple content is a `value` property with `xml: {x-nodeType: text}`. - **Facets and values:** `nillable` adds `null` to the type, `default` becomes `default`, and `fixed` becomes `const`. Enumerations, lengths, bounds and patterns become their JSON Schema keywords. - **Built-in types:** each gets a type and a format; an `xs:int` is `{type: integer, format: int32}`, an `xs:dateTime` is `{type: string, format: date-time}`. - **Namespaces:** every `xml` object with a namespace has a prefix, the one the WSDL declares when it is free. Elements are qualified as `elementFormDefault` (or `form`) says. - **Descriptions:** `xs:documentation` becomes the description. ### Limits What has no exact counterpart is approximated, and told on the standard error as a warning with its file, line and column. Warnings with the same text are told once, followed by "(and N more like this)". - `xs:any`, `xs:anyAttribute` and `xs:anyType` accept any content: the object gets `additionalProperties: true` and `x-apigenie-lint-disable: [schema-no-additional-properties]`. - Substitution groups aren't followed: only the head element is accepted where it is used. Abstract elements and types are accepted as they are declared. - A type extending another one copies its content. An element of a derived type (`xsi:type`) isn't accepted in place of its base. - Mixed content: the text between child elements isn't described. - A list type becomes a string of space-separated values. - A repeated `xs:sequence` or `xs:choice` becomes an array per element; the order across elements is lost. - `xs:decimal` becomes a `double`, and integer types without bounds (`xs:integer`, `xs:nonNegativeInteger`...) an `int64`. - `totalDigits` is dropped, and so is `fractionDigits` other than 0. Patterns using `\i`, `\c`, `\p{Is...}` or character class subtraction are dropped. - `xs:redefine` and `xs:override` are read as `xs:include`. - A message part with a `type` instead of an `element` becomes an element in no namespace. - HTTP and MIME bindings are left out. So are operations in rpc style or with encoded use, next to document/literal ones. - WS-Policy, WS-Addressing, WS-Security and other WS-* extensions aren't read, and neither are MIME attachments (MTOM, SwA). - WSDL has no version: `info.version` is `1.0.0`. These documents are refused, with exit status 2: - documents that aren't well-formed XML, and WSDL 2.0 documents; - documents with a missing local import, or with a reference to something that isn't defined; - documents without a document/literal SOAP binding over HTTP: rpc/encoded and rpc/literal services, and SOAP over other transports. The message names the binding and its style and use. The importer converts WSDL to OpenAPI only: it doesn't generate SOAP clients or servers, and it doesn't write WSDL. ### Linting the result The converted document has no errors with the `recommended` ruleset. Some warnings stay, because they concern what WSDL doesn't describe or names WSDL sets: - security and rate limits: `operation-security-defined` and `operation-rate-limiting-defined`; - the length of strings: `schema-constraints`; - a binding without an address: `servers-defined`; - large services: `paths-max-count`; - the address's case: `paths-well-formed`; - date element names: `schema-datetime-suffix`. Two more come from XML Schema constructs: - `schema-discriminator-defined`: the alternatives of an `xs:choice` are told apart by their element, not by a property; - `schema-no-optional-nullable-properties`: an optional nillable element can be absent or `xsi:nil`, which differ in XML. ## Options ### --from The source: `swagger2` (Swagger 2.0), `wsdl` (WSDL 1.1) or `jsonschema` (a JSON Schema document, since 0.11.0). Without it, an XML input is WSDL, a document with a `swagger` member Swagger 2.0, and any other input a JSON Schema. ### --to Required. The target: `openapi32` (OpenAPI 3.2) for Swagger 2.0, `openapi31` (OpenAPI 3.1) for WSDL, and `draft7`, `draft4` or `openapi30` (the Schema Object of OpenAPI 3.0) for a JSON Schema, since 0.11.0. Another pair exits with status 2. ### --format Serialization of the output: `json` or `yaml`. Defaults to the format of the input, and to YAML for WSDL. ### -o, --output Path of the converted document. Without it, the document is written to the standard output. ## Exit status | Status | Meaning | | ------ | ------- | | 0 | The document was converted | | 2 | Invalid arguments (a missing `--to`, an unknown target or format, a target the source doesn't convert to), the input file can't be read, it isn't a valid Swagger 2.0 document, or the WSDL document can't be converted (the problems are listed on the standard error) | ## Examples Convert a YAML document and print the result: ```sh apigenie convert --to openapi32 petstore.yaml ``` Convert to a JSON file: ```sh apigenie convert --to openapi32 --format json -o petstore.openapi.json petstore.yaml ``` Downgrade a 2020-12 schema to draft-07, keeping the notes apart from the result: ```sh apigenie convert --to draft7 -o order.draft7.json order.schema.json 2> notes.txt ``` Convert a WSDL document, lint the result and serve it: ```sh apigenie convert --to openapi31 -o greeter.yaml greeter.wsdl apigenie lint greeter.yaml apigenie-server greeter.yaml ``` For this Swagger 2.0 input: ```yaml swagger: "2.0" info: {title: Pets, version: "1.0"} host: api.example.com basePath: /v1 schemes: [https, http] consumes: [application/json] produces: [application/json] securityDefinitions: basic: {type: basic} paths: /pets: post: operationId: addPet parameters: - {name: body, in: body, required: true, schema: {$ref: '#/definitions/Pet'}} responses: "201": {description: Created, schema: {$ref: '#/definitions/Pet'}} definitions: Pet: type: object properties: name: {type: string, x-nullable: true} photo: {type: file} ``` the command writes: ```yaml openapi: 3.2.0 info: title: Pets version: "1.0" servers: - url: https://api.example.com/v1 - url: http://api.example.com/v1 paths: /pets: post: operationId: addPet responses: "201": description: Created content: application/json: schema: $ref: "#/components/schemas/Pet" requestBody: content: application/json: schema: $ref: "#/components/schemas/Pet" required: true components: schemas: Pet: type: object properties: name: type: - string - "null" photo: type: string format: binary securitySchemes: basic: type: http scheme: basic ``` For this WSDL input: ```xml Greets someone. ``` the command writes (the 500 response and the shared `Soap11Header` and `Soap11Fault` components left out): ```yaml openapi: 3.1.0 info: title: GreeterService summary: The SOAP service GreeterService, converted from WSDL description: The operations of the SOAP service GreeterService. Each operation takes and returns a SOAP envelope; its path is the address of the service followed by the name of the operation. version: 1.0.0 x-wsdl-target-namespace: urn:example:greeter servers: - url: https://api.example.com tags: - name: Greeter description: The operations of the port type Greeter. paths: /soap/greeter/Greet: post: tags: - Greeter description: Greets someone. operationId: Greet requestBody: required: true content: text/xml: schema: type: object properties: Header: $ref: "#/components/schemas/Soap11Header" Body: type: object xml: namespace: http://schemas.xmlsoap.org/soap/envelope/ prefix: soap properties: Greet: $ref: "#/components/schemas/Greet" xml: name: Greet namespace: urn:example:greeter prefix: g required: - Greet additionalProperties: false required: - Body additionalProperties: false xml: name: Envelope namespace: http://schemas.xmlsoap.org/soap/envelope/ prefix: soap responses: "200": description: The response of Greet. content: text/xml: schema: type: object properties: Header: $ref: "#/components/schemas/Soap11Header" Body: type: object xml: namespace: http://schemas.xmlsoap.org/soap/envelope/ prefix: soap properties: GreetResponse: $ref: "#/components/schemas/GreetResponse" xml: name: GreetResponse namespace: urn:example:greeter prefix: g required: - GreetResponse additionalProperties: false required: - Body additionalProperties: false xml: name: Envelope namespace: http://schemas.xmlsoap.org/soap/envelope/ prefix: soap x-soap-action: urn:example:greeter/Greet x-soap-address: https://api.example.com/soap/greeter components: schemas: Greet: type: object properties: name: type: string xml: namespace: urn:example:greeter prefix: g times: type: integer format: int32 xml: namespace: urn:example:greeter prefix: g required: - name additionalProperties: false xml: name: Greet namespace: urn:example:greeter prefix: g GreetResponse: type: object properties: greeting: type: array items: type: string xml: namespace: urn:example:greeter prefix: g minItems: 1 required: - greeting additionalProperties: false xml: name: GreetResponse namespace: urn:example:greeter prefix: g ``` `apigenie-server greeter.yaml` then answers this request with a `GreetResponse` envelope, and a request without `name` with a 422 problem (`body/Body/Greet: required property 'name' is missing`): ```sh curl -X POST http://127.0.0.1:4010/soap/greeter/Greet -H 'Content-Type: text/xml' \ --data ' Ada ' ``` --- # apigenie credits Source: https://apigenie.pl/docs/reference/cli/credits Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md). Its other pages: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [format](https://apigenie.pl/docs/reference/cli/format.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md), [test](https://apigenie.pl/docs/reference/cli/test.md). Prints the open-source libraries API Genie is built with: the name, the project page and a line on what each one does, as their licenses ask. ## Usage ```sh apigenie credits ``` The output is a list with one entry per library, the same for every command-line tool of the version installed: ```text API Genie uses the following open-source libraries: - argparse (https://github.com/p-ranav/argparse) Command line argument parser. - {fmt} (https://github.com/fmtlib/fmt) C++ formatting library. ``` The command has no options and exits with 0. ## See also - [license](/docs/reference/cli/license): The license of API Genie, and the license text of each library. --- # apigenie diff Source: https://apigenie.pl/docs/reference/cli/diff Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md). Its other pages: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [format](https://apigenie.pl/docs/reference/cli/format.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md), [test](https://apigenie.pl/docs/reference/cli/test.md). Compares two versions of an OpenAPI, Swagger 2.0 or AsyncAPI document, of a Protobuf file or of a GraphQL schema, and reports every change with its severity, breaking, non-breaking or non-functional, as the [rules](/docs/reference/cli/diff/rules) define it. A script reads the status, release notes the changelog, a review the detailed list, and `--update-version` writes the version the changes call for into the document. ## Usage ```sh apigenie diff [OPTIONS] SOURCE_FILE DEST_FILE apigenie diff --report status|changelog|detailed [--formatter NAME] SOURCE_FILE DEST_FILE apigenie diff --update-version SOURCE_FILE DEST_FILE ``` Both files must be OpenAPI 3.x documents, both Swagger 2.0 documents, both AsyncAPI 3.x documents, both Protobuf files or both GraphQL files. Without options, the changelog of the two versions is printed in the `stylish` format, and the exit status says whether a change is breaking: ```sh apigenie diff api/v1/openapi.yaml api/openapi.yaml ``` ## Options | Option | Description | | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--config FILE` | The configuration file. Without it, the project's `apigenie.yaml` is read (see [Configuration](/docs/reference/cli/configuration#where-the-file-is-found)). | | `--no-config` | Compares with the `recommended` rules, without looking for a configuration file. | | `--report` | What to print: `status`, `changelog` (the default) or `detailed`. | | `--formatter` | `html`, `json`, `markdown`, `stylish` (the default), `unix` or `visualstudio`. | | `--bundle` | Bundles the local files each OpenAPI document references into it before comparing, as [bundle](/docs/reference/cli/bundle) does, so that what the references lead to is compared. Without it, a reference to another file is compared by its `$ref`. A reference to a URL can't be bundled. Can't be combined with `--update-version`. | | `--update-version` | Updates `info.version` of the destination file to the smallest version compatible with the changes (a new major version for breaking changes, minor for non-breaking and patch for non-functional ones), keeping the rest of the file intact. | | `--today DATE` | The date of the comparison (`YYYY-MM-DD`) for the `sunset_passed` condition of the OpenAPI rules: a deprecated element whose `x-sunset` date is on or before it may go. Defaults to the current date; it has no effect on the other formats. | ## Exit status | Status | When | | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | 0 | No breaking change, or, with `--update-version`, the version was written. | | 1 | At least one breaking change. | | 2 | A file cannot be read or compared, the configuration is invalid, or `--update-version` is given for Protobuf or GraphQL files, which have no version. | See the [exit statuses](/docs/reference/cli#exit-status) shared by the five binaries. ## OpenAPI documents For OpenAPI 3.0, 3.1 and 3.2 documents the differ compares the metadata (`info`, servers, security, tags, external documentation), the paths and webhooks with their operations, the parameters, request bodies, responses, headers, links and callbacks of each operation, the components and the security schemes, following references within the document. The severity of a change to a schema depends on the direction of the data: parameters and request bodies get the `request` rules, responses the `response` ones, and a component schema the stricter of the directions it is used in. The rules, and the conditions under which a deprecated element may go, are described under [Configuration](#configuration). A reference to another file or a URL, a schema's too, is compared by its `$ref` (the `reference.$ref` rule, which a schema's change is reported under as `schema.$ref`): the same `$ref` on both sides is no change, and another one changes the item that holds it, with a `reference.$ref` change (`breaking` in the recommended rules, as another reference may lead to anything). A parameter, response, path or component in another file that is added or removed follows the rule of its place, with the strictest facts: a parameter may be required. The changelog lists a parameter in another file by its `$ref`, and nothing for a path in another file, whose operations it can't name: the detailed report lists that change. With `--bundle`, the local files are bundled into the documents first, and what the references lead to is compared; changes in the bundled content have no position. ## Swagger documents A file is treated as Swagger when its root object has a `swagger` field. For Swagger documents the differ compares the host, the base path, the schemes, the consumed and produced media types, paths, operations, parameters, responses and their headers and examples, schemas, security definitions, security requirements and tags. Parameters are matched by their location and name, e.g. `query:limit`, so a parameter moved from the query to a header is a removed and an added one. An operation has at most one body parameter, whose name is only documentation: it is matched as `body`. Security requirements are alternatives, matched by the names of their schemes, so their order doesn't matter. References to definitions, parameters and responses are followed, and their changes are reported where they are used as well as where they are defined. As for OpenAPI documents, the severity of a change to a schema depends on the direction of the data: parameters, including body parameters, and consumed media types get the `request` rules, responses and produced media types the `response` ones. Definitions get the stricter of the two, and read-only properties don't matter in requests. The changelog report lists the changed metadata (including the host, the base path, the schemes, the media types and the security of the whole API), the added, removed and modified operations, with the changes of each modified one, and the paths whose own parameters changed. ## AsyncAPI documents A file is treated as AsyncAPI when its root object has an `asyncapi` field. For AsyncAPI documents the differ compares servers, channels, operations, messages with their payloads and headers, security schemes, bindings and components. Bindings of HTTP, WebSockets, Kafka, AMQP and MQTT are compared property by property, those of other protocols as whole values; schemas in formats other than AsyncAPI and JSON Schema, e.g. Avro, are compared as whole values too. The severity of a change to a message depends on who sends it. The messages of `receive` operations are sent by other parties to the application, those of `send` operations by the application. A reply flows the other way than the messages of its operation. For example, a new required payload property breaks the senders of a received message, while the receivers of a sent message can ignore it. Messages used in both directions, or by no operation, get the stricter severity. The changelog report lists the changed metadata, and the added, removed and modified servers, channels and operations, with the changes of each modified one. Changes of components are shown where the components are used. ## Protobuf files Files with the `.proto` extension are compared as Protobuf (proto3) files; both files must be Protobuf files. The differ compares the package, imports and options of the files, and their messages, enums, services and extend blocks, down to fields, oneofs, enum values, methods, reserved numbers and names, options and comments. Declarations are matched the way the programs that use them find them: - messages, enums, services, oneofs and methods by their names; - fields and enum values by their numbers, which identify them in the encoded data. A renamed field is a modified field; a field that got another number is a removed and an added one; - extend blocks by the type they extend; - reserved numbers as sets, so `reserved 1, 2, 3;` equals `reserved 1 to 3;`. Type names are resolved before they are compared, so `Address`, `User.Address` and `.shop.v1.User.Address` are the same type when they name the same message, and renaming the package is one change rather than a change of every type. The files are compared on their own: the files they import are not read, and the types those declare are compared by their names. To compare imported declarations as well, [bundle](/docs/reference/cli/bundle) both versions first. With the `recommended` rules, a change is breaking when it breaks the programs exchanging encoded messages (the binary or the JSON encoding) or the code compiled against the generated classes: removing or renaming a declaration, changing the type, the label or the oneof of a field, the types or the streaming of a method, the package, or an option that decides the names of the generated code (e.g. `go_package`). Adding declarations is non-breaking, and comments are non-functional. Removing a field or an enum value is non-breaking when the destination file reserves its number, which is how Protobuf files retire them. Changes are reported at their positions in the destination file; what has been removed is reported at the closest enclosing declaration that is still there. The changelog report lists the changed metadata (package, imports, file options), and the added, removed and modified messages, enums, services and extensions, with the changes of each modified one: ```text shop.proto 19 1 breaking Modified message 'Customer' 19 1 non-breaking Removed field 'fax' 25 3 breaking Modified field 'full_name' 25 3 breaking Modified field name 36 3 non-breaking Modified message 'Address' 39 5 non-breaking Added field 'country' ``` ## GraphQL files Files with the `.graphql`, `.graphqls` or `.gql` extension are compared as GraphQL schemas; both files must be GraphQL files. The differ compares their type systems: the root operation types, the types of every kind with their fields, arguments, input fields, default values, interfaces, union members and enum values, the directive definitions, the directives applied to all of these, and descriptions. Operations and fragments are ignored. Type extensions (`extend type`, `extend schema`, ...) are merged into what they extend, so moving a field from a type into an extension, or reordering definitions, is not a change. Everything is matched by its name. When a schema has no `schema` definition, the types named `Query`, `Mutation` and `Subscription` are its root operation types, so adding a `schema` definition that names them changes nothing. The files are compared on their own: types defined elsewhere are compared by their names. With the `recommended` rules, a change is breaking when operations that were valid become invalid, or when clients can no longer read their results, as graphql-js's `findBreakingChanges()` decides it: - removing a type, a field, an argument, an input field, an enum value, a union member, an implemented interface, a directive or one of its locations, or changing the kind of a type or a root operation type; - adding a required argument or input field: one with a non-null type and no default value; - changing a type in an incompatible way. The type of a field may become stricter (`String` to `String!`, `[String]` to `[String!]!`); the type of an argument or input field may become looser (`String!` to `String`). Named types must stay the same, and lists must stay lists; - removing the default value of a non-null argument or input field, which operations that omitted it relied on; - making a directive non-repeatable, or adding `@oneOf` to an input type. Additions are non-breaking, as are changed default values and applied directives such as `@deprecated`; descriptions are non-functional. Changes are reported at their positions in the destination file; what has been removed is reported at the closest enclosing definition that is still there. The changelog report lists the changed metadata (root operation types, the description and the directives of the schema), and the added, removed and modified scalars, objects, interfaces, unions, enums, input objects and directives, with the changes of each modified one: ```text shop.graphql 36 1 breaking Modified object 'Customer' 44 3 non-breaking Added field 'phone' 36 1 breaking Removed field 'fax' 38 3 non-breaking Modified field 'name' 38 3 non-breaking Modified field type ``` ## JSON output With `--formatter json` every report is an object whose `formatVersion` member is the version of the format. It changes only when a member is removed or changes meaning (see [Compatibility](/docs/reference/cli/compatibility)). The JSON Schema of the three reports is [`apigenie-diff-report.json`](https://apigenie.pl/schemas/apigenie-diff-report.json). - `--report status`: `{ "formatVersion": 1, "status": "breaking" }`. - `--report changelog`: `formatVersion`, `metadata` (which top-level fields changed) and groups of added, modified and removed items named after the elements of the format, e.g. `added`, `modified` and `removed` operations for OpenAPI or `channels`, `operations` and `servers` for AsyncAPI. - `--report detailed`: `formatVersion` and `changes`, every change in document order: ```json5 { "formatVersion": 1, "changes": [ { "type": "key_removed", "severity": "breaking", "target": "paths", "config_key": "paths", "key": "/pets/{id}", "line": 9, "column": 3 } ] } ``` API Genie 0.9 and earlier wrote the reports without `formatVersion`, and the detailed one as the bare `changes` array. ## Configuration The differ is configured in the `commands.diff` block of the [configuration file](/docs/reference/cli/configuration) given with `--config`. The block itself configures the differ for OpenAPI documents; its `swagger`, `asyncapi`, `protobuf` and `graphql` sections configure the other formats. Without `--config`, or without a section for a format, the format is compared with its `recommended` rules. A block or section starts only from the rulesets in its `extends`, so list `recommended` there to change only some of the recommended rules. [Rules and severities](/docs/reference/cli/diff/rules) says what the severities mean, how a report names the rule that rated a change, and lists the `recommended` rules of each standard. ### diff The configuration of the differ for OpenAPI documents. It accepts these keys: | Key | Description | | --- | ----------- | | `extends` | Rulesets to start from: `recommended`. | | `rules` | Severities of the changes of the properties of each node type. | | `request`, `response` | Overlays of `rules` for the data sent by API consumers (parameters, request bodies) and by API providers (responses). Inside callbacks and webhooks the directions are swapped. A component schema takes the direction of the places it is used in (following the references between schemas, in either document); one used both ways, or nowhere, gets the stricter severity. Only node types and properties, no `defaults` or `extensions`. | | `overrides` | A list of `where` (`location`: one pattern or a list of them, and optionally `direction`: `request` or `response`) and `rules` applied to the matching locations. | The rules set a severity (`breaking`, `non_breaking`, `non_functional`, `none` to ignore the change, or `nested` to take the highest severity of the changes inside) for the properties of each node type: | Node type | Properties | | --------- | ---------- | | `openapi` | `openapi`, `info`, `jsonSchemaDialect`, `servers`, `paths`, `webhooks`, `components`, `security`, `tags`, `externalDocs` | | `info` | `title`, `summary`, `description`, `termsOfService`, `contact`, `license`, `version` | | `server` | `url`, `description`, `variables` | | `serverVariable` | `enum`, `default`, `description` | | `components` | `schemas`, `responses`, `parameters`, `examples`, `requestBodies`, `headers`, `securitySchemes`, `links`, `callbacks`, `pathItems` | | `pathItem` | `summary`, `description`, `parameters`, `operations`, `servers` | | `operation` | `tags`, `summary`, `operationId`, `description`, `externalDocs`, `deprecated`, `parameters`, `requestBody`, `responses`, `callbacks`, `security`, `servers` | | `parameter` | `name`, `in`, `description`, `required`, `deprecated`, `allowEmptyValue`, `style`, `explode`, `allowReserved`, `schema`, `content`, `example`, `examples` | | `header` | the properties of `parameter`, except `in` and `style` | | `requestBody` | `description`, `content`, `required` | | `response` | `description`, `headers`, `content`, `links` | | `mediaType` | `schema`, `encoding`, `example`, `examples` | | `encoding` | `contentType`, `headers`, `style`, `explode`, `allowReserved` | | `link` | `description`, `server`, `operationRef`, `operationId`, `parameters`, `requestBody` | | `example` | `summary`, `description`, `value`, `externalValue` | | `reference` | `$ref`, `summary`, `description` | | `schema` | `id`, `dialect`, `type`, `properties`, `required`, `readOnly`, `writeOnly`, `enum`, `discriminator`, `xml`, and the other JSON Schema keywords | | `discriminator` | `propertyName`, `mapping` | | `securityScheme` | `name`, `description`, `type`, `in`, `scheme`, `bearerFormat`, `flows`, `openIdConnectUrl` | | `oauthFlows` | `implicit`, `password`, `clientCredentials`, `authorizationCode` | | `oauthFlow` | `authorizationUrl`, `tokenUrl`, `refreshUrl`, `scopes` | | `paths`, `responses`, `callback`, `securityRequirement` | none: the node type itself is set to the rules of its items, e.g. `paths: { remove_item: breaking }` | | `contact`, `license`, `tag`, `externalDocumentation`, `xml` | their fields | A property is set to a severity, or to separate severities for `add`, `remove` and `modify`; lists and maps take `add_item`, `remove_item`, `modify_item`, `add_first_item` and `remove_last_item`. Properties that every node has, e.g. `parameter.name` or `schema.readOnly`, can only be modified, so they take a severity or `modify`. A severity can depend on a condition: `{ if: CONDITION, then: SEVERITY, else: SEVERITY }`, where the condition is `required` (the added or removed item is required), `deprecated` (it is deprecated), `sunset_passed` (it is deprecated and its `x-sunset` date is on or before the date of the comparison, `--today`), or `true` / `false` (the new value of a boolean property). The `extensions` property of a node type configures its `x-` extensions by name, with `*` for the extensions that are not listed, and `defaults.extensions` applies to all node types. `sunset_passed` is how the `recommended` rules let a deprecated element go once its window has closed: the `remove_item` of operations, path items (every operation deprecated and sunset), parameters, component schemas and parameters, response properties and their `required` items, and request enum values is non-breaking when the condition holds and breaking otherwise. An `x-sunset` is an RFC 3339 date (`2027-01-06`) or date-time next to `deprecated: true`; a property may carry them where it is used, as siblings of its `$ref`, or where it is defined; an enum value is deprecated when the schema's `x-deprecated-enum` array lists it, and the schema's `x-sunset` says when it may go. Deprecating itself (`deprecated: true` on an operation, a parameter, a header or a schema) is non-breaking: it announces the removal, and the removal is the breaking change. [`apigenie evolve plan`](/docs/reference/cli/evolve) writes documents that follow this convention. ```yaml version: '1.0' commands: diff: extends: [recommended] rules: defaults: extensions: non_functional pathItem: operations: # deprecated operations may be removed remove_item: if: deprecated then: non_breaking else: breaking response: schema: properties: # clients reject unknown properties add_item: breaking overrides: - where: location: /paths/~1internal~1*/** rules: operation: parameters: non_functional ``` The locations of `overrides` are JSON pointers into the document, where `*` matches any part of a segment and `**` any number of segments, e.g. `/paths/~1pets/get/parameters/query:limit`, `/paths/**/properties/name` or `/components/schemas/Pet/**`. The Swagger, AsyncAPI, Protobuf and GraphQL sections accept the same severities, rule forms and location patterns. ### diff.protobuf The configuration of the differ for Protobuf files. It accepts `extends` (`recommended`), `rules` and `overrides`; there are no `request` and `response` overlays. The OpenAPI settings of the `diff` block do not apply to Protobuf files; without this block, Protobuf files are compared with the `recommended` rules. The rules set a severity (`breaking`, `non_breaking`, `non_functional`, `none` to ignore the change, or `nested` to take the highest severity of the changes inside) for the properties of each node type: | Node type | Properties | | --------- | ---------- | | `file` | `package`, `imports`, `messages`, `enums`, `services`, `extends`, `comment` | | `import` | `kind` (`public` or `weak`) | | `message` | `fields`, `oneofs`, `messages`, `enums`, `extends`, `reservedNumbers`, `reservedNames`, `comment` | | `field` | `name`, `type`, `label`, `oneof`, `comment` | | `oneof` | `comment` | | `enum` | `values`, `reservedNumbers`, `reservedNames`, `comment` | | `enumValue` | `name`, `comment` | | `service` | `methods`, `comment` | | `method` | `inputType`, `outputType`, `clientStreaming`, `serverStreaming`, `comment` | | `extend` | `fields`, `comment` | Map fields and the fields of oneofs are configured as `field`. The `comment` of a declaration is its leading and trailing comment, that of a file the comment of its `syntax` statement. A property is set to a severity, or to separate severities for `add`, `remove` and `modify` (lists: `add_item`, `remove_item`, `modify_item`, `add_first_item`, `remove_last_item`). Properties that every declaration has, e.g. the `name`, `type` and `label` of a field or the types of a method, take only a severity or `modify`. A severity can depend on a condition: | Condition | Holds when | | --------- | ---------- | | `reserved` | the number of the removed field or enum value is reserved in the destination file | | `deprecated` | the added, removed or modified field or enum value has `deprecated = true` | | `wire_compatible` | the old and the new type (or label) of a field are encoded the same way, e.g. `int32` and `int64`, `string` and `bytes`, or a field with and without `optional` | | `true`, `false` | the new value of a boolean option is `true` or `false` (the old value for a removed option) | Options are configured by their names as written in the file, in the `options` property of `file`, `message`, `field`, `oneof`, `enum`, `enumValue`, `service` and `method`; `*` stands for the options that are not listed, and `defaults.options` applies to all node types. ```yaml version: '1.0' commands: diff: protobuf: extends: [recommended] rules: defaults: options: non_functional field: # only the encoded data matters: names and compatible types may change name: non_breaking type: modify: if: wire_compatible then: non_breaking else: breaking options: json_name: non_breaking "(validate.rules)": breaking message: fields: # removing a field is breaking even when its number is reserved remove_item: breaking overrides: - where: location: /messages/Internal*/** rules: message: fields: none ``` The locations of `overrides` follow the structure of the file, with declarations by their names, e.g. `/messages/User/fields/email/type`, `/messages/User/messages/Address/**`, `/enums/Status/values/*` or `/services/Users/methods/Get`. ### diff.swagger The configuration of the differ for Swagger 2.0 documents. It accepts the same keys as the `diff` block itself: `extends`, `rules`, the `request` and `response` overlays and `overrides`. The properties are those of the Swagger node types: | Node type | Properties | | --------- | ---------- | | `swagger` | `swagger`, `info`, `host`, `basePath`, `schemes`, `consumes`, `produces`, `paths`, `definitions`, `parameters`, `responses`, `securityDefinitions`, `security`, `tags`, `externalDocs` | | `info` | `title`, `description`, `termsOfService`, `contact`, `license`, `version` | | `pathItem` | `$ref`, `parameters`, `operations` | | `operation` | `tags`, `summary`, `description`, `externalDocs`, `operationId`, `consumes`, `produces`, `parameters`, `responses`, `schemes`, `deprecated`, `security` | | `parameter` | `name`, `in`, `description`, `required`, `schema`, `type`, `format`, `allowEmptyValue`, `items`, `collectionFormat`, and the validation keywords | | `response` | `description`, `schema`, `headers`, `examples` | | `header`, `items` | `type`, `format`, `items`, `collectionFormat`, the validation keywords, and `description` for headers | | `schema` | `title`, `description`, `type`, `format`, the validation keywords, `items`, `allOf`, `properties`, `required`, `maxProperties`, `minProperties`, `additionalProperties`, `discriminator`, `readOnly`, `xml`, `externalDocs`, `example` | | `securityScheme` | `type`, `description`, `name`, `in`, `flow`, `authorizationUrl`, `tokenUrl`, `scopes` | | `securityRequirement` | `scopes` | | `contact`, `license`, `tag`, `externalDocumentation`, `xml` | their fields | The validation keywords are `default`, `multipleOf`, `maximum`, `exclusiveMaximum`, `minimum`, `exclusiveMinimum`, `maxLength`, `minLength`, `pattern`, `maxItems`, `minItems`, `uniqueItems` and `enum`. For `additionalProperties`, `add` applies when additional properties become allowed, `remove` when they become forbidden, and `modify` to changes of their schema. The OpenAPI settings of the `diff` block do not apply to Swagger documents; without this block, Swagger documents are compared with the `recommended` rules. ```yaml version: '1.0' commands: diff: extends: [recommended] swagger: extends: [recommended] rules: swagger: host: non_breaking pathItem: operations: # deprecated operations may be removed remove_item: if: deprecated then: non_breaking else: breaking overrides: - where: location: /paths/~1internal~1*/** rules: operation: parameters: non_functional ``` The locations of `overrides` follow the structure of the document, with parameters by their keys and security requirements by the names of their schemes, e.g. `/paths/~1pets/get/parameters/query:limit/maximum`, `/paths/~1pets/post/parameters/body/schema/properties/name` or `/definitions/Pet/**`. ### diff.graphql The configuration of the differ for GraphQL schemas. It accepts `extends` (`recommended`), `rules` and `overrides`, like `diff.protobuf`. The OpenAPI settings of the `diff` block do not apply to GraphQL files; without this block, GraphQL files are compared with the `recommended` rules. The node types and their properties are: | Node type | Properties | | --------- | ---------- | | `schema` | `query`, `mutation`, `subscription`, `types`, `directiveDefinitions`, `description` | | `type` | `kind` (of types of all kinds) | | `scalar` | `description` | | `object` | `interfaces`, `fields`, `description` | | `interface` | `interfaces`, `fields`, `description` | | `union` | `members`, `description` | | `enum` | `values`, `description` | | `enumValue` | `description` | | `inputObject` | `fields`, `description` | | `field` | `type`, `arguments`, `description` | | `argument` | `type`, `defaultValue`, `description` | | `inputField` | `type`, `defaultValue`, `description` | | `directive` | `arguments`, `repeatable`, `locations`, `description` | The arguments of directive definitions are configured as `argument`. A severity can depend on a condition: | Condition | Holds when | | --------- | ---------- | | `required` | the added or removed argument or input field has a non-null type and no default value; for a default value, the type of the argument or input field is non-null | | `compatible` | the old and the new type of a field, argument or input field are compatible (see above) | | `deprecated` | the added or removed field, argument, input field or enum value has `@deprecated` | | `true`, `false` | the new value of `repeatable`, or of the only argument of an applied directive when it is a boolean (the old value for a removed directive) | Applied directives are configured by their names, without `@`, in the `directives` property of `schema`, `scalar`, `object`, `interface`, `union`, `enum`, `enumValue`, `inputObject`, `field`, `argument` and `inputField`; `*` stands for the directives that are not listed, and `defaults.directives` applies to all node types. Directives are compared with their arguments, whatever the order of the arguments and the form of the strings; the uses of a repeatable directive are compared together. ```yaml version: '1.0' commands: diff: graphql: extends: [recommended] rules: defaults: directives: non_functional field: directives: # authorization changes matter to clients auth: breaking enum: values: # deprecated values can be removed remove_item: if: deprecated then: non_breaking else: breaking overrides: - where: location: /types/Internal*/** rules: object: fields: none ``` The locations of `overrides` follow the structure of the schema, with definitions by their names, e.g. `/types/User/fields/email/type`, `/types/Query/fields/users/arguments/first/defaultValue`, `/types/Status/values/*`, `/directiveDefinitions/auth/locations/*` or `/query`. ### diff.asyncapi The configuration of the differ for AsyncAPI documents. It accepts the same keys as the `diff` block itself: `extends`, `rules`, `overrides`, and the `receive` and `send` overlays in place of `request` and `response` (also as the `direction` of an override). The properties are those of the AsyncAPI node types, e.g. `channel.address` or `message.payload`. The OpenAPI settings of the `diff` block do not apply to AsyncAPI documents; without this block, AsyncAPI documents are compared with the `recommended` rules. ```yaml version: '1.0' commands: diff: extends: [recommended] asyncapi: extends: [recommended] rules: channel: address: non_breaking send: schema: properties: # receivers reject unknown properties add_item: breaking overrides: - where: location: /channels/internal/** rules: message: payload: non_functional ``` ## See also - [Rules and severities](/docs/reference/cli/diff/rules): What the severities mean, the `recommended` rules of each standard, and what makes a breaking change acceptable. - [changelog](/docs/reference/cli/changelog): The changes between the revisions of a file in git, with the same rules. - [evolve](/docs/reference/cli/evolve): Writes the deprecations and sunsets the rules understand. - [Configuration](/docs/reference/cli/configuration): The configuration file, and where it is looked for. --- # Rules and severities Source: https://apigenie.pl/docs/reference/cli/diff/rules Part of the reference of [diff](https://apigenie.pl/docs/reference/cli/diff.md). `apigenie diff` rates every change between two versions of a document with a rule: the kind of node the change is in, the property that changed, and whether the property was added, removed or modified. Without a configuration, the rules are the `recommended` ruleset of the standard, listed below for each of them; a [configuration](/docs/reference/cli/diff#configuration) that names `recommended` in `extends` changes some of them. This page says what the severities mean, how a report names the rule that rated a change, and what makes a breaking change acceptable. ## Severities | Severity | In reports | What it means | | ---------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `breaking` | `breaking` | A client built against the old version fails: an operation it calls is gone, a parameter it does not send is required, a value it reads has another type. | | `non_breaking` | `non-breaking` | Old clients keep working; the change is there for new ones: a new operation, a new optional parameter, a new property in a response. | | `non_functional` | `non-functional` | Nothing a client sends or receives changes: a description, a summary, an example, a tag. | | `none` | `none` | The change does not count. The status and the changelog leave it out; the detailed report lists it. | | `nested` | | The property is an object or a list compared member by member, and the change takes the highest severity found inside: `info: nested` rates a changed `info` by its title, version and contact. | The status of a comparison is the highest severity of its changes. The command exits with status 1 when it is `breaking`, so a CI job fails on the pull request that would break a client, and with 0 otherwise. `--update-version` turns the status into a version: a new major version for `breaking`, minor for `non_breaking`, patch for `non_functional`. ## How a rule is written A rule names a node type, one of its properties, and the severity of a change of that property. The property takes one of these forms: - A severity alone, `host: breaking`, for a property a node always has, which can only be modified, and for a property whose addition, removal and modification weigh the same. - `add`, `remove` and `modify`, each with a severity, for an optional property: `license: {add: breaking, remove: non_breaking, modify: nested}`. - `add_item`, `remove_item` and `modify_item` for the items of a list or a map, such as the operations of a path item or the properties of a schema. `add_first_item` rates the first item of a list that was empty, and `remove_last_item` the last item of a list that becomes empty: the first value of an `enum` restricts what was unrestricted, and removing the last one lifts the restriction. - A condition in place of a severity: `{if: CONDITION, then: SEVERITY, else: SEVERITY}`, where the conditions are the ones [below](#conditions). The `defaults` node type sets what is not named elsewhere: `defaults.extensions` rates every `x-` extension of an OpenAPI, Swagger 2.0 or AsyncAPI document that no node type's `extensions` map names, `defaults.options` the Protobuf options no node type's `options` map names, and `defaults.directives` the GraphQL directives no node kind's `directives` map names. ## Conditions | Condition | Standards | Holds when | | ----------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `required` | OpenAPI, Swagger 2.0, AsyncAPI, GraphQL | The added or removed item is required: a parameter with `required: true`, a property listed in the schema's `required`, a GraphQL argument or input field of a non-null type without a default value. | | `deprecated` | OpenAPI, Swagger 2.0, Protobuf, GraphQL | The item is deprecated: `deprecated: true` on an operation, a parameter or a schema, an enum value listed in the schema's `x-deprecated-enum`, the `deprecated = true` option of a Protobuf field or enum value, `@deprecated` in GraphQL. | | `sunset_passed` | OpenAPI, Swagger 2.0 | The item is deprecated and its `x-sunset` date is on or before the date of the comparison, the current date or `--today`. | | `reserved` | Protobuf | The number of the removed field or enum value is reserved in the new file. | | `wire_compatible` | Protobuf | The old and the new type of a field are encoded the same way: `int32` and `int64`, `string` and `bytes`, a field with and without `optional`. | | `compatible` | GraphQL | The old and the new type are compatible for the direction of the data: a field may become non-null and an argument or input field nullable, a list stays a list. | | `true`, `false` | all | The new value of a boolean property, such as `repeatable` of a directive or a Protobuf option; the old value when the property was removed. | ## Direction A schema change weighs differently for the data clients send and the data they receive: a new required property breaks the clients that send the object and not those that receive it, and a removed property the other way round. The rules of a standard therefore come in layers. For OpenAPI and Swagger 2.0, `rules` applies everywhere, `request` replaces some of them for parameters and request bodies, and `response` for responses; inside callbacks and webhooks the directions are swapped. A component schema takes the direction of the places it is used in, following the references between schemas in either document; one used both ways, or nowhere, gets the stricter severity of the two. For AsyncAPI the directions are those of the application the document describes: `receive` applies to the messages of `receive` operations, which other parties send, and `send` to the messages of `send` operations, which other parties receive. Replies flow the other way than the messages of their operation, and a message used both ways, or by no operation, gets the stricter severity. Protobuf files and GraphQL schemas have no direction layers: a GraphQL argument or input field is always sent and a field always received, and the rules of each node kind say so. ## Reading a report The detailed report (`--report detailed`) lists every change with the node type and the property that rated it, and the severity the rule gave: ```text streetlights.yaml 38 5 breaking Removed asyncapi.servers['mtls-connections'] 128 7 non-breaking Added channel.messages['dimLight'] 167 7 non-functional Added schema.description ``` `asyncapi.servers['mtls-connections']` is a removed item of the `servers` property of the `asyncapi` node: the rule is `asyncapi.servers.remove_item`, `breaking` in the AsyncAPI table below. A report spells a node type of two words with an underscore, `security_scheme` or `path_item`, where the configuration and the tables write `securityScheme` and `pathItem`. The JSON report carries the same two names in `target` and `config_key`. The changelog report, the default, groups the changes by operation, channel, message or type and lists the rated changes of each one under it, with the same words. ## Accepting a breaking change A failed check leaves four ways forward, the first two of them without touching the rules. **Announce the removal first.** In OpenAPI and Swagger 2.0 documents, the `recommended` rules let a deprecated operation, path item, parameter, component schema, response property or request enum value go once its `x-sunset` date has passed, the `sunset_passed` condition. Mark it in one pull request, which is `non_breaking`, and remove it in another after the date: ```yaml paths: /v1/orders: get: deprecated: true x-sunset: 2027-01-31 ``` `x-sunset` is an RFC 3339 date or date-time next to `deprecated: true`, on the element itself, next to the `$ref` that uses it, or where it is defined; an enum value is deprecated when the schema's `x-deprecated-enum` lists it, and goes on the schema's `x-sunset` date. `--today` runs the comparison as of another date, to see the removal pass before then. [`apigenie evolve plan`](/docs/reference/cli/evolve) writes the deprecations and the removal in two waves. **Reserve the number.** In a Protobuf file, a removed field or enum value whose number is reserved is `non_breaking`, the `reserved` condition: the removal is deliberate, and no later field can take the number and misread the data of the old one. ```protobuf message Customer { reserved 7; reserved "telex"; string name = 1; } ``` **Change the rule.** When a change is breaking by the rules and not for the API's clients, say so in the `commands.diff` block of the [configuration](/docs/reference/cli/configuration), starting from `recommended` and overriding the rule, the same path as in the tables below. `overrides` limits a rule to the locations that match a pattern, and `none` turns a change off: ```yaml version: '1.0' commands: diff: extends: [recommended] rules: operation: # tags are not part of the contract of this API tags: none graphql: extends: [recommended] rules: object: fields: # fields marked @deprecated may go remove_item: if: deprecated then: non_breaking else: breaking overrides: - where: location: /paths/~1internal~1*/** rules: pathItem: operations: remove_item: non_breaking ``` The sections [diff](/docs/reference/cli/diff#diff), [diff.swagger](/docs/reference/cli/diff#diffswagger), [diff.asyncapi](/docs/reference/cli/diff#diffasyncapi), [diff.protobuf](/docs/reference/cli/diff#diffprotobuf) and [diff.graphql](/docs/reference/cli/diff#diffgraphql) of the diff reference describe the keys of each standard and the location patterns. **Ship a new major version.** When the break is intended, the check records it rather than blocks it: `--update-version` writes the major version the changes call for into the document, and the [GitHub Action](/docs/ci/github-action) with `fail-on: never`, or a job that ignores exit status 1, reports the changes without failing. ## Recommended rules The tables list the `recommended` ruleset of each standard as the CLI of this release applies it: the node type, the property, the rule in the form a configuration writes it, and the reason the ruleset gives. A standard with [directions](#direction) has a table per direction after its rules. ### OpenAPI | Node type | Property | Rule | Note | | --------- | -------- | ---- | ---- | | `defaults` | `extensions` | `non_functional` | | | `openapi` | `openapi` | `breaking` | | | | `info` | `nested` | | | | `jsonSchemaDialect` | `none` | | | | `servers` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `paths` | `nested` | | | | `webhooks` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `components` | `nested` | | | | `security` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `modify_item: nested` | `add_item`: Requirements are alternatives: adding one to existing ones is harmless, but requiring authentication where none was required breaks clients. | | | `tags` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `externalDocs` | `add: non_breaking`, `remove: non_breaking`, `modify: nested` | | | `info` | `title` | `breaking` | | | | `summary` | `non_functional` | | | | `description` | `non_functional` | | | | `termsOfService` | `breaking` | | | | `contact` | `nested` | | | | `license` | `add: breaking`, `remove: non_breaking`, `modify: nested` | | | | `version` | `none` | | | `contact` | `name` | `add: non_breaking`, `remove: breaking`, `modify: non_breaking` | | | | `url` | `add: non_breaking`, `remove: breaking`, `modify: non_breaking` | | | | `email` | `add: non_breaking`, `remove: breaking`, `modify: non_breaking` | | | `license` | `name` | `breaking` | | | | `identifier` | `breaking` | | | | `url` | `breaking` | | | `server` | `url` | `breaking` | | | | `description` | `non_functional` | | | | `variables` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | `serverVariable` | `description` | `non_functional` | | | | `default` | `breaking` | | | | `enum` | `add_item: non_breaking`, `remove_item: breaking` | | | `components` | `schemas` | `add_item: non_breaking`, `remove_item: {if: sunset_passed, then: non_breaking, else: breaking}`, `modify_item: nested` | `remove_item`: A deprecated schema may go once its `x-sunset` date has passed. | | | `responses` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `parameters` | `add_item: non_breaking`, `remove_item: {if: sunset_passed, then: non_breaking, else: breaking}`, `modify_item: nested` | | | | `examples` | `non_functional` | | | | `requestBodies` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `headers` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `securitySchemes` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `links` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `callbacks` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `pathItems` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | `paths` | | `add_item: non_breaking`, `remove_item: {if: sunset_passed, then: non_breaking, else: breaking}`, `modify_item: nested` | `remove_item`: A path whose operations are all deprecated may go once their sunset dates have passed. | | `pathItem` | `summary` | `non_functional` | | | | `description` | `non_functional` | | | | `parameters` | `add_item: {if: required, then: breaking, else: non_breaking}`, `remove_item: {if: sunset_passed, then: non_breaking, else: breaking}`, `modify_item: nested` | `remove_item`: A deprecated parameter may go once its `x-sunset` date has passed. | | | `operations` | `add_item: non_breaking`, `remove_item: {if: sunset_passed, then: non_breaking, else: breaking}`, `modify_item: nested` | `remove_item`: A deprecated operation may go once its `x-sunset` date has passed; to allow removing every deprecated operation, use `remove_item: { if: deprecated, then: non_breaking, else: breaking }`. | | | `servers` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | `operation` | `tags` | `non_breaking` | | | | `summary` | `non_functional` | | | | `operationId` | `breaking` | | | | `description` | `non_functional` | | | | `externalDocs` | `non_functional` | | | | `deprecated` | `non_breaking` | Deprecating announces a removal; the removal itself is the breaking change. | | | `parameters` | `add_item: {if: required, then: breaking, else: non_breaking}`, `remove_item: {if: sunset_passed, then: non_breaking, else: breaking}`, `modify_item: nested` | `remove_item`: A deprecated parameter may go once its `x-sunset` date has passed. | | | `requestBody` | `nested` | | | | `responses` | `nested` | | | | `callbacks` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `security` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `servers` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | `externalDocumentation` | `description` | `non_functional` | | | | `url` | `non_functional` | | | `parameter` | `name` | `breaking` | | | | `in` | `breaking` | | | | `description` | `non_functional` | | | | `required` | `modify: {if: true, then: breaking, else: non_breaking}` | | | | `deprecated` | `non_breaking` | | | | `allowEmptyValue` | `modify: {if: true, then: non_breaking, else: breaking}` | | | | `style` | `breaking` | | | | `explode` | `breaking` | | | | `allowReserved` | `modify: {if: true, then: non_breaking, else: breaking}` | | | | `schema` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `content` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `example` | `non_functional` | | | | `examples` | `non_functional` | | | `requestBody` | `description` | `non_functional` | | | | `required` | `add: {if: true, then: breaking, else: non_breaking}`, `remove: breaking`, `modify: {if: true, then: breaking, else: non_breaking}` | | | | `content` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | `mediaType` | `schema` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `encoding` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `example` | `non_functional` | | | | `examples` | `non_functional` | | | `encoding` | `contentType` | `breaking` | | | | `headers` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `style` | `breaking` | | | | `explode` | `breaking` | | | | `allowReserved` | `breaking` | | | `responses` | | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | `response` | `description` | `non_functional` | | | | `headers` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `content` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `links` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | `callback` | | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | `example` | `summary` | `non_functional` | | | | `description` | `non_functional` | | | | `value` | `non_functional` | | | | `externalValue` | `non_functional` | | | `link` | `description` | `non_functional` | | | | `server` | `non_breaking` | | | | `operationRef` | `non_breaking` | | | | `operationId` | `non_breaking` | | | | `parameters` | `non_breaking` | | | | `requestBody` | `non_breaking` | | | `header` | `name` | `breaking` | | | | `description` | `non_functional` | | | | `required` | `modify: {if: true, then: breaking, else: non_breaking}` | | | | `deprecated` | `non_breaking` | | | | `allowEmptyValue` | `breaking` | | | | `explode` | `breaking` | | | | `allowReserved` | `breaking` | | | | `schema` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `content` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `example` | `non_functional` | | | | `examples` | `non_functional` | | | `tag` | `name` | `breaking` | | | | `description` | `non_functional` | | | | `externalDocs` | `non_functional` | | | `reference` | `$ref` | `breaking` | | | | `summary` | `non_breaking` | | | | `description` | `non_functional` | | | `schema` | `id` | `breaking` | | | | `title` | `non_breaking` | | | | `description` | `non_functional` | | | | `type` | `breaking` | | | | `format` | `breaking` | | | | `const` | `breaking` | | | | `enum` | `add_item: breaking`, `remove_item: {if: sunset_passed, then: non_breaking, else: breaking}` | `remove_item`: A value listed in `x-deprecated-enum` may go once the schema's `x-sunset` date has passed. | | | `deprecated` | `non_breaking` | | | | `readOnly` | `non_functional` | | | | `writeOnly` | `non_functional` | | | | `minimum` | `breaking` | | | | `exclusiveMinimum` | `breaking` | | | | `maximum` | `breaking` | | | | `exclusiveMaximum` | `breaking` | | | | `multipleOf` | `breaking` | | | | `minLength` | `breaking` | | | | `maxLength` | `breaking` | | | | `pattern` | `breaking` | | | | `items` | `add: breaking`, `remove: non_breaking`, `modify: nested` | | | | `contains` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `minContains` | `breaking` | | | | `maxContains` | `breaking` | | | | `prefixItems` | `breaking` | | | | `minItems` | `breaking` | | | | `maxItems` | `breaking` | | | | `uniqueItems` | `breaking` | | | | `unevaluatedItems` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `required` | `breaking` | | | | `properties` | `add_item: non_breaking`, `remove_item: non_breaking`, `modify_item: nested` | | | | `patternProperties` | `add_item: non_breaking`, `remove_item: non_breaking`, `modify_item: nested` | | | | `propertyNames` | `non_breaking` | | | | `additionalProperties` | `breaking` | | | | `minProperties` | `breaking` | | | | `maxProperties` | `breaking` | | | | `unevaluatedProperties` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `allOf` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `oneOf` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `anyOf` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `not` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `if` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `then` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `else` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `anchor` | `none` | | | | `dynamicAnchor` | `none` | | | | `dynamicRef` | `none` | | | | `vocabulary` | `breaking` | | | | `contentEncoding` | `breaking` | | | | `contentMediaType` | `breaking` | | | | `contentSchema` | `nested` | | | | `discriminator` | `add: breaking`, `remove: non_breaking`, `modify: nested` | | | | `xml` | `nested` | | | | `externalDocs` | `non_functional` | | | | `examples` | `non_functional` | | | | `default` | `breaking` | | | | `dialect` | `breaking` | | | `discriminator` | `propertyName` | `breaking` | | | | `mapping` | `breaking` | | | `xml` | `name` | `breaking` | | | | `namespace` | `breaking` | | | | `prefix` | `breaking` | | | | `attribute` | `breaking` | | | | `wrapped` | `breaking` | | | `securityScheme` | `name` | `breaking` | | | | `description` | `non_functional` | | | | `type` | `breaking` | | | | `in` | `breaking` | | | | `scheme` | `breaking` | | | | `bearerFormat` | `breaking` | | | | `flows` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `openIdConnectUrl` | `breaking` | | | `oauthFlows` | `implicit` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `password` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `clientCredentials` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `authorizationCode` | `add: breaking`, `remove: breaking`, `modify: nested` | | | `oauthFlow` | `authorizationUrl` | `breaking` | | | | `tokenUrl` | `breaking` | | | | `refreshUrl` | `breaking` | | | | `scopes` | `add_item: breaking`, `remove_item: breaking`, `modify_item: non_functional` | | | `securityRequirement` | | `breaking` | | Severities that depend on the direction of data flow. They override `rules` in requests (parameters, request bodies; sent by API consumers) and responses (sent by API providers). Inside callbacks and webhooks the directions are swapped, as the API provider sends the requests there. Changes in places shared by both (e.g. component schemas) get the stricter of the request and the response severity. These defaults assume that servers and clients ignore unknown properties. For clients that reject them, set `response.schema.properties.add_item` to `breaking`. The `request` layer, for the parameters and the request bodies, replaces these rules of the layer above: | Node type | Property | Rule | Note | | --------- | -------- | ---- | ---- | | `schema` | `properties` | `add_item: {if: required, then: breaking, else: non_breaking}`, `remove_item: non_breaking` | `add_item`: Existing clients don't send new required properties. | | | `required` | `add_item: breaking`, `remove_item: non_breaking` | | | | `enum` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: {if: sunset_passed, then: non_breaking, else: breaking}`, `remove_last_item: non_breaking` | `add_first_item`: Restricting a value to a set of values. `remove_item`: A value listed in `x-deprecated-enum` may go once the schema's `x-sunset` date has passed. | The `response` layer, for the responses, replaces these: | Node type | Property | Rule | Note | | --------- | -------- | ---- | ---- | | `schema` | `properties` | `add_item: non_breaking`, `remove_item: {if: sunset_passed, then: non_breaking, else: breaking}` | `remove_item`: Existing clients may rely on the removed property, unless it was deprecated and its `x-sunset` date has passed. | | | `required` | `add_item: non_breaking`, `remove_item: {if: sunset_passed, then: non_breaking, else: breaking}` | `remove_item`: The item of a deprecated property goes with the property, once its `x-sunset` date has passed. | | | `enum` | `add_item: breaking`, `add_first_item: non_breaking`, `remove_item: non_breaking`, `remove_last_item: breaking` | `add_item`: Existing clients may not handle new values. | ### Swagger 2.0 The recommended severities of changes of Swagger 2.0 documents. A severity is one of `none` (not reported), `non_functional`, `non_breaking`, `breaking` and `nested` (the highest severity of the nested changes). | Node type | Property | Rule | Note | | --------- | -------- | ---- | ---- | | `defaults` | `extensions` | `non_functional` | | | `swagger` | `swagger` | `breaking` | | | | `info` | `nested` | | | | `host` | `breaking` | Where the API is served. | | | `basePath` | `breaking` | | | | `schemes` | `add_item: non_breaking`, `remove_item: breaking` | | | | `consumes` | `add_item: non_breaking`, `remove_item: breaking` | Media types the API accepts; clients may send the removed ones. | | | `produces` | `add_item: breaking`, `remove_item: non_breaking` | Media types the API returns; clients may not accept the new ones. | | | `paths` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `definitions` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `parameters` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `responses` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `securityDefinitions` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `security` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `modify_item: nested` | `add_item`: Requirements are alternatives: adding one to existing ones is harmless, but requiring authentication where none was required breaks clients. | | | `tags` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `externalDocs` | `add: non_breaking`, `remove: non_breaking`, `modify: nested` | | | `info` | `title` | `breaking` | | | | `description` | `non_functional` | | | | `termsOfService` | `breaking` | | | | `contact` | `nested` | | | | `license` | `add: breaking`, `remove: non_breaking`, `modify: nested` | | | | `version` | `none` | | | `contact` | `name` | `add: non_breaking`, `remove: breaking`, `modify: non_breaking` | | | | `url` | `add: non_breaking`, `remove: breaking`, `modify: non_breaking` | | | | `email` | `add: non_breaking`, `remove: breaking`, `modify: non_breaking` | | | `license` | `name` | `breaking` | | | | `url` | `breaking` | | | `pathItem` | `$ref` | `breaking` | | | | `parameters` | `add_item: {if: required, then: breaking, else: non_breaking}`, `remove_item: breaking`, `modify_item: nested` | | | | `operations` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | `remove_item`: To allow removing deprecated operations, use `remove_item: { if: deprecated, then: non_breaking, else: breaking }`. | | `operation` | `tags` | `non_breaking` | | | | `summary` | `non_functional` | | | | `description` | `non_functional` | | | | `externalDocs` | `non_functional` | | | | `operationId` | `breaking` | | | | `consumes` | `add_item: non_breaking`, `remove_item: breaking` | | | | `produces` | `add_item: breaking`, `remove_item: non_breaking` | | | | `parameters` | `add_item: {if: required, then: breaking, else: non_breaking}`, `remove_item: breaking`, `modify_item: nested` | | | | `responses` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `schemes` | `add_item: non_breaking`, `remove_item: breaking` | | | | `deprecated` | `modify: {if: true, then: breaking, else: non_breaking}` | | | | `security` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | `parameter` | `name` | `breaking` | | | | `in` | `breaking` | | | | `description` | `non_functional` | | | | `required` | `modify: {if: true, then: breaking, else: non_breaking}` | | | | `schema` | `add: breaking`, `remove: breaking`, `modify: nested` | The schema of a body parameter. | | | `type` | `breaking` | | | | `format` | `breaking` | | | | `allowEmptyValue` | `modify: {if: true, then: non_breaking, else: breaking}` | | | | `items` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `collectionFormat` | `breaking` | | | | `default` | `breaking` | | | | `multipleOf` | `breaking` | | | | `maximum` | `breaking` | | | | `exclusiveMaximum` | `breaking` | | | | `minimum` | `breaking` | | | | `exclusiveMinimum` | `breaking` | | | | `maxLength` | `breaking` | | | | `minLength` | `breaking` | | | | `pattern` | `breaking` | | | | `maxItems` | `breaking` | | | | `minItems` | `breaking` | | | | `uniqueItems` | `breaking` | | | | `enum` | `add_item: breaking`, `remove_item: breaking` | | | `response` | `description` | `non_functional` | | | | `schema` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `headers` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `examples` | `non_functional` | | | `header` | `description` | `non_functional` | | | | `type` | `breaking` | | | | `format` | `breaking` | | | | `items` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `collectionFormat` | `breaking` | | | | `default` | `breaking` | | | | `multipleOf` | `breaking` | | | | `maximum` | `breaking` | | | | `exclusiveMaximum` | `breaking` | | | | `minimum` | `breaking` | | | | `exclusiveMinimum` | `breaking` | | | | `maxLength` | `breaking` | | | | `minLength` | `breaking` | | | | `pattern` | `breaking` | | | | `maxItems` | `breaking` | | | | `minItems` | `breaking` | | | | `uniqueItems` | `breaking` | | | | `enum` | `add_item: breaking`, `remove_item: breaking` | | | `items` | `type` | `breaking` | | | | `format` | `breaking` | | | | `items` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `collectionFormat` | `breaking` | | | | `default` | `breaking` | | | | `multipleOf` | `breaking` | | | | `maximum` | `breaking` | | | | `exclusiveMaximum` | `breaking` | | | | `minimum` | `breaking` | | | | `exclusiveMinimum` | `breaking` | | | | `maxLength` | `breaking` | | | | `minLength` | `breaking` | | | | `pattern` | `breaking` | | | | `maxItems` | `breaking` | | | | `minItems` | `breaking` | | | | `uniqueItems` | `breaking` | | | | `enum` | `add_item: breaking`, `remove_item: breaking` | | | `schema` | `title` | `non_breaking` | | | | `description` | `non_functional` | | | | `type` | `breaking` | | | | `format` | `breaking` | | | | `default` | `breaking` | | | | `multipleOf` | `breaking` | | | | `maximum` | `breaking` | | | | `exclusiveMaximum` | `breaking` | | | | `minimum` | `breaking` | | | | `exclusiveMinimum` | `breaking` | | | | `maxLength` | `breaking` | | | | `minLength` | `breaking` | | | | `pattern` | `breaking` | | | | `maxItems` | `breaking` | | | | `minItems` | `breaking` | | | | `uniqueItems` | `breaking` | | | | `enum` | `add_item: breaking`, `remove_item: breaking` | | | | `items` | `add: breaking`, `remove: non_breaking`, `modify: nested` | | | | `allOf` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `properties` | `add_item: non_breaking`, `remove_item: non_breaking`, `modify_item: nested` | | | | `required` | `breaking` | | | | `maxProperties` | `breaking` | | | | `minProperties` | `breaking` | | | | `additionalProperties` | `add: breaking`, `remove: breaking`, `modify: nested` | `add` when additional properties become allowed, `remove` when they become forbidden, `modify` for changes of the schema of additional properties. | | | `discriminator` | `breaking` | | | | `readOnly` | `non_functional` | | | | `xml` | `nested` | | | | `externalDocs` | `non_functional` | | | | `example` | `non_functional` | | | `xml` | `name` | `breaking` | | | | `namespace` | `breaking` | | | | `prefix` | `breaking` | | | | `attribute` | `breaking` | | | | `wrapped` | `breaking` | | | `securityScheme` | `type` | `breaking` | | | | `description` | `non_functional` | | | | `name` | `breaking` | | | | `in` | `breaking` | | | | `flow` | `breaking` | | | | `authorizationUrl` | `breaking` | | | | `tokenUrl` | `breaking` | | | | `scopes` | `add_item: breaking`, `remove_item: breaking`, `modify_item: non_functional` | | | `securityRequirement` | `scopes` | `add_item: breaking`, `remove_item: non_breaking` | Clients may not have tokens with the new scopes. | | `tag` | `name` | `breaking` | | | | `description` | `non_functional` | | | | `externalDocs` | `non_functional` | | | `externalDocumentation` | `description` | `non_functional` | | | | `url` | `non_functional` | | Severities that depend on the direction of data flow. They override `rules` in requests (parameters, including body parameters; sent by API clients) and responses (sent by the API). Changes in places shared by both (e.g. definitions) get the stricter of the request and the response severity. These defaults assume that servers and clients ignore unknown properties. For clients that reject them, set `response.schema.properties.add_item` to `breaking`. The `request` layer, for the parameters, replaces these rules of the layer above: | Node type | Property | Rule | Note | | --------- | -------- | ---- | ---- | | `schema` | `properties` | `add_item: {if: required, then: breaking, else: non_breaking}`, `remove_item: non_breaking` | `add_item`: Existing clients don't send new required properties. | | | `required` | `add_item: breaking`, `remove_item: non_breaking` | | | | `enum` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `remove_last_item: non_breaking` | `add_first_item`: Restricting a value to a set of values. | | | `additionalProperties` | `add: non_breaking`, `remove: breaking` | | | `parameter` | `enum` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `remove_last_item: non_breaking` | | | `items` | `enum` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `remove_last_item: non_breaking` | | The `response` layer, for the responses, replaces these: | Node type | Property | Rule | Note | | --------- | -------- | ---- | ---- | | `schema` | `properties` | `add_item: non_breaking`, `remove_item: breaking` | `remove_item`: Existing clients may rely on the removed property. | | | `required` | `add_item: non_breaking`, `remove_item: breaking` | | | | `enum` | `add_item: breaking`, `add_first_item: non_breaking`, `remove_item: non_breaking`, `remove_last_item: breaking` | `add_item`: Existing clients may not handle new values. | | | `additionalProperties` | `add: non_breaking`, `remove: non_breaking` | | | `header` | `enum` | `add_item: breaking`, `add_first_item: non_breaking`, `remove_item: non_breaking`, `remove_last_item: breaking` | | | `items` | `enum` | `add_item: breaking`, `add_first_item: non_breaking`, `remove_item: non_breaking`, `remove_last_item: breaking` | | ### AsyncAPI | Node type | Property | Rule | Note | | --------- | -------- | ---- | ---- | | `defaults` | `extensions` | `non_functional` | | | `asyncapi` | `asyncapi` | `non_breaking` | The specification version; minor versions of AsyncAPI 3 are compatible. | | | `id` | `breaking` | | | | `info` | `nested` | | | | `servers` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `defaultContentType` | `breaking` | | | | `channels` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `operations` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `components` | `nested` | | | `info` | `title` | `non_functional` | | | | `version` | `none` | | | | `description` | `non_functional` | | | | `termsOfService` | `non_breaking` | | | | `contact` | `nested` | | | | `license` | `add: breaking`, `remove: non_breaking`, `modify: nested` | | | | `tags` | `non_functional` | | | | `externalDocs` | `non_functional` | | | `contact` | `name` | `non_functional` | | | | `url` | `non_functional` | | | | `email` | `non_functional` | | | `license` | `name` | `breaking` | | | | `url` | `breaking` | | | `server` | `host` | `breaking` | | | | `protocol` | `breaking` | | | | `protocolVersion` | `breaking` | | | | `pathname` | `breaking` | | | | `description` | `non_functional` | | | | `title` | `non_functional` | | | | `summary` | `non_functional` | | | | `variables` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `security` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `modify_item: nested` | `add_item`: Security schemes are alternatives: adding one to existing ones is harmless, but requiring authentication where none was required breaks clients. | | | `tags` | `non_functional` | | | | `externalDocs` | `non_functional` | | | | `bindings` | `nested` | | | `serverVariable` | `enum` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `remove_last_item: non_breaking` | | | | `default` | `breaking` | | | | `description` | `non_functional` | | | | `examples` | `non_functional` | | | `channel` | `address` | `breaking` | | | | `messages` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `title` | `non_functional` | | | | `summary` | `non_functional` | | | | `description` | `non_functional` | | | | `servers` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `remove_last_item: non_breaking` | `add_item`: A channel without servers is available on all servers. | | | `parameters` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `tags` | `non_functional` | | | | `externalDocs` | `non_functional` | | | | `bindings` | `nested` | | | `parameter` | `enum` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `remove_last_item: non_breaking` | | | | `default` | `breaking` | | | | `description` | `non_functional` | | | | `examples` | `non_functional` | | | | `location` | `breaking` | | | `operation` | `action` | `breaking` | | | | `channel` | `breaking` | | | | `title` | `non_functional` | | | | `summary` | `non_functional` | | | | `description` | `non_functional` | | | | `security` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `tags` | `non_functional` | | | | `externalDocs` | `non_functional` | | | | `bindings` | `nested` | | | | `traits` | `nested` | Traits are applied to the operation, so their changes are the operation's changes. | | | `messages` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `remove_last_item: non_breaking` | `add_item`: An operation without messages uses all messages of its channel. | | | `reply` | `add: breaking`, `remove: breaking`, `modify: nested` | | | `operationTrait` | `title` | `non_functional` | | | | `summary` | `non_functional` | | | | `description` | `non_functional` | | | | `security` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `tags` | `non_functional` | | | | `externalDocs` | `non_functional` | | | | `bindings` | `nested` | | | `operationReply` | `address` | `nested` | | | | `channel` | `breaking` | | | | `messages` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `remove_last_item: non_breaking` | | | `operationReplyAddress` | `description` | `non_functional` | | | | `location` | `breaking` | | | `message` | `headers` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `payload` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `correlationId` | `add: non_breaking`, `remove: breaking`, `modify: nested` | | | | `contentType` | `breaking` | | | | `name` | `non_breaking` | | | | `title` | `non_functional` | | | | `summary` | `non_functional` | | | | `description` | `non_functional` | | | | `tags` | `non_functional` | | | | `externalDocs` | `non_functional` | | | | `bindings` | `nested` | | | | `examples` | `non_functional` | | | | `traits` | `nested` | Traits are applied to the message, so their changes are the message's changes. | | `messageTrait` | `headers` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `correlationId` | `add: non_breaking`, `remove: breaking`, `modify: nested` | | | | `contentType` | `breaking` | | | | `name` | `non_breaking` | | | | `title` | `non_functional` | | | | `summary` | `non_functional` | | | | `description` | `non_functional` | | | | `tags` | `non_functional` | | | | `externalDocs` | `non_functional` | | | | `bindings` | `nested` | | | | `examples` | `non_functional` | | | `messageExample` | `headers` | `non_functional` | | | | `payload` | `non_functional` | | | | `name` | `non_functional` | | | | `summary` | `non_functional` | | | `correlationId` | `description` | `non_functional` | | | | `location` | `breaking` | | | `tag` | `name` | `non_functional` | | | | `description` | `non_functional` | | | | `externalDocs` | `non_functional` | | | `externalDocumentation` | `description` | `non_functional` | | | | `url` | `non_functional` | | | `components` | `schemas` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `servers` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `channels` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `operations` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `messages` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `securitySchemes` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `serverVariables` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `parameters` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `correlationIds` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `replies` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `replyAddresses` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `externalDocs` | `non_functional` | | | | `tags` | `non_functional` | | | | `operationTraits` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `messageTraits` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `serverBindings` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `channelBindings` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `operationBindings` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `messageBindings` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | `schema` | `id` | `breaking` | | | | `dialect` | `breaking` | | | | `comment` | `none` | | | | `title` | `non_functional` | | | | `description` | `non_functional` | | | | `type` | `breaking` | | | | `enum` | `add_item: breaking`, `remove_item: breaking` | | | | `const` | `breaking` | | | | `default` | `breaking` | | | | `examples` | `non_functional` | | | | `readOnly` | `non_functional` | | | | `writeOnly` | `non_functional` | | | | `deprecated` | `non_breaking` | | | | `format` | `breaking` | | | | `contentEncoding` | `breaking` | | | | `contentMediaType` | `breaking` | | | | `multipleOf` | `breaking` | | | | `maximum` | `breaking` | | | | `exclusiveMaximum` | `breaking` | | | | `minimum` | `breaking` | | | | `exclusiveMinimum` | `breaking` | | | | `maxLength` | `breaking` | | | | `minLength` | `breaking` | | | | `pattern` | `breaking` | | | | `items` | `add: breaking`, `remove: non_breaking`, `modify: nested` | | | | `tupleItems` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `additionalItems` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `maxItems` | `breaking` | | | | `minItems` | `breaking` | | | | `uniqueItems` | `breaking` | | | | `contains` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `maxProperties` | `breaking` | | | | `minProperties` | `breaking` | | | | `required` | `breaking` | | | | `properties` | `add_item: non_breaking`, `remove_item: non_breaking`, `modify_item: nested` | | | | `patternProperties` | `add_item: non_breaking`, `remove_item: non_breaking`, `modify_item: nested` | | | | `additionalProperties` | `breaking` | | | | `dependencies` | `breaking` | | | | `propertyNames` | `non_breaking` | | | | `if` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `then` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `else` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `allOf` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `anyOf` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `oneOf` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `not` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `discriminator` | `breaking` | | | | `externalDocs` | `non_functional` | | | `multiFormatSchema` | `schemaFormat` | `breaking` | | | | `schema` | `nested` | | | | `untypedSchema` | `breaking` | Schemas in formats without a typed model, e.g. Avro, are compared as whole values. | | `reference` | `ref` | `breaking` | A reference the document can't follow (to another file or a URL) is compared by its $ref: another one may lead to anything. | | `securityScheme` | `type` | `breaking` | | | | `description` | `non_functional` | | | | `name` | `breaking` | | | | `in` | `breaking` | | | | `scheme` | `breaking` | | | | `bearerFormat` | `breaking` | | | | `flows` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `openIdConnectUrl` | `breaking` | | | | `scopes` | `add_item: breaking`, `remove_item: non_breaking` | `add_item`: The scopes a server or an operation requires. | | `oauthFlows` | `implicit` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `password` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `clientCredentials` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `authorizationCode` | `add: breaking`, `remove: breaking`, `modify: nested` | | | `oauthFlow` | `authorizationUrl` | `breaking` | | | | `tokenUrl` | `breaking` | | | | `refreshUrl` | `breaking` | | | | `availableScopes` | `add_item: breaking`, `remove_item: breaking`, `modify_item: non_functional` | | | `serverBindings` | `protocols` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `untyped` | `breaking` | Bindings of protocols without a typed model are compared as a whole. | | `channelBindings` | `protocols` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `untyped` | `breaking` | | | `operationBindings` | `protocols` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `untyped` | `breaking` | | | `messageBindings` | `protocols` | `add_item: breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `untyped` | `breaking` | | | `httpOperationBinding` | `bindingVersion` | `non_breaking` | | | | `method` | `breaking` | | | | `query` | `add: breaking`, `remove: breaking`, `modify: nested` | | | `httpMessageBinding` | `bindingVersion` | `non_breaking` | | | | `headers` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `statusCode` | `breaking` | | | `webSocketsChannelBinding` | `bindingVersion` | `non_breaking` | | | | `method` | `breaking` | | | | `query` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `headers` | `add: breaking`, `remove: breaking`, `modify: nested` | | | `kafkaServerBinding` | `bindingVersion` | `non_breaking` | | | | `schemaRegistryUrl` | `breaking` | | | | `schemaRegistryVendor` | `breaking` | | | `kafkaChannelBinding` | `bindingVersion` | `non_breaking` | | | | `topic` | `breaking` | | | | `partitions` | `breaking` | | | | `replicas` | `breaking` | | | | `topicConfiguration` | `add: breaking`, `remove: breaking`, `modify: nested` | | | `kafkaTopicConfiguration` | `cleanupPolicy` | `breaking` | | | | `retentionMs` | `breaking` | | | | `retentionBytes` | `breaking` | | | | `deleteRetentionMs` | `breaking` | | | | `maxMessageBytes` | `breaking` | | | | `confluentKeySchemaValidation` | `breaking` | | | | `confluentKeySubjectNameStrategy` | `breaking` | | | | `confluentValueSchemaValidation` | `breaking` | | | | `confluentValueSubjectNameStrategy` | `breaking` | | | `kafkaOperationBinding` | `bindingVersion` | `non_breaking` | | | | `groupId` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `clientId` | `add: breaking`, `remove: breaking`, `modify: nested` | | | `kafkaMessageBinding` | `bindingVersion` | `non_breaking` | | | | `key` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `schemaIdLocation` | `breaking` | | | | `schemaIdPayloadEncoding` | `breaking` | | | | `schemaLookupStrategy` | `breaking` | | | `amqpChannelBinding` | `bindingVersion` | `non_breaking` | | | | `is` | `breaking` | | | | `exchange` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `queue` | `add: breaking`, `remove: breaking`, `modify: nested` | | | `amqpExchange` | `name` | `breaking` | | | | `type` | `breaking` | | | | `durable` | `breaking` | | | | `autoDelete` | `breaking` | | | | `vhost` | `breaking` | | | `amqpQueue` | `name` | `breaking` | | | | `durable` | `breaking` | | | | `exclusive` | `breaking` | | | | `autoDelete` | `breaking` | | | | `vhost` | `breaking` | | | `amqpOperationBinding` | `bindingVersion` | `non_breaking` | | | | `expiration` | `breaking` | | | | `userId` | `breaking` | | | | `cc` | `breaking` | | | | `priority` | `breaking` | | | | `deliveryMode` | `breaking` | | | | `mandatory` | `breaking` | | | | `bcc` | `breaking` | | | | `timestamp` | `breaking` | | | | `ack` | `breaking` | | | `amqpMessageBinding` | `bindingVersion` | `non_breaking` | | | | `contentEncoding` | `breaking` | | | | `messageType` | `breaking` | | | `mqttServerBinding` | `bindingVersion` | `non_breaking` | | | | `clientId` | `breaking` | | | | `cleanSession` | `breaking` | | | | `lastWill` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `keepAlive` | `breaking` | | | | `sessionExpiryInterval` | `breaking` | | | | `maximumPacketSize` | `breaking` | | | `mqttLastWill` | `topic` | `breaking` | | | | `qos` | `breaking` | | | | `message` | `breaking` | | | | `retain` | `breaking` | | | `mqttOperationBinding` | `bindingVersion` | `non_breaking` | | | | `qos` | `breaking` | | | | `retain` | `breaking` | | | | `messageExpiryInterval` | `breaking` | | | `mqttMessageBinding` | `bindingVersion` | `non_breaking` | | | | `payloadFormatIndicator` | `breaking` | | | | `correlationData` | `add: breaking`, `remove: breaking`, `modify: nested` | | | | `contentType` | `breaking` | | | | `responseTopic` | `breaking` | | Severities that depend on the direction in which messages flow, from the point of view of the application the document describes. They override `rules` for messages the application receives (used by `receive` operations; sent by other parties) and for messages it sends (used by `send` operations; received by other parties). Replies flow the other way than the messages of their operation. Messages used in both directions, or by no operation (e.g. component messages), get the stricter of the receive and the send severity. These defaults assume that applications ignore unknown message properties. For receivers that reject them, set `send.schema.properties.add_item` to `breaking`. The `receive` layer, for the messages of `receive` operations, replaces these rules of the layer above: | Node type | Property | Rule | Note | | --------- | -------- | ---- | ---- | | `message` | `correlationId` | `add: breaking` | `add`: Senders don't provide the new correlation ID yet. | | `schema` | `properties` | `add_item: {if: required, then: breaking, else: non_breaking}`, `remove_item: non_breaking` | `add_item`: Existing senders don't send new required properties. | | | `required` | `add_item: breaking`, `remove_item: non_breaking` | | | | `enum` | `add_item: non_breaking`, `add_first_item: breaking`, `remove_item: breaking`, `remove_last_item: non_breaking` | `add_first_item`: Restricting a value to a set of values. | The `send` layer, for the messages of `send` operations, replaces these: | Node type | Property | Rule | Note | | --------- | -------- | ---- | ---- | | `message` | `correlationId` | `add: non_breaking` | | | `schema` | `properties` | `add_item: non_breaking`, `remove_item: breaking` | `remove_item`: Existing receivers may rely on the removed property. | | | `required` | `add_item: non_breaking`, `remove_item: breaking` | | | | `enum` | `add_item: breaking`, `add_first_item: non_breaking`, `remove_item: non_breaking`, `remove_last_item: breaking` | `add_item`: Existing receivers may not handle new values. | ### Protobuf Severities of changes between two versions of a Protobuf (proto3) file. A change is breaking when it breaks the programs that use the file: those exchanging encoded messages (the binary or the JSON encoding) and those compiled with the code generated from it. | Node type | Property | Rule | Note | | --------- | -------- | ---- | ---- | | `defaults` | `options` | `non_breaking` | An option may change the behaviour of the generated code or of the tools that read it; options known to break their users are listed per node type below. | | `file` | `package` | `breaking` | The package is a part of the names of all types and of the paths of gRPC methods. | | | `imports` | `add_item: non_functional`, `remove_item: non_functional`, `modify_item: nested` | | | | `messages` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `enums` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `services` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `extends` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | Extend blocks, by the extended type. | | | `comment` | `non_functional` | The comment of the syntax statement. | | | `options.cc_enable_arenas` | `breaking` | These decide the names and the layout of the generated code. | | | `options.cc_generic_services` | `breaking` | | | | `options.csharp_namespace` | `breaking` | | | | `options.go_package` | `breaking` | | | | `options.java_generic_services` | `breaking` | | | | `options.java_multiple_files` | `breaking` | | | | `options.java_outer_classname` | `breaking` | | | | `options.java_package` | `breaking` | | | | `options.java_string_check_utf8` | `breaking` | | | | `options.objc_class_prefix` | `breaking` | | | | `options.optimize_for` | `breaking` | | | | `options.php_class_prefix` | `breaking` | | | | `options.php_generic_services` | `breaking` | | | | `options.php_metadata_namespace` | `breaking` | | | | `options.php_namespace` | `breaking` | | | | `options.py_generic_services` | `breaking` | | | | `options.ruby_package` | `breaking` | | | | `options.swift_prefix` | `breaking` | | | `import` | `kind` | `breaking` | Files that import this one see the types of its public imports. | | `message` | `fields` | `add_item: non_breaking`, `remove_item: {if: reserved, then: non_breaking, else: breaking}`, `modify_item: nested` | `remove_item`: A removed field breaks the code that uses it, unless its number is reserved: then the removal is deliberate, and the number can't be taken by another field, which would misread the data of the old one. | | | `oneofs` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `messages` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `enums` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `extends` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `reservedNumbers` | `add_item: non_breaking`, `remove_item: breaking` | A number or a name that is no longer reserved can be taken by a new field. | | | `reservedNames` | `add_item: non_breaking`, `remove_item: breaking` | | | | `comment` | `non_functional` | | | | `options.message_set_wire_format` | `breaking` | | | | `options.no_standard_descriptor_accessor` | `breaking` | | | `field` | `name` | `breaking` | The name is used by the JSON encoding and by the generated code. | | | `type` | `breaking` | Some types are encoded the same way, e.g. int32 and int64; to accept such changes, use `type: { modify: { if: wire_compatible, then: non_breaking, else: breaking } }`. | | | `label` | `breaking` | `optional` and `repeated`. | | | `oneof` | `breaking` | Moving a field into or out of a oneof. | | | `comment` | `non_functional` | | | | `options.ctype` | `breaking` | | | | `options.jstype` | `breaking` | | | | `options.json_name` | `breaking` | | | `oneof` | `comment` | `non_functional` | | | `enum` | `values` | `add_item: non_breaking`, `remove_item: {if: reserved, then: non_breaking, else: breaking}`, `modify_item: nested` | | | | `reservedNumbers` | `add_item: non_breaking`, `remove_item: breaking` | | | | `reservedNames` | `add_item: non_breaking`, `remove_item: breaking` | | | | `comment` | `non_functional` | | | `enumValue` | `name` | `breaking` | The name is used by the JSON encoding and by the generated code. | | | `comment` | `non_functional` | | | `service` | `methods` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `comment` | `non_functional` | | | `method` | `inputType` | `breaking` | | | | `outputType` | `breaking` | | | | `clientStreaming` | `breaking` | | | | `serverStreaming` | `breaking` | | | | `comment` | `non_functional` | | | | `options.idempotency_level` | `breaking` | | | | `options.(google.api.http)` | `breaking` | The HTTP mapping of the method. | | `extend` | `fields` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `comment` | `non_functional` | | ### GraphQL Severities of changes between two versions of a GraphQL schema. A change is breaking when operations that were valid for the old schema become invalid, or when clients can't read their results any more. The rules follow graphql-js's findBreakingChanges(); its "dangerous" changes, e.g. a new enum value or a changed default value, are non-breaking here. | Node type | Property | Rule | Note | | --------- | -------- | ---- | ---- | | `defaults` | `directives` | `non_breaking` | Directives are mostly read by servers and tools; those known to change the meaning of the schema for clients are listed per node kind below. | | `schema` | `query` | `add: non_breaking`, `remove: breaking`, `modify: breaking` | The root operation types. | | | `mutation` | `add: non_breaking`, `remove: breaking`, `modify: breaking` | | | | `subscription` | `add: non_breaking`, `remove: breaking`, `modify: breaking` | | | | `types` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `directiveDefinitions` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `description` | `non_functional` | | | `type` | `kind` | `breaking` | E.g. an object type that becomes an interface. | | `scalar` | `description` | `non_functional` | | | | `directives.specifiedBy` | `non_functional` | | | `object` | `interfaces` | `add_item: non_breaking`, `remove_item: breaking` | Fragments on an interface no longer match the type. | | | `fields` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `description` | `non_functional` | | | `interface` | `interfaces` | `add_item: non_breaking`, `remove_item: breaking` | | | | `fields` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `description` | `non_functional` | | | `union` | `members` | `add_item: non_breaking`, `remove_item: breaking` | | | | `description` | `non_functional` | | | `enum` | `values` | `add_item: non_breaking`, `remove_item: breaking`, `modify_item: nested` | | | | `description` | `non_functional` | | | `enumValue` | `description` | `non_functional` | | | `inputObject` | `fields` | `add_item: {if: required, then: breaking, else: non_breaking}`, `remove_item: breaking`, `modify_item: nested` | `add_item`: Operations that don't give a value for a new required field become invalid. | | | `description` | `non_functional` | | | | `directives.oneOf` | `breaking` | Values of a @oneOf input object have exactly one field. | | `field` | `type` | `modify: {if: compatible, then: non_breaking, else: breaking}` | A field may become non-null, but not nullable; lists must stay lists. | | | `arguments` | `add_item: {if: required, then: breaking, else: non_breaking}`, `remove_item: breaking`, `modify_item: nested` | | | | `description` | `non_functional` | | | `argument` | `type` | `modify: {if: compatible, then: non_breaking, else: breaking}` | An argument may become nullable, but not non-null. | | | `defaultValue` | `add: non_breaking`, `remove: {if: required, then: breaking, else: non_breaking}`, `modify: non_breaking` | Operations that relied on the default value of a non-null argument become invalid. | | | `description` | `non_functional` | | | `inputField` | `type` | `modify: {if: compatible, then: non_breaking, else: breaking}` | | | | `defaultValue` | `add: non_breaking`, `remove: {if: required, then: breaking, else: non_breaking}`, `modify: non_breaking` | | | | `description` | `non_functional` | | | `directive` | `arguments` | `add_item: {if: required, then: breaking, else: non_breaking}`, `remove_item: breaking`, `modify_item: nested` | | | | `repeatable` | `modify: {if: false, then: breaking, else: non_breaking}` | Documents that use the directive more than once at a location become invalid. | | | `locations` | `add_item: non_breaking`, `remove_item: breaking` | | | | `description` | `non_functional` | | ## See also - [diff](/docs/reference/cli/diff): Every option of the command, the node types and keys of each standard, and the JSON report. - [Catch breaking changes in CI](/docs/guides/catch-breaking-changes-in-ci): The check in a pull request, and retiring an operation on a schedule. - [changelog](/docs/reference/cli/changelog): The changes between the revisions of a file in git, with the same rules. --- # apigenie evolve Source: https://apigenie.pl/docs/reference/cli/evolve Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md). Its other pages: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [format](https://apigenie.pl/docs/reference/cli/format.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md), [test](https://apigenie.pl/docs/reference/cli/test.md). Plans safe API changes: `evolve plan` splits the breaking changes between two OpenAPI documents into an expand wave (deprecate, add next to) and a contract wave (remove), writes the wave documents and the plan, and proves the plan with `diff`. > **(experimental, outside the 1.0 compatibility promise)** `evolve plan` is the first version of > the planner: its recipes, the layout of `plan.yaml` and the options can still change, and > `evolve status` and `evolve next` will join it. It says so in its `--help` and on the first line > it prints, on the standard error. See the > [experimental commands](/docs/reference/cli#experimental-commands). ## Usage ```sh apigenie evolve plan [OPTIONS] OLD_FILE NEW_FILE ``` ## Description `diff` says that a change breaks consumers. `evolve plan` says how to ship the same change without breaking anyone, the way database migrations do it: first **expand** (add the new shape next to the old one and deprecate the old one with a sunset date), let consumers move during a **window**, then **contract** (remove what was deprecated). The command takes the document consumers use today (`OLD_FILE`) and the document the change arrives at (`NEW_FILE`, usually the one in the pull request), and writes three files to the directory of `--out` (`evolve-out/` by default): | File | What it is | When to ship it | | ---- | ---------- | --------------- | | `1-expand.yaml` | The target document with every old element kept next to its replacement, `deprecated: true` and `x-sunset: `; non-breaking against `OLD_FILE` | now | | `2-contract.yaml` | The target document | on or after the sunset date | | `plan.yaml` | The plan: the waves, the units, the residue, the server notes | | The wave files take the format of `NEW_FILE` (`1-expand.json` for a JSON document) and keep its comments and layout. The sunset date is `--today` plus `--window` (90 days by default). ### Recipes Each breaking change of the diff becomes a **unit** with a recipe: | Change | Recipe | Expand wave | Contract wave | | ------ | ------ | ----------- | ------------- | | An operation or a whole path is removed | `remove-operation` | the operation stays, deprecated with its sunset date | removed | | An operation moved to another path (a hint says where, see below) | `move-path` | the old operation stays, deprecated | removed | | A response property is removed | `remove-response-property` | the property stays, deprecated (and required when it was) | removed | | A response property is renamed | `rename-response-property` | the old property stays, deprecated, next to the new one | removed | | A request property is renamed | `rename-request-property` | the old property stays, deprecated; neither name is required | the old one removed, the new one required when it was in `NEW_FILE` | | A request parameter is renamed | `rename-request-parameter` | the old parameter stays, deprecated and optional; the new one is optional | the old one removed, the new one required when it was | | A request parameter is removed | `remove-request-parameter` | the parameter stays, deprecated | removed | | A request property becomes required (new or existing) | `require-request-property` | present but optional | required | | A request parameter becomes required | `require-request-parameter` | optional | required | | A request enum value is removed | `remove-request-enum-value` | the value stays, listed in `x-deprecated-enum`, with `x-sunset` on the schema | removed | A rename is detected when an object loses one property (or an operation one parameter) and gains one whose schema is the same, after following `$ref`s and ignoring descriptions, titles, examples and extensions. Removed and added members that were not paired are listed as **rename candidates**; a hint decides them. A component schema is reported where it is used and under `components`; one unit covers all of them, and a schema used in requests and responses gets the request recipe, the stricter one. Changes the differ rates non-breaking need no recipe: they are in both waves as they are in `NEW_FILE`. Breaking changes no recipe makes safe are **residue**: a changed type or format, a response property no longer required, a new security requirement, a replaced server, a changed status code or media type. The plan lists them with a reason, the expand wave keeps the old shape there, the contract wave applies the change, and the command exits with status 1: these need a major version or a new resource. ### Server notes A document can say that both `fullName` and `name` exist; only the implementation can emit both or accept both. Each unit that needs it carries a **server note** (`server` in `plan.yaml`, the "Server checklist" of the report): emit both names until the sunset, accept both, apply a default when a soon-required property is missing, accept a deprecated enum value until the sunset. A plan whose server does not follow its notes is a lie the documents can't catch. ### Hints `--hints FILE` names what the diff can't see, as YAML or JSON: ```yaml renames: - from: "#/components/schemas/Customer/properties/fullName" to: "#/components/schemas/Customer/properties/name" - from: "GET /v1/parcels/{id}" to: "GET /v1/shipments/{id}" window: 90d reason: Unify naming with the shipments API ``` `renames` pairs a removed element with an added one: operations as `METHOD /path`, properties and parameters by their location, written the way the `overrides.where.location` of the [diff configuration](/docs/reference/cli/diff#configuration) is (`/components/schemas/Customer/properties/fullName`, `/paths/~1pets/get/parameters/query:page`; a leading `#` is accepted). A hint that names no removed and added element of the diff is an error. `window` applies when `--window` is not given, and `reason` is written into every unit. ### Verification Before anything is written, the plan is checked with the differ and the same configuration: 1. `diff OLD_FILE 1-expand.yaml` has no breaking change. 2. `diff 1-expand.yaml 2-contract.yaml --today ` has breaking changes only where a unit's contract step owns them (a `required` list it changes) or where the residue is; the scheduled removals are non-breaking thanks to the [`sunset_passed` condition](/docs/reference/cli/diff#configuration). 3. `2-contract.yaml` equals `NEW_FILE`, ignoring `x-sunset`, `x-deprecated-enum` and `x-apigenie-*` extensions. When a check fails, the report names the change and the unit, nothing is written, and the command exits with status 2. The same differ suggests the versions of the waves: a minor for the expand wave (a patch when it only adds extensions), a minor for a contract wave that only removes scheduled elements, a major for one that requires something or carries residue. ### plan.yaml ```yaml apigenie-evolve: 1 from: {path: api.v1.yaml, version: 1.4.0} to: {path: api.v2.yaml, version: 1.4.0} today: 2026-10-13 window: 90d waves: - id: expand file: 1-expand.yaml version: 1.5.0 units: [remove-operation-quoteLegacy, rename-response-property-Parcel-fullName] - id: contract file: 2-contract.yaml version: 1.6.0 notBefore: 2027-01-11 units: [remove-operation-quoteLegacy, rename-response-property-Parcel-fullName] units: remove-operation-quoteLegacy: recipe: remove-operation from: GET /quotes/legacy sunset: 2027-01-11 rename-response-property-Parcel-fullName: recipe: rename-response-property from: /components/schemas/Parcel/properties/fullName to: /components/schemas/Parcel/properties/name detected: true sunset: 2027-01-11 server: emit both fullName and name until 2027-01-11 residue: [] ``` A unit's `from` is `METHOD /path` for an operation and the element's location otherwise; `to` names the new element of a rename or a move, `value` the removed enum value, `detected` whether the planner found a rename itself (`true`) or a hint supplied it (`false`), `reason` comes from the hints, `sites` lists the places a component schema was reported at. Each residue item has its `location`, the `change` as `diff` describes it, and `why`. ## Options | Option | Description | | ------ | ----------- | | `--hints FILE` | The hints file: renames, the window, the reason. | | `--window WINDOW` | How long consumers have before the contract wave: days (`90d`) or weeks (`12w`). Defaults to the hints file's window, then to `90d`. | | `--today DATE` | The date the plan is made at (`YYYY-MM-DD`); the sunset dates are this plus the window. Defaults to the current date. | | `--config FILE`, `--no-config` | The configuration file whose `commands.diff` block rates the changes, as for [`diff`](/docs/reference/cli/diff#configuration). | | `--out DIR` | Where the plan and the wave documents go. Defaults to `evolve-out`. | | `--format FORMAT` | The report: `text` (default) or `json`. | ## JSON output With `--format json` the report is an object whose `formatVersion` member is the version of the format, changed only when a member is removed or changes meaning (see [Compatibility](/docs/reference/cli/compatibility)); its JSON Schema is [`apigenie-evolve-report.json`](https://apigenie.pl/schemas/apigenie-evolve-report.json). ```json5 { "formatVersion": 1, "result": "planned", // or "residue", or "failed" "plan": { "apigenie-evolve": 1, "...": "the same object as plan.yaml" }, "checks": [ { "id": "expand-non-breaking", "status": "ok" }, { "id": "contract-scheduled-only", "status": "ok" }, { "id": "contract-equals-target", "status": "ok" } ], "serverNotes": [{ "unit": "rename-response-property-Parcel-fullName", "note": "emit both fullName and name until 2027-01-11" }], "files": ["evolve-out/plan.yaml", "evolve-out/1-expand.yaml", "evolve-out/2-contract.yaml"] } ``` ## Exit status | Status | Meaning | | ------ | ------- | | 0 | Every breaking change was placed in a wave; the files were written | | 1 | The files were written, but some changes are residue (listed in the report) | | 2 | Invalid options, a file that can't be read or isn't an OpenAPI 3.x document, a hint that names nothing, an invalid configuration, or a failed check (nothing written) | ## Examples Plan the change of a pull request, then let `diff` confirm the waves: ```sh apigenie evolve plan api.main.yaml api.pr.yaml --out evolve-out apigenie diff api.main.yaml evolve-out/1-expand.yaml apigenie diff evolve-out/1-expand.yaml evolve-out/2-contract.yaml --today 2027-01-11 ``` With hints for a moved endpoint, a two-month window and a JSON report for a pipeline: ```sh apigenie evolve plan api.main.yaml api.pr.yaml --hints evolve.yaml --window 8w --format json ``` Serve the expand wave to old consumers before shipping it: ```sh apigenie-server evolve-out/1-expand.yaml ``` --- # apigenie format Source: https://apigenie.pl/docs/reference/cli/format Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md). Its other pages: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md), [test](https://apigenie.pl/docs/reference/cli/test.md). Formats OpenAPI, Swagger 2.0 and AsyncAPI documents, written in JSON or YAML, Protobuf files and GraphQL documents in place, or checks that they are formatted. What it changes comes from the configuration file: the [layout and the YAML styles](/docs/reference/cli/format/styles) of a document, the [order of the properties](/docs/reference/cli/format/property-order) of every object its specification defines, and what is sorted in [Protobuf](/docs/reference/cli/format/protobuf) and [GraphQL](/docs/reference/cli/format/graphql) files. A document keeps its comments and its meaning. ## Topics - [Layout and YAML styles](/docs/reference/cli/format/styles): The output format, indentation, line endings and folding, and the YAML styles of strings, keys, sequences and mappings, for a whole document or chosen fields, and the layout of JSON arrays and objects. - [Property order](/docs/reference/cli/format/property-order): `original`, `sorted` or a fixed order for each kind of OpenAPI object, and how the objects are recognized in OpenAPI 3.0, 3.1 and 3.2 documents. - [AsyncAPI documents](/docs/reference/cli/format/asyncapi): The `asyncapi` section, and the objects of AsyncAPI 3 with their recommended order. - [Swagger 2.0 documents](/docs/reference/cli/format/swagger): The `swagger` section, and the objects of Swagger 2.0 with their recommended order. - [Protobuf files](/docs/reference/cli/format/protobuf): The layout of `.proto` files, and the imports, options, declarations, fields and values `sort` can reorder. - [GraphQL documents](/docs/reference/cli/format/graphql): The Prettier layout of schemas and operations, where the output differs from Prettier's, and what `sort` can reorder. ## Usage ```sh apigenie format [OPTIONS] FILES... apigenie format --check [OPTIONS] FILES... apigenie format --output OUTPUT [OPTIONS] FILE ``` Without options, the files are formatted with the settings of the project's configuration file, or the defaults, and written back in their own format: ```sh apigenie format api/openapi.yaml api/events.yaml ``` `--check` lists the files that are not formatted instead of writing them, for a CI job, and `--output` writes one file elsewhere, in JSON or YAML: ```sh apigenie format --check api/*.yaml apigenie format api/openapi.yaml --output build/openapi.json ``` ## What the formatter changes The formatter recognizes a file by the root field of its document or by its extension, and reads its settings from the section of the configuration named after it: | File | Recognized by | Section | | ---------------------------- | ----------------------------------------------- | ---------- | | OpenAPI 3.0, 3.1 or 3.2 | the `openapi` field of the root | `openapi` | | Swagger 2.0 | the `swagger` field of the root, a string | `swagger` | | AsyncAPI 3 | the `asyncapi` field of the root | `asyncapi` | | Protobuf (proto3) | the `.proto` extension | `protobuf` | | GraphQL schema or operations | the `.graphql`, `.graphqls` or `.gql` extension | `graphql` | A JSON or YAML file with none of the three fields is reported (`'FILE' is not an OpenAPI, Swagger, AsyncAPI, Protobuf or GraphQL document.`) and left untouched; the other files are still formatted, and the command exits with 2. In an OpenAPI, Swagger or AsyncAPI document, the formatter changes: - the indentation, the line endings, the final line break and the width at which long YAML values are folded - the YAML styles of strings, keys, sequences and mappings, for the whole document or for chosen fields, and the layout of JSON arrays and objects for the whole document - the order of the properties of every object the specification defines, at every depth of the document, and of the names in maps such as components, properties or media types A Protobuf file gets one statement per line, normalized spacing and blank lines between its declarations, and its imports and options sorted; a GraphQL document gets the layout of Prettier. The pages of [Protobuf files](/docs/reference/cli/format/protobuf) and [GraphQL documents](/docs/reference/cli/format/graphql) list what else can be sorted. The formatter never changes what a document means: the output holds the same values as the input, and formatting it again gives the same output. YAML anchors and aliases are the one construct it does not keep: each alias is written as a copy of its anchor's value, in YAML as in JSON. A YAML or JSON document is formatted even when it is not a valid document of its specification, and only a syntax error stops the formatter, unlike `lint` and `diff`, which read valid documents only. A Protobuf or GraphQL file with syntax errors is reported with the position of each error and left untouched. ## Comments The formatter keeps comments: the YAML comments of OpenAPI, Swagger and AsyncAPI documents (at the top and the end of the file, above keys, at the end of lines, inside sequences, between entries and after the last entry), the comments of Protobuf files and the `#` comments of GraphQL documents. A comment directly above a key belongs to that key and moves with it when properties are sorted; a comment at the top of the file that a blank line separates from the first key stays at the top. JSON has no comments, so a YAML document written as ## Options ### --config FILE The configuration file. Without it, the first of `apigenie.yaml`, `apigenie.yml`, `apigenie.json`, `.apigenie.yaml`, `.apigenie.yml` and `.apigenie.json` found in the current directory or its parents, up to the root of the git repository, is read. See [Configuration](#configuration). ```sh apigenie format --config api-style-guide.yaml api/openapi.yaml api/events.json ``` ### --no-config Formats with the default settings, without looking for a configuration file. ### --check Checks that the files are formatted, without writing anything. The path of every file that formatting would change is printed on standard output, one per line, with `N file(s) would be reformatted.` on standard error, and the command exits with 1 when there is at least one. A file whose output format differs from its own (see [format](/docs/reference/cli/format/styles#format)) always counts as a change. Files with syntax errors and unsupported documents are reported as without `--check`. Not with `--output`. ```sh apigenie format --check api/*.yaml ``` ### --strip-comments Drops the comments of the files instead of keeping them: YAML comments of OpenAPI, Swagger and AsyncAPI documents, `//` and `/* */` comments of Protobuf files and `#` comments of GraphQL documents. GraphQL descriptions are part of the schema and are kept. A `# prettier-ignore` comment is dropped too, so the definition after it is formatted. ```sh apigenie format --strip-comments api/openapi.yaml ``` ### --openapi-fragment KIND Formats the files as fragments of OpenAPI documents, such as a schema kept in its own file and referenced with `$ref`. `KIND` is the object at the root of the files: `schema`, `pathItem`, `operation`, `parameter`, `requestBody`, `response`, `header`, `example`, `link`, `securityScheme` or `components`. The objects inside the fragment are recognized as in a whole document. Protobuf and GraphQL files are formatted as usual. ```sh apigenie format --openapi-fragment schema schemas/*.yaml ``` ### --output OUTPUT Writes the result to `OUTPUT` instead of the input file, and takes one input file. For an OpenAPI, Swagger or AsyncAPI document, the extension of `OUTPUT` chooses its format, `.json`, `.yaml` or `.yml`, so the option converts between JSON and YAML; another extension is an error. A Protobuf or GraphQL file is written in its own format, whatever the extension. Not with `--check`. ```sh apigenie format api/openapi.yaml --output build/openapi.json ``` ## Exit status | Status | When | | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 0 | Every file was formatted or, with `--check`, is already formatted. | | 1 | With `--check`, at least one file would change. | | 2 | A file has syntax errors or is not a supported document (the other files are still formatted or checked), the configuration file is invalid, or the options cannot be used together. | See the [exit statuses](/docs/reference/cli#exit-status) shared by the commands. ## Configuration The settings live under `commands.format` of the [configuration file](/docs/reference/cli/configuration): `extends`, and a section per kind of file. Every section is optional, so a configuration can hold the settings of some kinds only. | Section | Keys | Page | | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | `extends` | A list of the presets `recommended` and `original`, applied in order | [Presets](#presets) | | `openapi` | `format`, `indent`, `force_array_indent`, `line_width`, `newline`, `final_newline`, `document_marker`, `style`, `style_overrides`, `property_order` | [Layout and YAML styles](/docs/reference/cli/format/styles), [Property order](/docs/reference/cli/format/property-order) | | `asyncapi` | `format`, `indent`, `force_array_indent`, `style`, `property_order` | [AsyncAPI documents](/docs/reference/cli/format/asyncapi) | | `swagger` | `format`, `indent`, `force_array_indent`, `style`, `property_order` | [Swagger 2.0 documents](/docs/reference/cli/format/swagger) | | `protobuf` | `indent`, `sort` | [Protobuf files](/docs/reference/cli/format/protobuf) | | `graphql` | `indent`, `line_width`, `sort` | [GraphQL documents](/docs/reference/cli/format/graphql) | **Example** - Recommended settings, with CRLF line endings and the descriptions of OpenAPI documents written as literal blocks ```yaml commands: format: extends: - recommended openapi: newline: crlf style_overrides: - fields: [description] string: literal ``` ### Presets A configuration starts from the defaults: the presets named by `extends` are applied first, in order, to every kind of file, then the keys of the sections replace what the presets set. - `recommended` indents OpenAPI, Swagger and AsyncAPI documents by 2 spaces, writes their values in the `best-fit` styles and puts the properties of their objects in the fixed orders listed on the pages of the [OpenAPI](/docs/reference/cli/format/property-order#objects), [AsyncAPI](/docs/reference/cli/format/asyncapi#objects) and [Swagger 2.0](/docs/reference/cli/format/swagger#objects) objects, with path templates and response codes sorted. In Protobuf files it sorts imports and options; in GraphQL documents it sorts nothing. - `original` indents by 2 spaces and keeps the styles and the property order of the input. In Protobuf files and GraphQL documents it sorts nothing. Without a configuration file, an OpenAPI, Swagger or AsyncAPI document is formatted as with `original`: it keeps its format, its styles and its property order, indented by 2 spaces. A Protobuf or GraphQL file is formatted with the `recommended` settings. Unknown keys, unknown object names and values outside their range are errors, reported as `FILE:LINE:COLUMN: POINTER: MESSAGE`, for example `apigenie.yaml:5:15: /commands/format/openapi/indent: number is greater than maximum`; nothing is formatted then, and the command exits with 2. ## See also - [Configuration](/docs/reference/cli/configuration): The configuration file, and where it is looked for. - [lint](/docs/reference/cli/lint): Checks the content of the documents the formatter lays out. - [GitHub Action](/docs/ci/github-action): Runs `apigenie format --check` in a workflow. --- # Layout and YAML styles Source: https://apigenie.pl/docs/reference/cli/format/styles Part of the reference of [format](https://apigenie.pl/docs/reference/cli/format.md). Its other pages: [Property order](https://apigenie.pl/docs/reference/cli/format/property-order.md), [AsyncAPI documents](https://apigenie.pl/docs/reference/cli/format/asyncapi.md), [Swagger 2.0 documents](https://apigenie.pl/docs/reference/cli/format/swagger.md), [Protobuf files](https://apigenie.pl/docs/reference/cli/format/protobuf.md), [GraphQL documents](https://apigenie.pl/docs/reference/cli/format/graphql.md). The `openapi` section of `commands.format` sets how an OpenAPI document is written: its format, its indentation, its line endings, where long values are folded, the YAML styles of its strings, keys, sequences and mappings, and the layout of JSON arrays and objects. The `asyncapi` and `swagger` sections take `format`, `indent`, `force_array_indent` and `style` with the same values; the [layout](#layout) keys and `style_overrides` are for OpenAPI documents. ## format The output format: `yaml`, `json` or `original`. Without it, or with `original`, every file keeps its own format. With another format, formatting `api.json` in place writes `api.yaml` next to it. ## indent The number of spaces of one level of indentation, from 2 to 9. The default is 2. ## force_array_indent Indents the elements of YAML block sequences under their key (`true`), instead of writing them at the level of the key (`false`, the default). ## Layout The lines of the output: | Key | Values | Default | Effect | | ----------------- | -------------- | ---------- | -------------------------------------------------------------------------------------------- | | `line_width` | 0 to 100000 | 0 | Folds long YAML scalars at this width. 0 never folds them. | | `newline` | `lf`, `crlf` | `lf` | The line endings of the output, YAML and JSON. | | `final_newline` | `true`, `false`| the writer's | Whether the output ends with a line break. Without it, YAML and indented JSON end with one. | | `document_marker` | `true`, `false`| `false` | Starts YAML documents with `---`. | ## style The styles of the values: `string` (`original`, `best-fit`, `plain`, `single-quoted`, `double-quoted`, `literal`, `folded`), `array` and `object` (`original`, `best-fit`, `block`, `flow`) and `key` (`original`, `best-fit`, `plain`, `single-quoted`, `double-quoted`). The default is `original` for all of them, which keeps the styles of a YAML input in YAML output. Since 0.12.0, the `flow`, `block` and `best-fit` array and object styles also lay out JSON output. `flow` writes an array or object on one line, with everything inside it. `block` and `best-fit` write one element or member per line. With `object: flow`, the whole document is on one line, because its root is an object. With `original`, JSON output has one element or member per line, even for the flow collections of a YAML input. JSON keeps no styles, so a collection kept on one line would be spread over lines the next time the JSON is formatted. `style_overrides` apply to YAML output only. With the `best-fit` string and key styles, strings that YAML 1.1 parsers (such as PyYAML, SnakeYAML or go-yaml v2) would read as booleans, numbers or merge keys are written in double quotes: `yes`, `No`, `on`, `OFF`, `y`, `n`, `0755`, `0b101`, `1_000`, `1:30`, `<<` and the like. The `original` style keeps the quoting of the source. ## style_overrides A list of rules giving the values of some fields their own YAML styles. A rule selects values by `fields` (the names of their fields), by `objects` (the [kinds](/docs/reference/cli/format/property-order#objects) of the objects holding them), or by both, and sets one or more of `string`, `array` and `object`, with the values of [style](#style). A rule without `objects` applies to the fields of OpenAPI objects only, never to those inside example values or extensions. When several rules match a value, the later ones win. **Example** - Literal descriptions, and flow sequences for the tags of operations and the required properties of schemas ```yaml commands: format: openapi: style_overrides: - fields: [description] string: literal - fields: [tags] objects: [operation] array: flow - fields: [required] objects: [schema] array: flow ``` --- # Property order Source: https://apigenie.pl/docs/reference/cli/format/property-order Part of the reference of [format](https://apigenie.pl/docs/reference/cli/format.md). Its other pages: [Layout and YAML styles](https://apigenie.pl/docs/reference/cli/format/styles.md), [AsyncAPI documents](https://apigenie.pl/docs/reference/cli/format/asyncapi.md), [Swagger 2.0 documents](https://apigenie.pl/docs/reference/cli/format/swagger.md), [Protobuf files](https://apigenie.pl/docs/reference/cli/format/protobuf.md), [GraphQL documents](https://apigenie.pl/docs/reference/cli/format/graphql.md). The `property_order` key of the `openapi` section of `commands.format` sets the order of the properties of every kind of OpenAPI object, and of the names in maps such as components, properties and media types. The `asyncapi` and `swagger` sections have a `property_order` of their own, with the objects of [AsyncAPI 3](/docs/reference/cli/format/asyncapi#objects) and [Swagger 2.0](/docs/reference/cli/format/swagger#objects). ## Orders Each key of `property_order` takes one of three orders: - `original` keeps the order of the input file. It is the default, and the order to keep for a document that is edited by hand, because it adds nothing to a diff. - `sorted` sorts the properties by name. It suits maps whose keys are names: path templates, component names, the status codes of responses. - An array of property names puts the listed properties first, in that order, and the others after them in the order of the input file. Fields of later OpenAPI versions and extensions are never listed, so they follow the listed ones. A fixed order suits operations and schemas, where `summary` and `description` read better first. The order under `default` applies to every object without an order of its own, and the order under the name of a kind of object (see [Objects](#objects)) to that kind. **Example** - Preserve original property order for all schema objects ```yaml commands: format: openapi: property_order: default: original ``` **Example** - Sort all path items within `Paths` objects alphabetically ```yaml commands: format: openapi: property_order: paths: sorted ``` **Example** - Specify custom property order for `Operation` objects ```yaml commands: format: openapi: property_order: operation: # place summary and description at the beginning, to help # understand operation's purpose - summary - description - tags - operationId - externalDocs - deprecated - parameters - requestBody - responses - callbacks - security - servers ``` **Example** If the configuration for the `Contact` object looks like: ```yaml commands: format: openapi: property_order: contact: - name - url - email ``` and the actual contact data before formatting looks like: ```yaml openapi: 3.1.0 info: contact: x-team: awesome name: You email: you@example.com url: your.site x-audience: internal x-stability: stable ... ``` formatting it will change it to: ```yaml openapi: 3.1.0 info: contact: name: You url: your.site email: you@example.com x-team: awesome x-audience: internal x-stability: stable ... ``` ## Objects The keys of `property_order`, the objects they name, and the order the `recommended` preset gives each of them. Each key takes `sorted`, `original` or an array of property names. | Key | Object | Recommended order | | ----------------------- | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `openapi` | OpenAPI (document root) | openapi, $self, info, jsonSchemaDialect, servers, paths, webhooks, components, security, tags, externalDocs | | `info` | Info | title, summary, description, version, termsOfService, contact, license | | `contact` | Contact | name, url, email | | `license` | License | name, identifier, url | | `server` | Server | url, name, description, variables | | `serverVariable` | Server Variable | description, default, enum | | `paths` | Paths (the path templates) | sorted | | `pathItem` | Path Item (in paths, webhooks, callbacks and components) | $ref, summary, description, parameters, get, post, put, patch, delete, query, options, head, trace, additionalOperations, servers | | `operation` | Operation (also `query` and `additionalOperations`) | tags, summary, operationId, description, externalDocs, deprecated, parameters, requestBody, responses, callbacks, security, servers | | `components` | Components | schemas, responses, parameters, requestBodies, headers, mediaTypes, pathItems, securitySchemes, links, callbacks, examples | | `externalDocumentation` | External Documentation (also of schemas) | description, url | | `parameter` | Parameter | name, in, description, required, deprecated, style, allowEmptyValue, explode, allowReserved, schema, content, example, examples | | `requestBody` | Request Body | description, required, content | | `mediaType` | Media Type | description, schema, itemSchema, encoding, prefixEncoding, itemEncoding, example, examples | | `encoding` | Encoding | contentType, style, headers, explode, allowReserved, encoding, prefixEncoding, itemEncoding | | `responses` | Responses (the status codes of an operation) | sorted | | `response` | Response | summary, description, headers, content, links | | `example` | Example | summary, description, dataValue, serializedValue, value, externalValue | | `link` | Link | description, server, operationRef, operationId, parameters, requestBody | | `header` | Header | name, description, required, deprecated, allowEmptyValue, style, explode, allowReserved, schema, content, example, examples | | `tag` | Tag | name, summary, description, parent, kind, externalDocs | | `reference` | Reference (see below) | $ref, summary, description | | `schema` | Schema, at any depth | $schema, $id, $anchor, $dynamicAnchor, $ref, $dynamicRef, title, description, $comment, type, format, nullable, const, enum, numeric, string, array and object keywords, allOf, oneOf, anyOf, not, if, then, else, default, examples, example, readOnly, writeOnly, deprecated, discriminator, xml, externalDocs, $defs, definitions | | `discriminator` | Discriminator | propertyName, mapping, defaultMapping | | `xml` | XML | nodeType, name, namespace, prefix, attribute, wrapped | | `securityScheme` | Security Scheme | name, description, type, in, scheme, bearerFormat, flows, openIdConnectUrl, oauth2MetadataUrl, deprecated | | `oauthFlows` | OAuth Flows | implicit, password, clientCredentials, authorizationCode, deviceAuthorization | | `oauthFlow` | OAuth Flow | authorizationUrl, deviceAuthorizationUrl, tokenUrl, refreshUrl, scopes | | `componentNames` | The names in each map of Components | default | | `webhooks` | The names of webhooks | default | | `callbacks` | The names in the `callbacks` map of an operation | default | | `callback` | Callback (its runtime expressions) | default | | `content` | The media types of a `content` map | default | | `headers` | The names of a `headers` map | default | | `properties` | The names in `properties`, `patternProperties`, `$defs` and `dependentSchemas` | default | | `scopes` | OAuth scopes | default | | `extension` | Everything inside the value of an `x-` field | default | | `exampleValue` | Everything inside example payloads, `default`, `const` and `enum` values | default | The keys of named maps and raw values are independent of the object keys: for example, `componentNames: sorted` with `properties: original` and a fixed `schema` order sorts the schemas of the components by name, keeps the properties of each schema in their order and puts the keywords of each schema in the fixed order. Arrays are never sorted. **Example** - Sorted component names, everything else as in the input ```yaml commands: format: openapi: property_order: componentNames: sorted ``` ## OpenAPI versions and object recognition The formatter recognizes the objects of OpenAPI 3.0, 3.1 and 3.2 by their place in the document, from the root down, so names chosen by the author (paths, component names, schema properties) are never mistaken for fields: - Schemas are recognized at every depth: under `properties`, `patternProperties`, `additionalProperties`, `items` (a schema, or the array of schemas of 3.0), `prefixItems`, `allOf`, `anyOf`, `oneOf`, `not`, `if`, `then`, `else`, `$defs`, `dependentSchemas`, `contains`, `propertyNames`, `unevaluatedItems`, `unevaluatedProperties` and `contentSchema`, and under the `itemSchema` of a 3.2 media type. Boolean schemas are left as they are. - Path items and operations are recognized in `paths`, `webhooks`, the `callbacks` of operations at any depth and in components, and so are 3.2 `query` operations and `additionalOperations`. - Headers, media types, encodings (also 3.2 `prefixEncoding` and `itemEncoding`) and examples are recognized wherever the specification allows them, including the content and examples of headers. - Example payloads, `default`, `const` and `enum` values and the values of `x-` fields are data: they are never formatted as OpenAPI objects, and their keys follow the `exampleValue` and `extension` orders. An object in a place that allows a Reference Object (a parameter, request body, media type, response, header, example, link, callback, security scheme or path item) follows the `reference` order when it has a `$ref` field. A path item is a Reference Object only when it has no other fields than `$ref`, `summary` and `description`: next to its operations, `$ref` is merged with them. A schema with `$ref` is always a schema, because `$ref` is a schema keyword since 3.1; the `schema` order of the `recommended` configuration puts `$ref` first. A document that is valid YAML or JSON is formatted even when it is not a valid OpenAPI document; values in unexpected places keep the default order. --- # AsyncAPI documents Source: https://apigenie.pl/docs/reference/cli/format/asyncapi Part of the reference of [format](https://apigenie.pl/docs/reference/cli/format.md). Its other pages: [Layout and YAML styles](https://apigenie.pl/docs/reference/cli/format/styles.md), [Property order](https://apigenie.pl/docs/reference/cli/format/property-order.md), [Swagger 2.0 documents](https://apigenie.pl/docs/reference/cli/format/swagger.md), [Protobuf files](https://apigenie.pl/docs/reference/cli/format/protobuf.md), [GraphQL documents](https://apigenie.pl/docs/reference/cli/format/graphql.md). An AsyncAPI 3 document is recognized by the `asyncapi` field of its root and formatted with the `asyncapi` section of `commands.format`. The section takes `format`, `indent`, `force_array_indent` and `style`, with the values described in [Layout and YAML styles](/docs/reference/cli/format/styles), and `property_order`, with the [orders](/docs/reference/cli/format/property-order#orders) of the OpenAPI section and the objects below. The presets of `extends` apply to AsyncAPI documents as to the others. **Example** - Recommended settings for both specifications, with a custom property order for AsyncAPI `Operation` objects ```yaml commands: format: extends: - recommended asyncapi: indent: 2 property_order: channels: sorted operation: - action - channel - summary - description - messages - reply ``` ## Objects The keys of `property_order` are `default` and the names of the [objects of AsyncAPI 3](https://www.asyncapi.com/docs/reference/specification/v3.0.0) below. Each key takes `sorted`, `original` or an array of property names; the last column is the order of the `recommended` preset. | Key | Object | Recommended order | | ----------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `asyncapi` | AsyncAPI (document root) | asyncapi, id, info, servers, defaultContentType, channels, operations, components | | `info` | Info | title, version, description, termsOfService, contact, license, tags, externalDocs | | `contact` | Contact | name, url, email | | `license` | License | name, url | | `servers` | Servers | original | | `server` | Server | host, protocol, protocolVersion, pathname, title, summary, description, variables, security, tags, externalDocs, bindings | | `serverVariable` | Server Variable | enum, default, description, examples | | `channels` | Channels | sorted | | `channel` | Channel | address, title, summary, description, servers, parameters, messages, tags, externalDocs, bindings | | `parameter` | Parameter | enum, default, description, examples, location | | `operations` | Operations | original | | `operation` | Operation | action, channel, title, summary, description, security, tags, externalDocs, bindings, traits, messages, reply | | `operationTrait` | Operation Trait | title, summary, description, security, tags, externalDocs, bindings | | `operationReply` | Operation Reply | address, channel, messages | | `operationReplyAddress` | Operation Reply Address | description, location | | `message` | Message | name, title, summary, description, contentType, correlationId, headers, payload, tags, externalDocs, bindings, examples, traits | | `messageTrait` | Message Trait | name, title, summary, description, contentType, correlationId, headers, tags, externalDocs, bindings, examples | | `messageExample` | Message Example | name, summary, headers, payload | | `correlationId` | Correlation ID | description, location | | `tag` | Tag | name, description, externalDocs | | `externalDocumentation` | External Documentation | description, url | | `components` | Components | schemas, servers, channels, operations, messages, securitySchemes, serverVariables, parameters, correlationIds, replies, replyAddresses, externalDocs, tags, operationTraits, messageTraits, serverBindings, channelBindings, operationBindings, messageBindings | | `reference` | Reference | $ref | | `schema` | Schema (component, message payload/headers) | title, description, type, format, const, enum, default, examples, minimum, exclusiveMinimum, maximum, exclusiveMaximum, multipleOf, minLength, maxLength, pattern, items, contains, minItems, maxItems, uniqueItems, required, properties, ... | | `securityScheme` | Security Scheme | type, description, name, in, scheme, bearerFormat, flows, openIdConnectUrl, scopes | | `oauthFlows` | OAuth Flows | implicit, password, clientCredentials, authorizationCode | | `oauthFlow` | OAuth Flow | authorizationUrl, tokenUrl, refreshUrl, availableScopes | | `bindings` | Server, Channel, Operation, Message Bindings | sorted | Properties that are not listed in a fixed order are placed after the listed ones, in the same order as in the input file. --- # Swagger 2.0 documents Source: https://apigenie.pl/docs/reference/cli/format/swagger Part of the reference of [format](https://apigenie.pl/docs/reference/cli/format.md). Its other pages: [Layout and YAML styles](https://apigenie.pl/docs/reference/cli/format/styles.md), [Property order](https://apigenie.pl/docs/reference/cli/format/property-order.md), [AsyncAPI documents](https://apigenie.pl/docs/reference/cli/format/asyncapi.md), [Protobuf files](https://apigenie.pl/docs/reference/cli/format/protobuf.md), [GraphQL documents](https://apigenie.pl/docs/reference/cli/format/graphql.md). A Swagger 2.0 document is recognized by the `swagger` field of its root and formatted with the `swagger` section of `commands.format`. The section takes `format`, `indent`, `force_array_indent` and `style`, with the values described in [Layout and YAML styles](/docs/reference/cli/format/styles), and `property_order`, with the [orders](/docs/reference/cli/format/property-order#orders) of the OpenAPI section and the objects below. The presets of `extends` apply to Swagger documents as to the others. In YAML, the version must be quoted (`swagger: "2.0"`): an unquoted `2.0` is a number, and such documents are reported as unsupported. Every file keeps its own format unless `format` asks for another one: with `format: yaml`, formatting `swagger.json` in place writes `swagger.yaml` next to it. **Example** - Recommended settings, with sorted definitions and a custom property order for `Operation` objects ```yaml commands: format: extends: - recommended swagger: format: json indent: 2 property_order: definitions: sorted operation: - operationId - summary - tags - parameters - responses ``` ## Objects The keys of `property_order` are `default` and the names of the [objects of Swagger 2.0](https://swagger.io/specification/v2/) below. Each key takes `sorted`, `original` or an array of property names; the last column is the order of the `recommended` preset. | Key | Object | Recommended order | | ----------------------- | ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `swagger` | Swagger (document root) | swagger, info, host, basePath, schemes, consumes, produces, paths, definitions, parameters, responses, securityDefinitions, security, tags, externalDocs | | `info` | Info | title, description, version, termsOfService, contact, license | | `contact` | Contact | name, url, email | | `license` | License | name, url | | `paths` | Paths | sorted | | `pathItem` | Path Item | $ref, parameters, get, post, put, patch, delete, options, head | | `operation` | Operation | tags, summary, operationId, description, externalDocs, deprecated, schemes, consumes, produces, parameters, responses, security | | `externalDocumentation` | External Documentation | description, url | | `parameter` | Parameter (in path items, operations and `parameters`) | $ref, name, in, description, required, allowEmptyValue, schema, type, format, items, collectionFormat, default, enum, minimum, exclusiveMinimum, maximum, exclusiveMaximum, multipleOf, minLength, maxLength, pattern, minItems, maxItems, uniqueItems | | `items` | Items (of parameters and headers) | type, format, items, collectionFormat, default, enum, minimum, exclusiveMinimum, maximum, exclusiveMaximum, multipleOf, minLength, maxLength, pattern, minItems, maxItems, uniqueItems | | `responses` | Responses (of an operation) | sorted | | `response` | Response (in operations and `responses`) | $ref, description, schema, headers, examples | | `header` | Header | description, type, format, items, collectionFormat, default, enum, minimum, ..., uniqueItems | | `schema` | Schema, including nested ones | $ref, title, description, type, format, enum, default, minimum, exclusiveMinimum, maximum, exclusiveMaximum, multipleOf, minLength, maxLength, pattern, items, minItems, maxItems, uniqueItems, required, properties, additionalProperties, ... | | `xml` | XML | name, namespace, prefix, attribute, wrapped | | `definitions` | Definitions (`definitions`) | original | | `parametersDefinitions` | Parameters Definitions (`parameters` of the root) | original | | `responsesDefinitions` | Responses Definitions (`responses` of the root) | original | | `securityDefinitions` | Security Definitions | original | | `securityScheme` | Security Scheme | type, description, name, in, flow, authorizationUrl, tokenUrl, scopes | | `tag` | Tag | name, description, externalDocs | Schemas are recognized at any depth: in `definitions`, in body parameters and responses, and inside `properties`, `items`, `additionalProperties` and `allOf`. Values that are not Swagger objects, such as extensions (`x-*`), `example`, `examples`, `default`, `enum` and `scopes`, are ordered by the `default` setting only. Properties that are not listed in a fixed order are placed after the listed ones, in the same order as in the input file. --- # Protobuf files Source: https://apigenie.pl/docs/reference/cli/format/protobuf Part of the reference of [format](https://apigenie.pl/docs/reference/cli/format.md). Its other pages: [Layout and YAML styles](https://apigenie.pl/docs/reference/cli/format/styles.md), [Property order](https://apigenie.pl/docs/reference/cli/format/property-order.md), [AsyncAPI documents](https://apigenie.pl/docs/reference/cli/format/asyncapi.md), [Swagger 2.0 documents](https://apigenie.pl/docs/reference/cli/format/swagger.md), [GraphQL documents](https://apigenie.pl/docs/reference/cli/format/graphql.md). A file with the `.proto` extension is formatted as a proto3 file, with the `protobuf` section of `commands.format`: every declaration gets a canonical layout, nested declarations are indented, and imports, options, declarations, fields, enum values and methods are sorted as `sort` says. No comment is lost. ## Layout The formatter: - writes every declaration in a canonical layout: one statement per line, normalized spacing, blank lines between top-level declarations and around nested messages, enums and extends - indents nested declarations by the configured number of spaces - optionally sorts imports, options and declarations No comment is lost. Comments are written as `//` line comments and stay with their declarations when declarations are sorted. Comments that protoc ignores, such as those inside a declaration (`int32 /* type */ id = 1;`), are written as `/* */` comments directly before the end of their declaration (`int32 id = 1 /* type */;`). Files that are syntactically correct but break proto3 rules, for example with duplicate field numbers, are formatted. Files with syntax errors are reported with the position of each error and left untouched. Editions and proto2 files are not supported. ## Settings | Key | Values | Recommended | Description | | ------------------- | --------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `indent` | 1 to 8 | 2 | Number of spaces for one level of nesting. | | `sort.imports` | `original`, `sorted` | `sorted` | Sorts imports by path. | | `sort.options` | `original`, `sorted` | `sorted` | Sorts option statements and the options in brackets (`[deprecated = true, json_name = "x"]`) by name. | | `sort.declarations` | `original`, `grouped`, `sorted` | `original` | `grouped` puts top-level declarations in this order: package, imports, options, services, messages, enums, extends. `sorted` also sorts services, messages, enums and extends by name within their groups. | | `sort.fields` | `original`, `number`, `name` | `original` | Sorts the fields of messages, oneofs and extends. A oneof is placed by its lowest field number (or its name), and its fields are sorted too. | | `sort.enum_values` | `original`, `number`, `name` | `original` | Sorts enum values. A first value of zero stays first, as proto3 requires. | | `sort.nested_types` | `original`, `sorted` | `original` | Sorts the messages, enums and extends nested in a message by name. | Without a configuration file, the recommended settings are used. With `extends: [original]`, nothing is sorted. Each kind of declaration is sorted among the positions that declarations of that kind take in its body, so sorting fields, for example, does not move options, reserved statements or nested messages. Only the `grouped` and `sorted` values of `sort.declarations` move top-level declarations between kinds. Changing the order of fields, enum values or methods does not change the wire format, but it changes the order of declarations in generated code and descriptors. For this reason, the recommended configuration sorts only imports and options. **Example** - Recommended settings with 4-space indentation, and fields sorted by number ```yaml commands: format: extends: - recommended protobuf: indent: 4 sort: declarations: grouped fields: number enum_values: number ``` ```sh apigenie format api/store/v1/*.proto --config api-style-guide.yaml ``` --- # GraphQL documents Source: https://apigenie.pl/docs/reference/cli/format/graphql Part of the reference of [format](https://apigenie.pl/docs/reference/cli/format.md). Its other pages: [Layout and YAML styles](https://apigenie.pl/docs/reference/cli/format/styles.md), [Property order](https://apigenie.pl/docs/reference/cli/format/property-order.md), [AsyncAPI documents](https://apigenie.pl/docs/reference/cli/format/asyncapi.md), [Swagger 2.0 documents](https://apigenie.pl/docs/reference/cli/format/swagger.md), [Protobuf files](https://apigenie.pl/docs/reference/cli/format/protobuf.md). A file with the `.graphql`, `.graphqls` or `.gql` extension is formatted as a GraphQL document, a schema (type system definitions) or operations, with the `graphql` section of `commands.format`. The layout is that of [Prettier](https://prettier.io): a file formatted by Prettier with the same line width and indentation is left unchanged, and nothing is sorted unless `sort` says so. ## Layout The formatter: - writes selection sets, fields, enum values and input fields one per line - keeps argument lists, variable definitions, directives, list and object values, `implements` lists and union members on one line if they fit in the line width, and puts one item per line otherwise - keeps single blank lines between definitions and between members; several blank lines become one, and no blank lines are added - writes block strings (`"""`) on lines of their own, and trims the spaces around the text of a single line block string - keeps shorthand queries (`{ ... }`) and the `query` keyword as written - optionally sorts definitions and the members of types No comment is lost. Comments stay before or after the node they are written next to, and move with it when it is sorted. A node with a `# prettier-ignore` comment before it is written as it is in the source. Documents that are syntactically correct but break validation rules, for example with fields of unknown types, are formatted. Files with syntax errors are reported with the position of each error and left untouched. ## Differences from Prettier The output differs from that of Prettier in a few cases, where Prettier loses comments or writes documents that cannot be read back: - control characters in quoted strings, other than tabs, are written as escapes (`"\r"`, `"\u0001"`) instead of as they are - two comments after nodes that end on the same line are written on two lines; Prettier writes them on one line, which makes the second one part of the first - a comment on its own line between a description and a definition, or after the last variable or argument before `)`, stays there; Prettier moves it into the middle of a line, and moves it again on the next run Like Prettier, the formatter drops a blank line that follows a comment at the end of a member, and attaches comments written in the middle of a definition, such as between a field name and its type, to the nearest node, from where they can move again on the next run. ## Settings | Key | Values | Recommended | Description | | -------------------------- | ------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `indent` | 1 to 8 | 2 | Number of spaces for one level of nesting. | | `line_width` | 20 to 1000 | 80 | Line length that groups must fit in to stay on one line. East Asian wide characters count as two columns. | | `sort.definitions` | `original`, `grouped`, `sorted` | `original` | `grouped` puts definitions in this order: schema, directives, scalars, enums, interfaces, object types, input types, unions, operations, fragments. `sorted` also sorts them by name within their groups, with extensions after the definitions they extend. | | `sort.fields` | `original`, `sorted` | `original` | Sorts the fields of object types, interfaces and input types, and of their extensions, by name. | | `sort.enum_values` | `original`, `sorted` | `original` | Sorts enum values by name. | | `sort.arguments` | `original`, `sorted` | `original` | Sorts the argument definitions of fields and directives by name. | | `sort.union_members` | `original`, `sorted` | `original` | Sorts the member types of unions by name. | | `sort.interfaces` | `original`, `sorted` | `original` | Sorts the interfaces that types implement by name. | Without a configuration file, the recommended settings are used. Neither the recommended nor the `original` configuration sorts anything, because the order of definitions and fields shows in introspection results, generated code and documentation. Selections, arguments and variables of operations are never sorted, as selections define the order of the response. **Example** - 4-space indentation, a line width of 100 characters, and definitions and fields sorted by name ```yaml commands: format: extends: - recommended graphql: indent: 4 line_width: 100 sort: definitions: sorted fields: sorted ``` ```sh apigenie format schema/*.graphql --config api-style-guide.yaml ``` --- # apigenie i18n Source: https://apigenie.pl/docs/reference/cli/i18n Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md). Its other pages: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [format](https://apigenie.pl/docs/reference/cli/format.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md), [test](https://apigenie.pl/docs/reference/cli/test.md). Extracts texts for localization from OpenAPI, Swagger 2.0 and AsyncAPI specifications and Protobuf and GraphQL files, checks and updates their translations, and applies them. All subcommands work on all five: `i18n extract` writes the texts as a key-value file, `i18n check` tells whether a translation file is complete, `i18n sync` updates one after the document changed, and `i18n apply` puts the translated values back. ## Usage ```sh apigenie i18n extract [OPTIONS] FILE apigenie i18n check --translations TRANSLATIONS [OPTIONS] FILE apigenie i18n sync --previous PREVIOUS --translations TRANSLATIONS [OPTIONS] FILE apigenie i18n apply --translations TRANSLATIONS [--translations TRANSLATIONS ...] [OPTIONS] FILE ``` In version 0.9.0 `i18n` became a command with subcommands: `apigenie i18n FILE --output DEST` is now `apigenie i18n extract FILE --output DEST`. A typical workflow: 1. `apigenie i18n extract openapi.yaml --output i18n-en.json` writes the texts of the spec. 2. Translators turn `i18n-en.json` into `i18n-pl.json`, changing the values and keeping the keys. 3. `apigenie i18n check openapi.yaml --translations i18n-pl.json` fails, in CI for instance, until every text is translated and nothing else is. 4. `apigenie i18n apply openapi.yaml --translations i18n-pl.json --output openapi.pl.yaml` writes the Polish spec. 5. When the spec changes, `apigenie i18n sync openapi.yaml --previous i18n-en.json --translations i18n-pl.json --output i18n-pl.json` keeps the translations of the unchanged texts and lists the new texts, the changed ones (their translations may be stale) and the removed ones; then `i18n extract` writes the new `i18n-en.json`. The translation files can also be given to [`apigenie-generator docs`](/docs/reference/generator/docs) with `--i18n pl=i18n-pl.json`, which writes a translated copy of each document into the documentation site, with a locale switcher, without writing a translated spec. | Input | Recognized by | Keys | Texts | | --- | --- | --- | --- | | OpenAPI 3.0, 3.1, 3.2 | the `openapi` property (JSON or YAML) | JSON pointers | titles, summaries, descriptions, names | | Swagger 2.0 | the `swagger` property | JSON pointers | titles, summaries, descriptions, names | | AsyncAPI 3.x | the `asyncapi` property | JSON pointers | titles, summaries, descriptions, names | | Protobuf | the `.proto` extension | fully qualified names | leading comments | | GraphQL | the `.graphql`, `.graphqls` or `.gql` extension | schema coordinates and names | descriptions | ## i18n extract This command extracts texts suitable for translations, from an OpenAPI, Swagger 2.0 or AsyncAPI 3.x document, or from a Protobuf or GraphQL file. Files with the `.proto` extension are read as Protobuf files (see [Protobuf files](#protobuf-files)), and files with the `.graphql`, `.graphqls` or `.gql` extension as GraphQL files (see [GraphQL files](#graphql-files)); the kind of any other document is detected by its `openapi`, `swagger` or `asyncapi` property. Extracted texts are written in key-value files. For OpenAPI, Swagger and AsyncAPI, keys are JSON pointers to locations in the input file, and values are the strings the keys point to. For Protobuf and GraphQL files, keys are the full names of the documented declarations (see below). Example: ```sh apigenie i18n extract --output i18n-en.json openapi-in.yaml ``` may produce the following output: ```yaml /info/title: My API /info/contact/name: My Team ``` The command extracts the following properties of OpenAPI documents: | Object | Properties | | ------ | ---------- | | `Info` | `title`, `summary` (3.1+), `description` | | `Contact` | `name` | | `License` | `name` | | `Server` | `name` (3.2), `description` | | `ServerVariable` | `description` | | `PathItem` | `summary`, `description` | | `Schema` | `title`, `description` | | `Response` | `description` | | `Parameter` | `description` | | `Example` | `summary`, `description` | | `RequestBody` | `description` | | `Header` | `description` | | `SecurityScheme` | `description` | | `OAuthFlow` | the description of each scope, keyed `.../scopes/` | | `Link` | `description` | | `Operation` | `summary`, `description` | | `ExternalDocumentation` | `description` | | `Tag` | `summary` (3.2), `description` | | Reference Object | `summary`, `description` (3.1+): they override those of the referenced object at the place of the `$ref` only, so they are keyed there | Schemas are extracted wherever they are, including under `$defs`, `dependentSchemas` and `additionalItems` (`definitions` is not an OpenAPI 3.1 keyword, and is skipped). Identifiers and values that are part of the API's meaning are never extracted: names of tags, parameters, properties and scopes, `operationId`, URLs, enum values, defaults, examples, `xml.name` and `$comment`. the following properties of Swagger 2.0 documents, as for OpenAPI: | Object | Properties | | ------ | ---------- | | `Info` | `title`, `description` | | `Contact` | `name` | | `License` | `name` | | `Operation` | `summary`, `description` | | `Parameter` | `description` | | `Response` | `description` | | `Header` | `description` | | `Schema` | `title`, `description` | | `SecurityScheme` | `description` | | `ExternalDocumentation` | `description` | | `Tag` | `description` | and the following properties of AsyncAPI documents: | Object | Properties | | ------ | ---------- | | `Info` | `title`, `description` | | `Contact` | `name` | | `License` | `name` | | `Server` | `title`, `summary`, `description` | | `ServerVariable` | `description` | | `Channel` | `title`, `summary`, `description` | | `Parameter` | `description` | | `Operation` | `title`, `summary`, `description` | | `OperationTrait` | `title`, `summary`, `description` | | `OperationReplyAddress` | `description` | | `Message` | `title`, `summary`, `description` | | `MessageTrait` | `title`, `summary`, `description` | | `MessageExample` | `summary` | | `CorrelationId` | `description` | | `Schema` | `title`, `description` | | `SecurityScheme` | `description` | | `ExternalDocumentation` | `description` | | `Tag` | `description` | Texts are extracted where they are defined. An object used through a reference is extracted once, under `components` for instance, and objects kept in other files are not extracted; bundle the document first (`apigenie bundle`) to extract them too. Schemas in formats other than AsyncAPI and JSON Schema, such as Avro, and specification extensions are skipped. ### Protobuf files The texts of a Protobuf file are the leading comments of its declarations: the comment block right above a declaration, as `protoc` attaches it. Keys are fully qualified names instead of JSON pointers: | Declaration | Key | | ----------- | --- | | The file (the comment of its `syntax` statement) | the package, e.g. `acme.store.v1` | | Message, enum, service | `acme.store.v1.Order` | | Field, map field, oneof | `acme.store.v1.Order.id` | | Field of a oneof | the key of a field of the message, `acme.store.v1.Order.card` | | Enum value | under its enum, `acme.store.v1.Order.Status.STATUS_OPEN` | | Method | `acme.store.v1.OrderService.CreateOrder` | | Extension field | in the scope of its `extend` block, `acme.store.v1.max_length` | For example, the file ```proto syntax = "proto3"; package acme.greeter.v1; // Greets people. service Greeter { // Returns a greeting for one person. rpc SayHello(HelloRequest) returns (HelloReply); } ``` gives ```json { "acme.greeter.v1.Greeter": "Greets people.", "acme.greeter.v1.Greeter.SayHello": "Returns a greeting for one person." } ``` Comment markers are removed, as are one space at the start of each line, the whitespace at the end of each line, and empty lines at the start and the end of a comment. Line breaks inside a comment are kept. In a file without a package, the keys start with the top-level names and the file comment has the empty key. Trailing comments, detached comments (separated from the declaration by an empty line), and comments on the package, imports, options, `extend` blocks and `reserved` statements are not extracted. Imported files are not read. ### GraphQL files The command extracts the descriptions of GraphQL definitions, keyed by their full names: | Definition | Key | Example | | ---------- | --- | ------- | | Schema | `schema` | `schema` | | Scalar, object, interface, union, enum and input object type | type name | `Book` | | Field of an object or interface type | `Type.field` | `Book.title` | | Argument of a field | `Type.field(argument:)` | `Query.search(text:)` | | Field of an input object type | `Input.field` | `BorrowInput.days` | | Enum value | `Enum.VALUE` | `Genre.POETRY` | | Directive | `@directive` | `@key` | | Argument of a directive | `@directive(argument:)` | `@key(fields:)` | | Operation | operation type and name | `query FindBooks` | | Variable of an operation | `operation($variable:)` | `query FindBooks($text:)` | | Fragment | `fragment Name` | `fragment BookSummary` | Type system keys are the schema coordinates of the GraphQL specification. Fields, arguments and enum values of type extensions (`extend type`) are named after the extended type. An anonymous operation is keyed by its operation type only, e.g. `query`. Empty descriptions are skipped, and the document must be valid: duplicate names are reported as errors. For example, ```sh apigenie i18n extract --output i18n-en.yaml schema.graphql ``` may produce: ```yaml Query: The entry points of the library API Query.search(text:): The words to look for schema: The library service ``` ### Options #### -o, --output DEST Name of the file with extracted texts. Format of the file is determined by its extension: `.json`, or `.yaml` (`.yml`). Without it nothing is written: the file is only read and its problems reported. ## i18n apply This command replaces the texts of a document by their translations and writes the translated document. A translation file has the format `i18n extract` writes, in JSON or YAML: an object whose keys are those `i18n extract` gives for the document and whose values are the translated texts. Applying the texts `i18n extract` gives, untranslated, changes nothing. ```sh apigenie i18n apply --translations i18n-pl.json openapi.yaml --output openapi.pl.yaml ``` - A key that addresses nothing in the document (a key of an older version of the document, a mistyped one) is reported as a warning, and the other keys are applied. With `--strict`, it is an error, and nothing is written. - The translation files can be repeated: they are applied in order, so the translations of later files override those of earlier ones. - Comments are kept, unless `--strip-comments` is given. - A file that can't be read or parsed, or a translation that can't be applied (see below), is an error, and nothing is written. ### OpenAPI, Swagger and AsyncAPI specifications The keys are JSON pointers into the document (JSON or YAML). With `i18n-pl.json` ```json { "/info/title": "Moje API", "/paths/~1pets/get/summary": "Lista zwierząt" } ``` the title of the API and the summary of `GET /pets` are translated. Everything else is kept as it is: other values, the order of properties, and the YAML comments of the document, those of the translated texts included. - Only the texts `i18n extract` extracts are translated. A key pointing anywhere else, to an `operationId`, a URL, an object or a value that is not a string, addresses nothing: it is reported as a warning (an error with `--strict`), and the value is kept. The document must be a valid specification, so that its texts can be extracted. - Keys that are not JSON pointers, such as those of Protobuf and GraphQL files, and translations that are not strings, are errors. - References are not followed: a text used through a `$ref` is translated where it is defined, as `i18n extract` extracts it there. ### Protobuf files The keys are the fully qualified names `i18n extract` gives, and each translation replaces the leading comment of its declaration (the comment of the `syntax` statement for the package key): ```sh apigenie i18n apply --translations i18n-de.json greeter.proto --output greeter.de.proto ``` The comment is rewritten in place, in its style: `//` lines stay `//` lines with their indentation, and a `/* */` comment stays one, on one line if it was and the translation fits on one, as a `/*`, ` * line`, ` */` block otherwise. A translation containing `*/` is written as `//` lines, and an empty translation removes the comment. Nothing else changes: layout, trailing and detached comments, and the comments without a translation are kept byte for byte. A key naming a declaration without a leading comment addresses nothing. ### GraphQL files The keys are the schema coordinates and names `i18n extract` gives, and each translation replaces the description of its definition: ```json { "Query": "Die Einstiegspunkte der Bibliotheks-API", "Query.search(text:)": "Die zu suchenden Wörter" } ``` The description is rewritten in place, in its form: a block string (`"""..."""`) stays one, on one line if it was and the translation fits on one, on lines of their own at the indentation of the original otherwise; a quoted string (`"..."`) stays quoted, with escapes. A translation a block string can't hold (control characters, a common indentation of all lines) is quoted. Everything else is kept byte for byte, `#` comments included. A key naming a definition without a description addresses nothing. ### Options #### --translations TRANSLATIONS Path to a translation file, in JSON or YAML. Required. It can be repeated: the files are applied in order, so the translations of later files override those of earlier ones. #### -o, --output OUTPUT Path to the translated document. Defaults to the standard output. #### --format FORMAT Format of a translated specification, `json` or `yaml`. Defaults to the format of the input. Not available for Protobuf and GraphQL files, which are written in their own format. #### --strict Fails, without writing anything, when a key of a translation file addresses nothing in the document. #### --strip-comments Drops the comments of the document instead of keeping them: the YAML comments of a specification, the `#` comments of a GraphQL file (descriptions are kept, they are part of the schema). Not available for Protobuf files, whose translated texts are comments. ## i18n check This command compares a translation file with the texts of a document, and fails unless every text has a translation and every key of the file is a text. It is meant for CI: run it before publishing a translation. ```sh apigenie i18n check openapi.yaml --translations i18n-pl.json ``` `FILE` is a spec, a Protobuf or GraphQL file, whose texts are extracted as `i18n extract` does, or a file `i18n extract` wrote. The command reports, as errors: - the texts without a translation, in the order of the texts; - the texts whose translation is empty, unless `--allow-empty` is given; - the keys that are not texts of the document: a key of an older version of the document, a mistyped one, or one pointing to a value that is not meant to be translated, such as an `operationId`; - the keys that are not JSON pointers (for specs), and the translations that are not strings. It then writes, on the standard output, how many texts are translated: ```text i18n-pl.json: 74 of 76 texts translated (97.4%). ``` A text whose source changed after it was translated still counts as translated: `i18n sync` finds those. ### Options #### --translations TRANSLATIONS Path to the translation file, in JSON or YAML. Required. #### --allow-empty Counts empty translations (`""`) as translated, for texts meant to be empty in the language. #### --format FORMAT `text` (the default) or `json`. With `json`, nothing is written to the standard error, and the standard output is an object: ```json { "complete": false, "translated": 74, "total": 76, "coverage": 0.9736842105263158, "missing": ["/info/description", "/paths/~1pets/get/summary"], "empty": [], "unknown": [], "invalid": [] } ``` ## i18n sync This command updates a translation file after the document changed. Keys are locations, not texts: when a description changes, its key stays the same, and the old translation would still look complete. `i18n sync` compares the texts the translations were made from (`--previous`) with the current ones (`FILE`), and: - keeps the translations of the unchanged texts; - reports the texts whose source changed, as warnings: review their translations, which may be stale. With `--drop-changed`, their translations are dropped, so that `i18n check` reports them as missing; - reports the translations of removed texts, and keeps them unless `--prune` is given; - counts the new texts, which have no translation yet. ```sh apigenie i18n sync openapi.yaml --previous i18n-en.json --translations i18n-pl.json -o i18n-pl.json ``` `FILE` and `PREVIOUS` are specs, Protobuf or GraphQL files, or files `i18n extract` wrote: keeping the `i18n extract` output of the version the translators worked on is enough. Texts are matched by key, so a text that moved, such as a renamed path, is removed at its old key and added at its new one. The output follows the order of the current texts, then the kept translations of removed texts. Keys that are not JSON pointers, and values that are not strings, are copied at the end. ### Options #### --previous PREVIOUS The texts the translations were made from. Required. #### --translations TRANSLATIONS Path to the translation file to update, in JSON or YAML. Required. #### -o, --output OUTPUT Path to the updated translation file; its format follows its extension. With it, the command writes a summary (`3 new texts, 2 changed, 1 removed, 70 unchanged.`) on the standard output. Defaults to the standard output, in the format of the translation file. #### --prune Drops the translations of the texts the document no longer has. #### --drop-changed Drops the translations of the texts that changed, instead of keeping them for review. ## Exit status The subcommands exit with 0 on success, warnings about unknown keys and changed texts included. They exit with 1 when `i18n check` finds the translation file incomplete, or when, with `--strict`, a key of `i18n apply` addresses nothing. They exit with 2 when the input or a translation file can't be read or parsed, a translation can't be applied, an option isn't available for the input (`--format` for Protobuf and GraphQL files, `--strip-comments` for Protobuf files), or `i18n` is run without a subcommand. See the [exit statuses](/docs/reference/cli#exit-status) shared by the five binaries. ## See also - [bundle](/docs/reference/cli/bundle), to put the texts of referenced files into the document before extracting them - [`apigenie-generator docs`](/docs/reference/generator/docs), which takes the translation files with `--i18n` --- # apigenie init Source: https://apigenie.pl/docs/reference/cli/init Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md). Its other pages: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [format](https://apigenie.pl/docs/reference/cli/format.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md), [test](https://apigenie.pl/docs/reference/cli/test.md). Sets a repository up for API Genie and for coding agents: writes `apigenie.yaml` with the lint rules of the API descriptions it finds, and adds the section that tells coding agents how to check them to `AGENTS.md`. ## Usage ```sh apigenie init [DIR] [--ruleset recommended|strict|all] [--agents-file FILE] [--no-agents] [--dry-run] [--json] ``` ```sh apigenie init apigenie init --ruleset strict --agents-file CLAUDE.md ``` ## Description `init` works on the repository that holds `DIR` (the current directory by default): the directory of the configuration file the other commands would read there, else the root of its git repository, or `DIR` itself outside git. It finds the API descriptions in it as [`apigenie-catalog`](/docs/reference/catalog) does (the files git lists, OpenAPI, Swagger 2.0, AsyncAPI, Protobuf and GraphQL), lists them, and writes two files at the root: - **`apigenie.yaml`**, unless the repository has a [configuration file](/docs/reference/cli/configuration) already, which is kept as it is. The new file has the linter extend `--ruleset` (`recommended` by default) for OpenAPI and for each other family found, and `format` and `diff` their recommended settings. It names its JSON Schema for editors. - **The section "API descriptions"** for coding agents, the one the guide [Work with AI agents](/docs/guides/work-with-ai-agents) shows: in `AGENTS.md`, or the file of `--agents-file` (`CLAUDE.md`, `.github/copilot-instructions.md`, ...). A new file gets the section; a file without it gets it appended; a file with a line `## API descriptions` is kept. The section takes the file's line endings. `--no-agents` leaves the file alone. Running `init` again changes nothing. `--dry-run` prints what it would write and writes nothing. Commit both files, so that every agent and every CI run use the same rules. ## Options | Option | Description | | ------ | ----------- | | `--ruleset NAME` | `recommended` (default), `strict` or `all`: the ruleset the linter extends for every family. | | `--agents-file FILE` | The instructions file of the coding agents, relative to the repository and inside it (default `AGENTS.md`). | | `--no-agents` | Write no instructions for coding agents. | | `--dry-run` | Print what would be written, and write nothing. | | `--git PATH` | The git program (default `git`). | | `--json` | Print the report ([`apigenie-init-report.json`](https://apigenie.pl/schemas/apigenie-init-report.json)): the root, each file with its outcome (`created`, `updated`, `kept`, `skipped`) and the API descriptions found. | ## Exit status | Status | Meaning | | ------ | ------- | | 0 | The repository is set up (or, with `--dry-run`, would be). | | 2 | A usage error, a directory that doesn't exist, or git failed. | These are the statuses of every command ([exit status](/docs/reference/cli#exit-status)). ## See also - [Configuration](/docs/reference/cli/configuration): the sections of `apigenie.yaml`. - [Work with AI agents](/docs/guides/work-with-ai-agents): what the section asks of an agent. - [`apigenie-catalog init`](/docs/reference/catalog): the `catalog` section of `apigenie.yaml`. --- # apigenie license Source: https://apigenie.pl/docs/reference/cli/license Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md). Its other pages: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [format](https://apigenie.pl/docs/reference/cli/format.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md), [test](https://apigenie.pl/docs/reference/cli/test.md). Prints the license of API Genie, the names of the open-source libraries it is built with, or the license text of one of them. ## Usage ```sh apigenie license apigenie license --list apigenie license --library NAME ``` Without options, the command prints the terms under which the command-line tools are released as freeware. ## Options ### --list Prints the names of the libraries, separated by commas in lines of at most 80 characters, under the line `API Genie uses the following open-source libraries:`. With `--library` as well, `--list` wins. ### --library NAME Prints the license text of one library. `NAME` is a name as `--list` prints it, quoted when it has spaces: ```sh apigenie license --library LibBF apigenie license --library "Mbed TLS" ``` A name that is not in the list is reported (`No library with name NAME found.`). ## Exit status | Status | When | | ------ | ---------------------------------------- | | 0 | The text was printed. | | 2 | `--library` names an unknown library. | ## See also - [credits](/docs/reference/cli/credits): What each library does, with its project page. --- # apigenie lint Source: https://apigenie.pl/docs/reference/cli/lint Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md). Its other pages: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [format](https://apigenie.pl/docs/reference/cli/format.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md), [test](https://apigenie.pl/docs/reference/cli/test.md). Checks OpenAPI, Swagger 2.0 and AsyncAPI documents, Protobuf files and GraphQL schemas and operations against the rules of a ruleset, reports every issue with its position in the file, and fixes what its rules know how to fix. Each kind of document has a linter of its own, with its own rules, rulesets and configuration. [Linter rules](/docs/linter) lists the rules of all five with what each checks, since which version it exists and the rulesets that turn it on. ## Usage ```sh apigenie lint [OPTIONS] FILES... apigenie lint --fix [OPTIONS] FILES... apigenie lint --watch [OPTIONS] FILES... ``` Without options, each file is checked with the `recommended` ruleset of its linter, or with the rulesets of the project's configuration file, and the issues are printed in the `stylish` format, which ends with their counts: ```sh apigenie lint api/openapi.yaml ``` ```text 769:12 warning Object schema does not define constraints restricting its size schema-constraints 769:12 error Object schema does not disable additional properties schema-no-additional-properties 781:8 error Schema with integer type does not define proper format schema-format-defined 785:6 warning Unused shared component unused-shared-component 224 issues (32 errors, 192 warnings) 0 errors, 6 warnings are potentially auto-fixable ``` ## What the linter checks A file goes to the linter of its specification, which the linter tells from the root field of a JSON or YAML document, or from the file's extension: | File | Recognized by | Rules | Configuration | | ------------------------------ | ----------------------------------------------------------------------------- | ----- | ------------------------ | | OpenAPI 3.0, 3.1 or 3.2 | the `openapi` field of the root; any other JSON or YAML document is read as OpenAPI | 67 (64 before 0.12.0) | `commands.lint` | | Swagger 2.0 | the `swagger` field of the root | 48 | `commands.lint.swagger` | | AsyncAPI 3 | the `asyncapi` field of the root | 39 (34 before 0.12.0) | `commands.lint.asyncapi` | | Protobuf (proto3) | the `.proto` extension | 39 | `commands.lint.protobuf` | | GraphQL schemas and operations | the `.graphql`, `.graphqls` or `.gql` extension | 87 | `commands.lint.graphql` | A file that cannot be parsed, or that is not a document of its specification, is reported as `Errors reading OpenAPI file 'FILE':` (or `AsyncAPI`, `Swagger`, `Protobuf`, `GraphQL`) with the position and the message of each error, and the run stops with exit status 2; the files before it are reported. ### Rules and severities Every rule checks one thing, such as [contact-defined](/docs/linter/openapi/rules/contact-defined) (the `info.contact` of an OpenAPI document has a name and a way to reach it) or [paths-max-count](/docs/linter/openapi/rules/paths-max-count) (the document has at most the given number of paths). A rule has a severity, `error`, `warning` or `hint` (also written `info`), which its ruleset sets and the configuration changes. All three are reported, but only errors fail the run; hints are suggestions, and do not count as warnings either. A rule reports a hint where its advice cannot be followed yet, such as [schema-format-deprecated](/docs/linter/openapi/rules/schema-format-deprecated) in OpenAPI 3.0 documents. Some rules take options, listed on their pages, such as the number of paths of `paths-max-count`. ### Rulesets A ruleset is a named set of rules with their severities and options. Every linter has `recommended`, `strict`, which turns on more rules, and `all`, every rule of the linter. The OpenAPI linter also has [json-api](/docs/linter/openapi/rulesets/json-api), the conventions of JSON:API documents, and [privacy](/docs/linter/openapi/rulesets/privacy), which keeps credentials and personal data out of URLs and is not part of `all`; the AsyncAPI linter has [cloudevents](/docs/linter/asyncapi/rulesets/cloudevents), the envelope of CloudEvents messages, not part of `all` either; the GraphQL linter has [relay](/docs/linter/graphql/rulesets/relay), the Relay Cursor Connections conventions. A configuration lists the rulesets it `extends`, in order, and changes rules one by one under `rules`; see [Configuration](#configuration). The OpenAPI, AsyncAPI and Swagger linters also extend Spectral ruleset files, by their path (since 0.12.0); see [Ruleset files](#ruleset-files). The OpenAPI and Swagger linters ship with [`owasp`](#the-owasp-ruleset) (since 0.12.0), Spectral's OWASP API Security Top 10 ruleset, and the OpenAPI linter with [`camara`](#the-camara-ruleset), the [CAMARA project](https://camaraproject.org)'s ruleset. ### References to other files An OpenAPI document may keep parameters, request bodies, responses and other components in other files, or at URLs. The linter checks what the file holds. A rule about keys, such as `paths-sorted` or `standard-response-codes`, checks a path or a response in another file too; the other rules skip it. A rule doesn't report what another file may define: `path-parameters-defined` accepts a path parameter that a parameter in another file may define. Lint the other files too, or lint the document with [--bundle](#bundle) to check what the references lead to. ### AsyncAPI documents The 39 rules of the AsyncAPI linter are those of the OpenAPI linter that make sense for AsyncAPI 3 documents (`contact-defined`, `license-defined`, `operation-tags-defined`, `unused-shared-component` and others) and rules of its own, such as `channel-parameters-defined`, `channel-addresses-unique` and `server-hosts`. Since 0.12.0 they include the 5 core rules of the AsyncAPI parser (`asyncapi validate`) that the linter lacked: `operation-messages-from-channel`, `operation-channel-in-channels`, `channel-servers-in-servers`, `channel-address-no-query` and `latest-version`. Custom rules, JavaScript functions, `x-apigenie-lint-disable` and `--fix` work as for OpenAPI documents. OpenAPI and AsyncAPI files can be linted in one run. ### Swagger 2.0 documents The 48 rules of the Swagger linter are those of the OpenAPI linter that make sense for Swagger 2.0 documents (`operation-id-unique`, `parameters-unique`, `path-parameters-defined`, `unused-shared-component` and others) and rules of its own: `host-defined`, `schemes-secure`, `media-types-defined` and `swagger-validation`, which reports the violations of the Swagger 2.0 specification that span several objects (undefined security schemes, unresolved references, several body parameters and so on). Custom rules (with `oas2` in their `formats`), JavaScript functions, `x-apigenie-lint-disable` and `--fix` work as for OpenAPI documents. ### Protobuf files The 39 rules of the Protobuf linter check proto3 files for the naming of packages, files, messages, fields, enums and their values, oneofs, services and methods, for comments on declarations, for imports (resolved, used, sorted, without cycles, neither `public` nor `weak`), for the directory and version suffix of a package and the consistency of its options across files, for the request and response names of methods and their streaming, and for spelling. Imports are looked up in the directories of `--proto-path`, in the `import_paths` of the configuration and in the directories above the importing file. `--fix` fixes `import-used` and `imports-sorted`. ### GraphQL documents The 87 rules of the GraphQL linter check schemas and operations: the type system and operation rules of the GraphQL specification, naming conventions, descriptions, deprecations, schema design (root types, mutation inputs and payloads, unreachable types, identifiers), the Relay connection conventions, ordering and spelling. Operations are checked against a schema, the one of `--graphql-schema` or of the `schema` setting, or else the type system of their own document: unknown fields, types and arguments, required arguments, deprecated fields and selection depth. `--fix` does not change GraphQL files. ## Disabling rules in a document A rule that a part of a document breaks on purpose, because of a legacy decision or work in progress, is disabled in the document itself, as close to that part as possible: - In an OpenAPI, Swagger or AsyncAPI document, the `x-apigenie-lint-disable` extension of any object, the root included, lists the rules disabled for that object and everything nested in it. Here [contact-defined](/docs/linter/openapi/rules/contact-defined) is disabled for `info`, and so for its `contact`: ```yaml info: x-apigenie-lint-disable: - contact-defined ``` - In a Protobuf file, a comment attached to a declaration (before it, or at the end of its line) with `apigenie-lint-disable rule-a, rule-b` disables the rules for the declaration and everything nested in it; without rule ids it disables every rule. On the `syntax` statement it covers the whole file. - In a GraphQL document, a comment `# apigenie-lint-disable rule-a, rule-b` before a definition disables the rules for it and everything nested in it; without rule ids it disables every rule. The comments at the top of the file that a blank line separates from the first definition, and the comments of the `schema` definition, cover the whole file. Custom rules honour the extension and the comments like built-in rules. ## Custom rules A rule of the OpenAPI, Swagger or AsyncAPI linter can also be defined in the configuration, under `rules`, with an id that is not a built-in rule's. A custom rule is data, in the format of [Spectral](https://docs.stoplight.io/docs/spectral): it selects parts of the document with a JSONPath expression and checks each of them with a function. ```yaml version: "1.0" commands: lint: extends: [recommended] rules: operation-summary: description: Operations must have a summary message: "{{property}} is missing at {{path}}" severity: error given: "$.paths[*][get,put,post,delete,patch]" then: field: summary function: truthy ``` A rule definition accepts these properties: | Property | Description | | ------------- | ----------- | | `given` | JSONPath expression, or a list of them, selecting the values to check. Required. | | `then` | What to check: an object or a list of objects with `function`, optional `functionOptions` and optional `field`; a `message` there is ignored (since 0.12.0). Required. | | `field` | Narrows each selected value: a member path (`summary`, `a.b[0]`), `@key` to check member names, or a JSONPath expression relative to the value (`$.properties[*]`). | | `message` | Message template; see below. Defaults to `description`, then to the function's message. | | `description` | Human-readable description of the rule. | | `severity` | `error`, `warn` (default), `info`, `hint` or `off`. `info` and `hint` are reported as hints. | | `resolved` | Whether the rule sees the document with local `$ref`s followed. Defaults to `true`. | | `recommended` | `false` (since 0.12.0) leaves the rule off in a ruleset file extended with `recommended` (the default), until `rules` turns it on. Ignored in the configuration's own rules. | | `formats` | Restricts the rule to document formats: `oas2` (Swagger 2.0 documents), `oas3`, `oas3_0`, `oas3_1`, `oas3_2`, or, for AsyncAPI documents, `aas3` and `aas3_0`, `aas3_1`, ... | Messages may use `{{error}}` (the function's message), `{{description}}`, `{{path}}` (JSON pointer of the problem), `{{property}}` (the last path segment; since 0.12.0, for a path that doesn't exist, the path from its last existing member in Spectral's notation: `responses[429].content`) and `{{value}}`. Issues are reported where the offending value is defined, even when it is reached through a `$ref`. Custom rules honour `x-apigenie-lint-disable` like built-in ones. A custom rule can be switched off or have its severity changed later in the configuration (`my-rule: off`), but it cannot reuse the name of a built-in rule. ### JSONPath `given` and `field` expressions follow [RFC 9535](https://www.rfc-editor.org/rfc/rfc9535) with the extensions Spectral rulesets commonly use: - member unions without quotes: `$.paths[*][get,put]`; - `~` at the end selects member names: `$.paths[*]~`; - `^` selects the parent of what the query has selected so far (since 0.12.0): `$.paths..parameters[?(@.name === 'id')]^` is the list that holds the parameter. A member name that contains `^` is written in brackets: `$['a^b']`; - filters written as JavaScript expressions: `$..[?(@.type === 'object' && !@.properties)]`, with `@property`, `@parent`, `@parentProperty`, `@path` and `$`, and the string and array methods `match`, `test`, `startsWith`, `endsWith`, `includes`, `indexOf`, `toLowerCase`, `toUpperCase`, `trim` and `length`, and, since 0.12.0, `constructor.name`, which is `Array`, `Object`, `String`, `Number` or `Boolean`: `@.type.constructor.name === 'Array'`. Script expressions such as `[(@.length-1)]` and Spectral aliases (`#Name`) are not supported. ### Core functions | Function | Options | Checks that the value... | | -------- | ------- | ------------------------ | | `truthy`, `falsy` | none | is (not) truthy in the JavaScript sense | | `defined`, `undefined` | none | exists / does not exist | | `enumeration` | `values` | is one of the listed values | | `length` | `min`, `max` | has a length (string, array, object keys, number) within bounds | | `pattern` | `match`, `notMatch` | (does not) match a JavaScript regular expression; `/re/flags` is accepted | | `casing` | `type` (`flat`, `camel`, `pascal`, `kebab`, `cobol`, `snake`, `macro`), `disallowDigits`, `separator.char`, `separator.allowLeading` | follows a naming convention | | `alphabetical` | `keyedBy` | lists keys or items in alphabetical order | | `or`, `xor` | `properties` | has at least one / exactly one of the listed members | | `schema` | `schema`, `dialect`, `allErrors` | is valid against a JSON Schema (draft 4 to 2020-12) | | `typedEnum` | none | has `enum` values matching its `type` | | `unreferencedReusableObject` | `reusableObjectsLocation` | has only members referenced somewhere in the document | ### JavaScript functions When the core functions are not enough, a function can be written in JavaScript. It is listed under `functions`; API Genie loads `.js` from the `functions` directory next to the configuration file (change it with `functionsDir`). ```yaml commands: lint: functions: [operationIdPrefix] rules: operation-id-prefix: given: "$.paths[*][*].operationId" then: function: operationIdPrefix functionOptions: { prefix: api } ``` A function is an ES module whose default export receives the value, the options and a context, and returns a list of problems. The contract is that of Spectral custom functions, so a function written for Spectral works unchanged: ```js // functions/operationIdPrefix.js import { createRulesetFunction } from '@stoplight/spectral-core'; import { casing } from '@stoplight/spectral-functions'; export default createRulesetFunction( { input: { type: 'string' }, options: { type: 'object', properties: { prefix: { type: 'string' } }, required: ['prefix'], }, }, (input, options, context) => { if (!input.startsWith(options.prefix)) { return [{ message: `must start with "${options.prefix}"` }]; } return casing(input, { type: 'camel' }, context); }, ); ``` - `createRulesetFunction` validates `functionOptions` when the configuration is loaded and skips values that do not match `input`. - A result may carry a `path`, an array of keys and indexes, to point at a more specific location than `context.path`. Since 0.12.0, as in Spectral, a segment of another type, such as a negative number or an array, names the member that `String(value)` names. A path to a member that doesn't exist is reported at the closest member that does. - `context` provides `path`, `rule` (`name`, `severity`, `resolved`), `document` (`formats`, `data`) and `documentInventory`: `resolved`, `unresolved`, and, since 0.12.0, `graph.overallOrder()`, each distinct `$ref` value of the document once, depth first. - `console.log`, `console.info`, `console.warn`, `console.error` and `console.debug` print nothing (since 0.12.0); other `console` methods are not defined. - Functions may be `async`. - A function that throws is reported as an issue of its rule. Functions run in a sandbox: they can import other modules from the functions directory and the two built-in `@stoplight` modules, but have no access to the file system, network, processes or timers. Each call must finish within 5 seconds. Custom JavaScript functions are not available in the WebAssembly build. ### Ruleset files The OpenAPI, AsyncAPI and Swagger linters read Spectral ruleset files (YAML or JSON) since 0.12.0. `extends` names one by its path, relative to the configuration file, next to API Genie's rulesets: ```yaml commands: lint: extends: [recommended, ./lint/team.spectral.yaml] rules: team-no-todo: error ``` ```yaml # lint/team.spectral.yaml extends: ./base.spectral.yaml functionsDir: ./functions functions: [noTodo] rules: team-path-casing: given: "$.paths[*]~" then: { function: pattern, functionOptions: { match: "^(/[a-z-]+)+$" } } team-no-todo: recommended: false given: "$..description" then: { function: noTodo } ``` - An entry of `extends` is a path when it starts with `./`, `../`, `/`, `.\`, `..\` or `\`, is an absolute path, or ends in `.yaml`, `.yml` or `.json`. A file's own `extends`, `functions` and `functionsDir` resolve against that file. - The rulesets and the files apply in the order of `extends`, each file after what it extends, then the configuration's own `rules`, which can change the severity of a file's rule or switch it off. - `[ruleset, mode]` chooses how a ruleset's rules apply. `recommended` (the default) leaves out definitions with `recommended: false`, and `all` applies them too. `off` applies none, and a rule it defines can still be turned on under `rules`: `team-no-todo: error`, or `true` for the severity of its definition. On a built-in ruleset, `off` leaves it out and `all` is the same as `recommended`. - Files are local: a URL is an error, and so is a file that extends itself. In a ruleset file, `spectral:oas`, `spectral:asyncapi` and npm packages other than `@stoplight/spectral-owasp-ruleset` are skipped with a warning on the standard error. So are the settings of rules the linter doesn't have, and `aliases` and `overrides`. - A file in `extends` applies to the documents of that section's linter. A file of [--ruleset](#ruleset-file) applies to OpenAPI, AsyncAPI and Swagger documents: give its rules `formats` to keep them to one standard. A top-level `formats` is ignored, as are `description`, `documentationUrl` and `parserOptions`; another unknown top-level key is an error. - [--ruleset](#ruleset-file) adds a file from the command line. - The editor and the VS Code extension read ruleset files too, by relative path, without their functions: [the editor's hosts](/docs/reference/editor/hosts#panels) lists what they leave out. ### The `owasp` ruleset `owasp` (since 0.12.0) checks OpenAPI and Swagger 2.0 documents for 8 of the 10 risks of the [OWASP API Security Top 10](https://owasp.org/API-Security/editions/2023/en/0x11-t10/), 2023 edition: API1 to API5 and API7 to API9. Its rules cover numeric ids, authentication schemes, additional properties, unbounded strings, arrays and integers, rate limits, admin endpoints, URL parameters, error responses, CORS, plain HTTP and server inventories. It is Spectral's [`@stoplight/spectral-owasp-ruleset`](https://github.com/stoplightio/spectral-owasp-ruleset) 2.0.1, with its 32 rules and 2 JavaScript functions, and ships with API Genie: ```yaml version: '1.0' commands: lint: extends: [recommended, owasp] swagger: extends: [recommended, owasp] ``` With `extends: [owasp]` alone in `apigenie.yaml`, `apigenie lint openapi.yaml` reports 12 issues on this document: ```yaml openapi: 3.1.0 info: title: Pets version: 1.0.0 servers: - url: https://api.example.com paths: /pets: get: responses: '200': description: The pets content: application/json: schema: type: string ``` ```sh apigenie lint openapi.yaml ``` ```text 6:5 error Declare intended audience of every server by defining servers[0].x-internal as true/false. owasp:api9:2023-inventory-access 9:5 warning This read operation is not protected by any security scheme. owasp:api2:2023-read-restricted 10:7 warning Operation is missing rate limiting response in responses[429]. owasp:api4:2023-rate-limit-responses-429 10:7 warning Operation is missing rate limiting response in responses[429].content. owasp:api4:2023-rate-limit-responses-429 10:7 warning Operation is missing responses[401]. owasp:api8:2023-define-error-responses-401 10:7 warning Operation is missing responses[401].content. owasp:api8:2023-define-error-responses-401 10:7 warning Operation is missing responses[500]. owasp:api8:2023-define-error-responses-500 10:7 warning Operation is missing responses[500].content. owasp:api8:2023-define-error-responses-500 10:7 warning Missing error response of either 400, 422 or 4XX. owasp:api8:2023-define-error-validation 11:9 error All 2XX and 4XX responses should define rate limiting headers. owasp:api4:2023-rate-limit 15:15 error Schema of type string must specify maxLength, enum, or const. owasp:api4:2023-string-limit 15:15 warning Schema of type string should specify a format, pattern, enum, or const. owasp:api4:2023-string-restricted 12 issues (3 errors, 9 warnings) ``` - Its rules keep Spectral's ids and severities, and `rules` turns them off or changes their severity as for any other rule. `owasp:api7:2023-concerning-url-parameter`, `info` in Spectral, is reported as a hint. - Each rule applies to the documents Spectral applies it to, also from a ruleset file: none lints an AsyncAPI document. The rules that read `components.securitySchemes`, `owasp:api2:2023-no-http-basic`, `owasp:api2:2023-jwt-best-practices` and `owasp:api2:2023-short-lived-access-tokens`, report nothing in a Swagger 2.0 document. - A Spectral ruleset file that extends `@stoplight/spectral-owasp-ruleset` gets it without a change, as [`camara`](#the-camara-ruleset) does. In `apigenie.yaml`, write `owasp`. - On 120 of the 121 test documents of the upstream ruleset, it reports the rules, lines and messages that Spectral reports. On the other, which has an `apiKey` security scheme `in: path` that OpenAPI doesn't allow, API Genie stops with exit status 2. - The editor and the VS Code extension don't have it: its functions need JavaScript, which they don't run. There, a configuration that extends `owasp` gets an error on `extends` that begins `Unknown ruleset owasp`, and the documents are linted with the default rules. | Rule | Severity | Documents | | --- | --- | --- | | `owasp:api1:2023-no-numeric-ids` | error | Swagger 2.0, OpenAPI 3 | | `owasp:api2:2023-no-http-basic` | error | Swagger 2.0, OpenAPI 3 | | `owasp:api2:2023-no-api-keys-in-url` | error | OpenAPI 3 | | `owasp:api2:2023-no-credentials-in-url` | error | OpenAPI 3 | | `owasp:api2:2023-auth-insecure-schemes` | error | OpenAPI 3 | | `owasp:api2:2023-jwt-best-practices` | error | Swagger 2.0, OpenAPI 3 | | `owasp:api2:2023-short-lived-access-tokens` | error | Swagger 2.0, OpenAPI 3 | | `owasp:api2:2023-write-restricted` | error | Swagger 2.0, OpenAPI 3 | | `owasp:api2:2023-read-restricted` | warning | Swagger 2.0, OpenAPI 3 | | `owasp:api3:2023-no-additionalProperties` | warning | OpenAPI 3.0 | | `owasp:api3:2023-constrained-additionalProperties` | warning | OpenAPI 3.0 | | `owasp:api3:2023-no-unevaluatedProperties` | warning | OpenAPI 3.1 | | `owasp:api3:2023-constrained-unevaluatedProperties` | warning | OpenAPI 3.1 | | `owasp:api4:2023-rate-limit` | error | OpenAPI 3 | | `owasp:api4:2023-rate-limit-retry-after` | error | OpenAPI 3 | | `owasp:api4:2023-rate-limit-responses-429` | warning | Swagger 2.0, OpenAPI 3 | | `owasp:api4:2023-array-limit` | error | Swagger 2.0, OpenAPI 3 | | `owasp:api4:2023-string-limit` | error | Swagger 2.0, OpenAPI 3 | | `owasp:api4:2023-string-restricted` | warning | Swagger 2.0, OpenAPI 3 | | `owasp:api4:2023-integer-limit` | error | OpenAPI 3.1 | | `owasp:api4:2023-integer-limit-legacy` | error | Swagger 2.0, OpenAPI 3.0 | | `owasp:api4:2023-integer-format` | error | Swagger 2.0, OpenAPI 3 | | `owasp:api5:2023-admin-security-unique` | error | Swagger 2.0, OpenAPI 3 | | `owasp:api7:2023-concerning-url-parameter` | hint | Swagger 2.0, OpenAPI 3 | | `owasp:api8:2023-define-cors-origin` | error | Swagger 2.0, OpenAPI 3 | | `owasp:api8:2023-no-scheme-http` | error | Swagger 2.0 | | `owasp:api8:2023-no-server-http` | error | OpenAPI 3 | | `owasp:api8:2023-define-error-validation` | warning | Swagger 2.0, OpenAPI 3 | | `owasp:api8:2023-define-error-responses-401` | warning | Swagger 2.0, OpenAPI 3 | | `owasp:api8:2023-define-error-responses-500` | warning | Swagger 2.0, OpenAPI 3 | | `owasp:api9:2023-inventory-access` | error | OpenAPI 3 | | `owasp:api9:2023-inventory-environment` | error | OpenAPI 3 | ### The `camara` ruleset `camara` (since 0.12.0) is the ruleset the [CAMARA project](https://camaraproject.org) lints its APIs with, for Commonalities r4. It is the `.spectral-r4.yaml` file of [camaraproject/tooling](https://github.com/camaraproject/tooling/tree/main/linting/config) as of 4 November 2026, with its 41 rules and 14 JavaScript functions. It ships with API Genie, so nothing needs to be copied into the repository: ```yaml version: '1.0' commands: lint: extends: [camara] ``` - Its rules keep their ids (`camara-properties-descriptions`), and `rules` changes them as it changes any other rule. Two of them are `recommended: false`: `[camara, all]` also applies the deprecated `camara-discriminator-use`, and `camara-language-avoid-telco`, whose function only logs to the console and so reports nothing. `[camara, off]` applies none. - Upstream, the file also extends `@stoplight/spectral-owasp-ruleset`, which is [`owasp`](#the-owasp-ruleset) here: its rules apply with CAMARA's settings, which turn 15 of them off, make 4 warnings and make `owasp:api8:2023-define-error-responses-401` an error. It extends `spectral:oas` too, which API Genie doesn't have: those rules don't run, and nothing is reported about it. The file's setting `operation-success-response: true` turns on API Genie's rule of that id, as a warning. Add `recommended` next to it for API Genie's other checks: `extends: [recommended, camara]`. - A ruleset file can extend it too (`extends: [camara]`), which lints with it under `--no-config --ruleset FILE`. `--ruleset` itself always names a file. - CAMARA's APIs reference `CAMARA_common.yaml` and its other common files: lint them with [`bundle: true`](#configuration) in the configuration, or [--bundle](#bundle), so that the rules check what the references lead to. - The editor and the VS Code extension don't have it: its functions need JavaScript, which they don't run. There, a configuration that extends `camara` gets an error on `extends` that begins `Unknown ruleset camara`, and the documents are linted with the default rules. - [Lint CAMARA APIs](/docs/guides/industry/lint-camara-apis) sets up a CAMARA repository, its pull requests included. ## Fixing `--fix` fixes what the rules know how to fix and writes the files back under their names: the rules marked auto-fixable on their pages, 19 of the OpenAPI linter, 18 of the Swagger linter, 11 of the AsyncAPI linter and 2 of the Protobuf linter (`import-used` and `imports-sorted`). The YAML comments of a fixed OpenAPI, Swagger or AsyncAPI document stay with the values they belong to, and those of a value a fix removes go with it; `--strip-comments` drops them instead. A Protobuf file is fixed by editing its text, which keeps everything outside the edited declarations. Files without fixes are not rewritten. The exit status counts the issues that remain after the fixes. ## Formatters `--formatter NAME` chooses how the issues are written to standard output. The formats are those of ESLint's formatters, with SARIF added, so that tools which read ESLint reports read these too. Every format sorts the issues by file, then by line and column. `checkstyle`, `html`, `json`, `junit`, `sarif` and `tap` write one document for the whole run, reported at the end; `compact`, `stylish`, `unix` and `visualstudio` report each file as soon as it is linted. ### checkstyle The [Checkstyle](https://checkstyle.sourceforge.io) XML format. ```xml ``` ### compact The default output of JSHint: one line per issue. ``` /apigenie/data/openapi.yaml: line 2, col 2, Error - Info summary is missing or empty. (info-defined) /apigenie/data/openapi.yaml: line 12, col 4, Warning - Tag 'Articles' has no meaningful description defined. (tag-description-defined) /apigenie/data/openapi.yaml: line 13, col 4, Warning - Tag 'Comments' has no meaningful description defined. (tag-description-defined) /apigenie/data/openapi.yaml: line 14, col 4, Warning - Tag 'Favorites' has no meaningful description defined. (tag-description-defined) /apigenie/data/openapi.yaml: line 15, col 4, Warning - Tag 'Profile' has no meaningful description defined. (tag-description-defined) ``` ### html One HTML file, with the counts and a table of the issues, one row each, linking to the pages of the rules. ```html

API Genie Report

  • Total: 224
  • Errors: 32
  • Warnings: 192
/apigenie/data/openapi.yaml
2:2 Error Info summary is missing or empty info-defined
12:4 Warning Tag 'Articles' has no meaningful description defined tag-description-defined
``` ### json A JSON report, for scripts. `results` has one item per file with issues; `formatVersion` is the version of the format, which changes only when a member is removed or changes meaning (see [Compatibility](/docs/reference/cli/compatibility)). Its JSON Schema is [`apigenie-lint-report.json`](https://apigenie.pl/schemas/apigenie-lint-report.json). API Genie 0.9 and earlier wrote the bare `results` array. ```json5 { "formatVersion": 1, "results": [ { "filePath": "/apigenie/data/openapi.yaml", "messages": [ { "column": 2, "line": 2, "message": "Info summary is missing or empty", "ruleId": "info-defined", "severity": "error" }, { "column": 4, "line": 12, "message": "Tag 'Articles' has no meaningful description defined", "ruleId": "tag-description-defined", "severity": "warning" }, ... more issues ... ] } ] } ``` ### junit The format of the [JUnit Jenkins plugin](https://plugins.jenkins.io/junit/): a test suite per file, a test case per issue. ```xml ``` ### sarif [SARIF 2.1.0](https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html), the format of GitHub code scanning and other static analysis dashboards. Files below the current directory are given relative to it (`%SRCROOT%`), so that code scanning finds them in the repository. A result whose JSON pointer is known has it as a logical location and in a fingerprint, which lets code scanning keep tracking the issue when lines move. ```json5 { "$schema": "https://json.schemastore.org/sarif-2.1.0.json", "version": "2.1.0", "runs": [ { "tool": { "driver": { "name": "apigenie", "informationUri": "https://apigenie.pl", "rules": [ { "id": "info-defined", "helpUri": "https://apigenie.pl/docs/linter/openapi/rules/info-defined" }, ... more rules ... ] } }, "originalUriBaseIds": { "%SRCROOT%": { "uri": "file:///apigenie/" } }, "results": [ { "ruleId": "info-defined", "ruleIndex": 0, "level": "error", "message": { "text": "Info summary is missing or empty" }, "locations": [ { "physicalLocation": { "artifactLocation": { "uri": "data/openapi.yaml", "uriBaseId": "%SRCROOT%" }, "region": { "startLine": 2, "startColumn": 2 } }, "logicalLocations": [ { "fullyQualifiedName": "#/info", "kind": "member" } ] } ], "partialFingerprints": { "apigenieLocation/v1": "info-defined|data/openapi.yaml|#/info" } }, ... more issues ... ] } ] } ``` ### stylish The default: a table per file, with the position, the severity, the message and the rule of each issue, coloured on a terminal, and the counts at the end. ```sh 764:6 warning Unused shared component unused-shared-component 769:12 warning Object schema does not define constraints restricting its size schema-constraints 769:12 error Object schema does not disable additional properties schema-no-additional-properties 777:6 warning Unused shared component unused-shared-component 781:8 error Schema with integer type does not define proper format schema-format-defined 781:8 warning Integer schema does not define constraints restricting its range schema-constraints 785:6 warning Unused shared component unused-shared-component 789:8 error Schema with integer type does not define proper format schema-format-defined 789:8 warning Integer schema does not define constraints restricting its range schema-constraints 795:6 warning Unused shared component unused-shared-component 224 issues (32 errors, 192 warnings) 0 errors, 6 warnings are potentially auto-fixable ``` ### tap [Test Anything Protocol](https://testanything.org) version 14: one test per file, with the issues as its YAML diagnostics. ```yaml TAP version 14 1..1 not ok - /apigenie/data/openapi.yaml --- errorCount: 32 issues: - column: 2 line: 2 message: Info summary is missing or empty ruleId: info-defined severity: error - column: 4 line: 12 message: Tag 'Articles' has no meaningful description defined ruleId: tag-description-defined severity: warning - column: 4 line: 13 message: Tag 'Comments' has no meaningful description defined ruleId: tag-description-defined severity: warning ``` ### unix One line per issue in the `file:line:column: message` form of Unix tools, for `grep` and `awk`. ``` /apigenie/data/openapi.yaml:2:2: Info summary is missing or empty. [Error/info-defined] /apigenie/data/openapi.yaml:12:4: Tag 'Articles' has no meaningful description defined. [Warning/tag-description-defined] /apigenie/data/openapi.yaml:13:4: Tag 'Comments' has no meaningful description defined. [Warning/tag-description-defined] /apigenie/data/openapi.yaml:14:4: Tag 'Favorites' has no meaningful description defined. [Warning/tag-description-defined] /apigenie/data/openapi.yaml:15:4: Tag 'Profile' has no meaningful description defined. [Warning/tag-description-defined] /apigenie/data/openapi.yaml:16:4: Tag 'Tags' has no meaningful description defined. [Warning/tag-description-defined] ``` ### visualstudio The form the integrated terminal of Visual Studio turns into clickable errors. ``` /apigenie/data/openapi.yaml(2,2): error info-defined : Info summary is missing or empty. /apigenie/data/openapi.yaml(12,4): warning tag-description-defined : Tag 'Articles' has no meaningful description defined. /apigenie/data/openapi.yaml(13,4): warning tag-description-defined : Tag 'Comments' has no meaningful description defined. /apigenie/data/openapi.yaml(14,4): warning tag-description-defined : Tag 'Favorites' has no meaningful description defined. /apigenie/data/openapi.yaml(15,4): warning tag-description-defined : Tag 'Profile' has no meaningful description defined. /apigenie/data/openapi.yaml(16,4): warning tag-description-defined : Tag 'Tags' has no meaningful description defined. ``` ## Options ### --config FILE The configuration file. Without it, the first of `apigenie.yaml`, `apigenie.yml`, `apigenie.json`, `.apigenie.yaml`, `.apigenie.yml` and `.apigenie.json` found in the current directory or its parents, up to the root of the git repository, is read. See [Configuration](#configuration). ```sh apigenie lint --config api-style-guide.yaml api/*.yaml ``` ### --no-config Lints without looking for a configuration file: with the `recommended` ruleset of each linter, or, for the OpenAPI, AsyncAPI and Swagger linters, with the files of `--ruleset` instead. ### --ruleset FILE A Spectral ruleset file that OpenAPI, AsyncAPI and Swagger documents are linted with (since 0.12.0). It applies after the rulesets of the configuration's `extends` and before its `rules`, which can re-tune the file's rules. Without a configuration file, and for a linter whose section is missing, it replaces `recommended`. The path is relative to the current directory, and always names a file, whatever its name: a file that doesn't end in `.json` is read as YAML. Can be repeated; see [Ruleset files](#ruleset-files). ```sh apigenie lint --no-config --ruleset .spectral.yaml api/openapi.yaml ``` ### --fix Fixes the issues the rules know how to fix and writes the files back; see [Fixing](#fixing). The exit status counts the issues that remain. ```sh apigenie lint --fix api/openapi.yaml ``` ### --bundle Bundles the local files an OpenAPI 3.x document references into it before linting, as [bundle](/docs/reference/cli/bundle) does, so that the rules check what the references lead to. An issue in bundled content is reported in the file it comes from, at its line. A reference to a URL can't be bundled: the command reports it and exits with status 2. `--bundle` can't be combined with `--fix`, which would write the bundled document to the file. Swagger and AsyncAPI files are linted as they are. To bundle on every run except under `--fix`, set [`bundle: true`](#configuration) in the configuration. ```sh apigenie lint --bundle api/openapi.yaml ``` ### --strip-comments With `--fix`, drops the YAML comments of the OpenAPI, Swagger and AsyncAPI documents it rewrites instead of keeping them. ### --watch Keeps running, and lints again whenever an input file, the configuration file, a ruleset file, a JavaScript function file or a GraphQL schema file changes. A ruleset file that can't be read or parsed is watched too, so fixing it lints again. Each run is preceded by a `Changed: PATH` line for every changed file on standard error, so that the reports on standard output stay parseable. The command never exits because of issues. ```sh apigenie lint --watch --formatter compact api/*.yaml ``` ### --formatter NAME The format of the report: `checkstyle`, `compact`, `html`, `json`, `junit`, `sarif`, `stylish` (the default), `tap`, `unix` or `visualstudio`; see [Formatters](#formatters). ```sh apigenie lint --formatter sarif api/openapi.yaml > lint.sarif ``` ### --proto-path DIR A directory in which the imports of `.proto` files are looked up, before the `import_paths` of the configuration and the directories above the importing file. Can be repeated. ```sh apigenie lint --proto-path proto --proto-path third_party proto/acme/**/*.proto ``` ### --graphql-schema FILE A GraphQL schema file that the operations and fragments of the linted GraphQL files are checked against. Can be repeated for a schema split across files. When given, it replaces the files of the [schema](#graphql) setting of the configuration; relative paths resolve against the current directory. With `--watch`, the schema files are watched too. ```sh apigenie lint --graphql-schema schema.graphql queries/*.graphql ``` ## Exit status | Status | When | | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 0 | No issue of severity `error` was reported; warnings and hints do not count. With `--fix`, no error remains after the fixes. | | 1 | At least one error was reported, or remains after the fixes of `--fix`. | | 2 | The configuration, a ruleset file or an input file cannot be read or parsed or is invalid, a ruleset is a URL or a ruleset file extends itself, or an input is not a document of its specification. The files before it are reported. `--fix` is combined with `--bundle`: no file is linted. | With `--watch` the command keeps running and never exits because of issues. See the [exit statuses](/docs/reference/cli#exit-status) shared by the commands. ## Configuration The settings live under `commands.lint` of the [configuration file](/docs/reference/cli/configuration). The keys of the section configure the OpenAPI linter; its `asyncapi`, `swagger`, `protobuf` and `graphql` sections configure the other linters, each with its own rules. Without a configuration file, and for every linter whose section is missing, the `recommended` ruleset applies, as if the configuration were the one below. For the OpenAPI, AsyncAPI and Swagger linters, the files of [--ruleset](#ruleset-file) replace it. ```yaml version: "1.0" commands: lint: extends: [recommended] ``` | Key | Linter | Keys | | -------------- | -------- | -------------------------------------------------------------- | | `extends` | OpenAPI | The rulesets and ruleset files to combine, in order | | `rules` | OpenAPI | The settings of single rules, and custom rules | | `functions` | OpenAPI | The JavaScript functions of custom rules | | `functionsDir` | OpenAPI | Their directory, `functions` next to the configuration file | | `bundle` | OpenAPI | Whether to bundle the local files a document references first | | `asyncapi` | AsyncAPI | `extends`, `rules`, `functions`, `functionsDir` | | `swagger` | Swagger | `extends`, `rules`, `functions`, `functionsDir` | | `protobuf` | Protobuf | `extends`, `rules`, `import_paths` | | `graphql` | GraphQL | `extends`, `rules`, `self_contained`, `schema` | **Example** - The recommended rules, with one rule turned off, the severity of one changed, and the options of two set ```yaml version: "1.0" commands: lint: extends: - recommended rules: info-defined: off paths-max-count: - error - 30 schema-datetime-suffix: - error - At tags-unique: error ``` `bundle: true` (since 0.12.0) bundles the local files an OpenAPI 3.x document references into it before linting, on every run, as [--bundle](#bundle) does. The default is `false`, and then `--bundle` bundles for one run. `--fix` ignores the key: it lints and fixes each file as it is. The editor and the VS Code extension ignore `bundle` too: they lint what each file holds. **Example** - A [CAMARA](#the-camara-ruleset) repository, whose APIs reference its common files ```yaml version: "1.0" commands: lint: extends: [recommended, camara] bundle: true ``` The formats that the format rules accept come from the [format registry](/docs/reference/cli/formats), which [openapi.custom_formats](/docs/reference/cli/configuration#openapicustom_formats) extends for every linter of JSON and YAML documents. ### extends The rulesets whose rules, severities and options make up the starting point, in the order they are applied: when two rulesets set the same rule, the later one wins. The names are those of the ruleset pages of the linter ([OpenAPI](/docs/linter/openapi), [AsyncAPI](/docs/linter/asyncapi), [Swagger 2.0](/docs/linter/swagger), [Protobuf](/docs/linter/protobuf), [GraphQL](/docs/linter/graphql)). For the OpenAPI, AsyncAPI and Swagger linters, an entry can also be (since 0.12.0) a Spectral ruleset file, by its path relative to the configuration file, or a `[ruleset, recommended|all|off]` pair; see [Ruleset files](#ruleset-files). For the OpenAPI and Swagger linters, an entry can also be (since 0.12.0) [`owasp`](#the-owasp-ruleset), and for the OpenAPI linter [`camara`](#the-camara-ruleset); both ship with API Genie. ### rules The settings of single rules, applied over the rulesets, by rule id. A setting is one of: - a severity: `off` disables the rule; `warning` (also `warn`), `error` (`err`) and `hint` (`info`) enable it with that severity - `false`, which disables the rule, or `true`, which enables it with its current severity - a two-element array `[severity, options]`: an active severity and the options of the rule, described on its page - for an id that is not a built-in rule's, the definition of a [custom rule](#custom-rules) (OpenAPI, Swagger and AsyncAPI linters) **Example** - [paths-max-count](/docs/linter/openapi/rules/paths-max-count) reports an error above 30 paths, and `info-defined` is off ```yaml version: "1.0" commands: lint: rules: info-defined: off paths-max-count: - error - 30 ``` ### asyncapi The configuration of the AsyncAPI linter: `extends`, `rules`, `functions` and `functionsDir` as above, with the ids of the [AsyncAPI rules](/docs/linter/asyncapi). The OpenAPI settings of `commands.lint` do not apply to AsyncAPI documents. ```yaml version: "1.0" commands: lint: extends: [recommended] asyncapi: extends: [strict] rules: parameter-naming: [warning, camelCase] server-hosts: off ``` ### swagger The configuration of the Swagger linter: `extends`, `rules`, `functions` and `functionsDir` as above, with the ids of the [Swagger 2.0 rules](/docs/linter/swagger). The OpenAPI settings of `commands.lint` do not apply to Swagger documents. ```yaml version: "1.0" commands: lint: extends: [recommended] swagger: extends: [strict] rules: schemes-secure: [error, { upgradeInsecure: true }] swagger-validation: [error, { checks: [unresolved-reference, security-scheme-defined] }] paths-sorted: off ``` ### protobuf The configuration of the Protobuf linter: `extends` and `rules` as above, with the ids of the [Protobuf rules](/docs/linter/protobuf), and `import_paths`, the directories searched for imported files after those of `--proto-path`; relative paths resolve against the directory of the configuration file. ```yaml version: "1.0" commands: lint: protobuf: extends: [strict] import_paths: [proto, third_party] rules: enum-zero-value-suffix: [error, _UNKNOWN] rpc-no-client-streaming: off ``` ### graphql The configuration of the GraphQL linter: `extends` and `rules` as above, with the ids of the [GraphQL rules](/docs/linter/graphql), `self_contained` (whether each document holds every type and fragment it references, so that references to missing ones are reported; `false` by default) and `schema` (a path, or a list of paths, of the schema files operations are checked against; relative paths resolve against the directory of the configuration file; [--graphql-schema](#graphql-schema-file) replaces them). Without `schema`, operations are checked against the type system of their own document. ```yaml version: "1.0" commands: lint: graphql: extends: [recommended, relay] schema: schema.graphql rules: field-description-defined: warning selection-set-depth: [error, { maxDepth: 5 }] no-deprecated: off ``` ## See also - [Linter rules](/docs/linter): Every rule of the five linters, and the rulesets. - [Configuration](/docs/reference/cli/configuration): The configuration file, and where it is looked for. - [format](/docs/reference/cli/format): Lays out the documents the linter checks. - [GitHub Action](/docs/ci/github-action): Runs `apigenie lint` in a workflow. --- # apigenie overlay Source: https://apigenie.pl/docs/reference/cli/overlay Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md). Its other pages: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [format](https://apigenie.pl/docs/reference/cli/format.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [test](https://apigenie.pl/docs/reference/cli/test.md). Applies [OpenAPI Overlays](https://spec.openapis.org/overlay/latest.html) to an OpenAPI schema, or to any JSON or YAML document. ## Usage ```sh apigenie overlay [OPTIONS] --overlay OVERLAY [--overlay OVERLAY ...] INPUT apigenie overlay --validate --overlay OVERLAY [--overlay OVERLAY ...] ``` ## Description An overlay is a JSON or YAML document with an ordered list of actions. Each action selects nodes of the input with a JSONPath query (its `target`) and changes them. The overlays are applied in the order of the `--overlay` options, and the actions of an overlay in their order, each to the result of the previous one. The result is written to the standard output, or to the file of `--output`, in the format of the input unless `--format` says otherwise. YAML comments of the input and of the overlays are kept, unless `--strip-comments` is given. Strings that YAML 1.1 parsers would read as booleans or numbers, such as `yes`, `off`, `0755` or `1:30`, are written in double quotes. Overlays of versions 1.0, 1.1 and 1.2 of the specification are supported: `copy` actions need version 1.1 or later, `$self` and reusable actions (`components.actions`, referenced from the actions with `$ref`) version 1.2. The `extends` property is informative only: the input is always `INPUT`. To generate code from an overlaid document, there is no need for a separate step: `apigenie-generator` takes the overlays itself, with `--overlay`, and reports problems in the values they set at their lines in the overlay; see [overlays](/docs/reference/generator#overlays). For example, with `public.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Public API version: 1.0.0 actions: - target: $.info update: x-audience: public - target: $.servers[?@.description == 'Dev'] remove: true - target: $.paths.*.*.parameters[?@.name == 'debug'] remove: true ``` ```sh apigenie overlay --overlay public.overlay.yaml openapi.yaml -o public.yaml ``` ### Actions For every node the target selects: - with `remove: true`, the node is removed from its object or array; - otherwise the value of `update` (or, from version 1.1, a copy of the one node that the JSONPath query of `copy` selects) is merged into the node: - into an object, the value must be an object. Its members are added to the object, after the existing ones. When the object already has a member, a primitive value replaces a primitive value, an array is appended to an array, and an object is merged into an object the same way. Other combinations are errors; - to an array, an array is appended element by element, and any other value is appended as one element; - a primitive value (string, number, boolean or null) is replaced by the value, which must be a primitive value. An action without `update`, `copy` and `remove` changes nothing. The nodes selected by an action must all be objects, all arrays or all primitive values. An action that selects nothing changes nothing: the command warns about it on the standard error, and goes on. ### JSONPath Targets are JSONPath queries as defined by [RFC 9535](https://www.rfc-editor.org/rfc/rfc9535): names (`.name` or `['name']`), wildcards (`*`), indexes and slices (`[0]`, `[-1]`, `[1:3]`), descendants (`..`), unions (`[0, 2]`) and filters (`[?@.in == 'query']`), with the comparisons, `&&`, `||`, `!` and the functions `length()`, `count()`, `match()`, `search()` and `value()`. As an extension, member names written with a dot may contain `-`, as in `$.paths.*.get.x-internal`. ## Options | Option | Description | | ----------------------- | ------------------------------------------------------ | | `--overlay OVERLAY` | Path to an overlay. Required, can be repeated. | | `-o`, `--output OUTPUT` | Path to the result. Defaults to the standard output. | | `--format FORMAT` | Format of the result, `json` or `yaml`. | | `--validate` | Only checks the overlays. | | `--strip-comments` | Drops the comments of the result. | ### --overlay OVERLAY Path to an overlay, in JSON or YAML. The option can be repeated: the overlays are applied in the given order. When an overlay is invalid, its issues are listed and nothing is written. ### --output OUTPUT Path of the file to write the result to. Without it, the result is written to the standard output. ### --format FORMAT Format of the result: `json` or `yaml`. Defaults to the format of the input. ### --strip-comments Drops the YAML comments of the input and of the overlays from the result, instead of keeping them. ### --validate Checks the overlays against the specification of their version, without applying them: unknown properties, values of the wrong type, invalid JSONPath queries, unresolved reusable action references and duplicate actions are reported with their line and column. `INPUT` is not needed. The command exits with a non-zero status when an overlay has issues. ```sh apigenie overlay --validate --overlay public.overlay.yaml ``` --- # apigenie test Source: https://apigenie.pl/docs/reference/cli/test Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md). Its other pages: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [format](https://apigenie.pl/docs/reference/cli/format.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md). Runs the requests of `.http` files and requests generated from an OpenAPI or AsyncAPI document, a GraphQL schema or a `.proto` file against a live server, checks their assertions and scripts, and validates every request, response and message against the document or the schema with the checks of the [validating proxy](/docs/reference/server). HTTP requests are checked against an OpenAPI document, [GraphQL requests](/docs/reference/cli/test/graphql) against a GraphQL schema, [`GRPC` requests](/docs/reference/cli/test/grpc) against a `.proto` file, and [WebSocket and MQTT](/docs/reference/cli/test/websocket-mqtt), [Kafka](/docs/reference/cli/test/kafka) and [AMQP](/docs/reference/cli/test/amqp) requests and the requests of [HTTP channels](/docs/reference/cli/test/validation#requests-of-http-channels) against an AsyncAPI document. ## Topics - [Request files](/docs/reference/cli/test/requests): Regions, URLs and TLS, and the directives a request takes. - [Variables and OAuth 2](/docs/reference/cli/test/variables): Environment files, `{{name}}`, the responses of earlier requests, and tokens from a token endpoint. - [Assertions and scripts](/docs/reference/cli/test/assertions): `??` lines, and the JavaScript that runs before and after a request. - [Validation](/docs/reference/cli/test/validation): What `--spec` checks in requests, responses and messages, for each kind of document. - [Generated requests](/docs/reference/cli/test/generate): `--generate`: one request per operation, root field, method or channel of `--spec`. - [GraphQL requests](/docs/reference/cli/test/graphql): Queries, mutations and subscriptions over graphql-ws. - [WebSocket and MQTT requests](/docs/reference/cli/test/websocket-mqtt): `WS` and `MQTT` regions, the broker settings and MQTT 5 properties. - [Kafka requests](/docs/reference/cli/test/kafka): `KAFKA` regions: the records produced and read. - [AMQP requests](/docs/reference/cli/test/amqp): `AMQP` regions: the messages published and consumed. - [gRPC requests](/docs/reference/cli/test/grpc): `GRPC` requests to the methods of a `.proto` file, streams included. - [Importing collections](/docs/reference/cli/test/import): `apigenie test import`: a Postman collection as request files. - [httpYac compatibility](/docs/reference/cli/test/httpyac): What of the httpYac format is read, and what is not yet. ## Usage ```sh apigenie test [OPTIONS] FILES... apigenie test --spec SPEC --generate [--base-url URL] [OPTIONS] [FILES...] apigenie test --spec schema.graphql [--generate --base-url URL] [OPTIONS] [FILES...] apigenie test --spec service.proto [--proto-path DIR ...] FILES... apigenie test --spec ASYNCAPI --generate [--base-url ws://HOST:PORT] [--mqtt-url mqtt://HOST:PORT] [OPTIONS] apigenie test import COLLECTION -o DIR [--environment FILE ...] [--spec SPEC] [--force] ``` The request files are written in the httpYac flavour of the `.http` format (see [Request files](/docs/reference/cli/test/requests)). Three requests, the second reading the response of the first, and the run that checks them against an OpenAPI document: ```http @host = http://localhost:4010/v1 ### List pets # @name list GET {{host}}/pets?limit=2 Accept: application/json ?? status == 200 ?? body $ isArray ### Read the first one GET {{host}}/pets/{{list.response.body.$[0].id}} {{ exports.petName = response.parsedBody.name; test("has a name", () => assert.ok(response.parsedBody.name)); }} ### Create a pet POST {{host}}/pets Content-Type: application/json {"id": 7, "name": "{{petName}}"} ?? status == 201 ``` ```sh apigenie test --spec openapi.yaml pets.http --report report.json --report-junit report.xml ``` ```text PASS GET http://localhost:4010/v1/pets?limit=2 -> 200 (9 ms) listPets PASS GET http://localhost:4010/v1/pets/746 -> 200 (4 ms) showPetById PASS POST http://localhost:4010/v1/pets -> 201 (2 ms) createPets Requests: 3 passed, 0 failed, 0 skipped Contract: 3 requests (0 undocumented), 0 errors, 0 warnings Coverage: 70.0% of 10 branches, 3 of 3 operations ``` ## Options | Option | Description | | --- | --- | | `FILES` | `.http` and `.rest` files, or directories to search for them | | `--spec SPEC` | The OpenAPI 3.0, 3.1 or 3.2 (or Swagger 2.0) document HTTP requests are validated against, the GraphQL schema (`.graphql`, `.graphqls`, `.gql`) of GraphQL requests, the `.proto` file of `GRPC` requests, or the AsyncAPI 3.x document WS, MQTT, KAFKA and AMQP requests and the requests of its HTTP channels are validated against | | `--proto-path DIR` | A directory in which the imports of a `.proto` `--spec` are looked up; can be repeated | | `--generate` | Also send one request per operation (OpenAPI), root field (GraphQL), method (`.proto`) or channel (AsyncAPI; one per operation of an HTTP, Kafka or AMQP channel) of `--spec` | | `--base-url URL` | The server's URL for `--generate` (the endpoint, required, for a GraphQL schema; `HOST:PORT` for a `.proto` file; `ws://` or `http://` for an AsyncAPI document's WebSocket and HTTP channels), also put before request URLs that start with `/` | | `--mqtt-url URL` | The MQTT broker (`mqtt://host:port`) of an AsyncAPI document's channels for `--generate` | | `--amqp-url URL` | The AMQP broker (`amqp://host:port/vhost`, `amqps://` over TLS) of an AsyncAPI document's AMQP channels for `--generate` | | `--kafka-url URL` | A broker of the Kafka cluster (`kafka://host:port`, `kafkas://` over TLS) of an AsyncAPI document's Kafka channels for `--generate` | | `--env NAME` | The environment of the environment files | | `--env-file FILE` | An environment file to read after the others; can be repeated | | `--var NAME=VALUE` | A variable above every other one; can be repeated | | `--header NAME:VALUE` | A header for every request that doesn't have it; can be repeated | | `--timeout MS` | How long to wait for a connection and for a response (30000) | | `--message-timeout MS` | How long WS, MQTT, KAFKA and AMQP requests, GraphQL subscriptions and gRPC client and bidi streams wait for messages (5000); `# @timeout` overrides it | | `--bail` | Stop at the first failed request | | `--ca-cert FILE` | A PEM file of certificate authorities trusted for `https://`, `grpcs://`, `wss://`, `mqtts://`, `kafkas://` and `amqps://` URLs, besides the system's; can be repeated | | `--insecure` | Don't verify the certificates of `https://`, `grpcs://`, `wss://`, `mqtts://`, `kafkas://` and `amqps://` servers; the traffic stays encrypted | | `--client-cert FILE` | A PEM client certificate (chain) presented to `https://`, `grpcs://`, `wss://`, `mqtts://`, `kafkas://` and `amqps://` servers that ask for one (mTLS); needs `--client-key` | | `--client-key FILE` | The unencrypted PEM private key of `--client-cert` | | `--report FILE` | Write the JSON report | | `--report-junit FILE` | Write the JUnit XML report | | `--fail-on none\|errors\|warnings` | The contract violations that fail the run (`errors`) | | `--min-coverage PERCENT` | Fail the run below this coverage of `--spec` (a GraphQL schema: the share of its fields; a `.proto` file: the share of its methods; an AsyncAPI document: the share of its operations' messages) | | `--severity CHECK=LEVEL` | Change a contract check's severity: `error`, `warn`, `info` or `off` (`ignore`); can be repeated. The checks are those of the OpenAPI, gRPC and AsyncAPI proxies or, with a GraphQL schema, of the GraphQL proxy; an unknown check is a bad option | | `--seed N` | Seed of the values `--generate` makes up | | `--formatter stylish\|json` | A line per request and a summary (`stylish`), or a JSON object per line | | `--quiet` | Show only failed requests and the summary | | `--verbose` | Also show the warnings and notes of the contract checks, and the scripts' log | ### --fail-on errors|warnings|none A failed request (an assertion, a script's test or error, no response, an unknown `@ref`) always fails the run. `--fail-on` says which contract violations do too: `errors` (the default), `warnings` (errors and warnings) or `none`. A request with such violations is shown as `FAIL`. ### --formatter json Each request is a line `{"event":"request",...}` with the members of the JSON report's `requests`; warnings are `{"event":"warning","file":...,"line":...,"message":...}`, notes about a Swagger 2.0 specification `{"event":"info",...}` with the same members; the last line is `{"event":"summary","formatVersion":1,"total":...,"passed":...,"failed":...,"skipped":...,"gate":{...}}` with the contract's `errors`, `warnings` and `coverage` when there is a `--spec`. Its `formatVersion` versions the whole stream, as `formatVersion` versions the report. ## Reports `--report` writes the [contract report](/docs/reference/server/contract-testing) of `apigenie-server` with `"report": "apigenie-test"`, plus `tests` (the counts and the run's gate) and `requests` (each request's file, line, URL, status, duration, operation, outcome, failures, assertions, violations and log; `grpc` and `grpcStatus` for `GRPC` requests). With a `.proto` file the contract members are those of the gRPC report (`"specification": "grpc"`, `methods`, `services`), with a GraphQL schema those of the GraphQL report (`"specification": "graphql"`, `rootFields`, `fields`, `uncoveredFields`, `operations`). Without `--spec`, only `report`, `formatVersion`, `version`, `startedAt`, `endedAt`, `tests` and `requests` are written. `formatVersion` is the version of the format, which changes only when a member is removed or changes meaning (see [Compatibility](/docs/reference/cli/compatibility)); `version` is its former name, kept for one release. The JSON Schema of the report is [`apigenie-test-report.json`](https://apigenie.pl/schemas/apigenie-test-report.json). `--report-junit` writes a `requests` suite (a test case per request: failed, or skipped for disabled requests) and, with `--spec`, the contract suite of `apigenie-server`. With an AsyncAPI document, the report is the AsyncAPI proxy's (`"specification": "asyncapi"`, channels, operations with their messages, violations); WS and MQTT requests also have `channel`, `address`, `messagesSent`, `messagesReceived` and `notes` (what wasn't checked, and why), and the coverage `--min-coverage` checks is the share of the operations' messages seen. ## Exit status | Code | Meaning | | --- | --- | | 0 | Every request passed and the contract gate held | | 2 | Bad options: no request files without `--generate`, `--generate` without `--spec`, or with a GraphQL schema or a `.proto` file but no `--base-url`, `--min-coverage` without `--spec`, an unknown `--severity` check; a request file, an environment file or the specification (an OpenAPI or AsyncAPI document, a GraphQL schema, or a `.proto` file with its imports) that can't be read or parsed; `--generate` without a URL it can use (no `--base-url` and no absolute server URL in the document, or a URL of the wrong scheme); a report that can't be written, or an unexpected error | | 5 | A request failed, or contract violations (`--fail-on`) or the coverage (`--min-coverage`) failed the run | ## See also - [`apigenie-server`](/docs/reference/server), whose validating proxy checks traffic something else drives, with the same checks and reports - [lint](/docs/reference/cli/lint), which checks the document itself --- # Request files Source: https://apigenie.pl/docs/reference/cli/test/requests Part of the reference of [test](https://apigenie.pl/docs/reference/cli/test.md). Its other pages: [Variables and OAuth 2](https://apigenie.pl/docs/reference/cli/test/variables.md), [Assertions and scripts](https://apigenie.pl/docs/reference/cli/test/assertions.md), [Validation](https://apigenie.pl/docs/reference/cli/test/validation.md), [Generated requests](https://apigenie.pl/docs/reference/cli/test/generate.md), [GraphQL requests](https://apigenie.pl/docs/reference/cli/test/graphql.md), [WebSocket and MQTT requests](https://apigenie.pl/docs/reference/cli/test/websocket-mqtt.md), [Kafka requests](https://apigenie.pl/docs/reference/cli/test/kafka.md), [AMQP requests](https://apigenie.pl/docs/reference/cli/test/amqp.md), [gRPC requests](https://apigenie.pl/docs/reference/cli/test/grpc.md), [Importing collections](https://apigenie.pl/docs/reference/cli/test/import.md), [httpYac compatibility](https://apigenie.pl/docs/reference/cli/test/httpyac.md). The request files `apigenie test` runs are written in the [httpYac](https://httpyac.github.io/) flavour of the `.http` format, which the JetBrains HTTP client and VS Code's REST Client read too. Directories are searched for `.http` and `.rest` files. A file is split into regions by lines starting with `###` (the rest of the line is the region's title). A region has comments and directives (`#` or `//`), variable definitions, the request line (`METHOD URL [HTTP/1.1]`; a URL alone is a `GET`), headers up to the first blank line, and a body up to the next region, script or assertion. Lines starting with `?` or `&` right after the request line continue the URL. A body of `< ./file.json` is read from that file, `<@ ./file.json` with its variables substituted. Requests run in the order of the file, files in the order given. `http://` and `https://` URLs both work. For `https://` (and `grpcs://`, `wss://` and `mqtts://` alike), the server's certificate is checked against the system's root certificates and the URL's host name. `--ca-cert FILE` adds authorities, such as a test CA or a company's root, and `--insecure` skips the check. `SSL_CERT_FILE` replaces the system's roots. A certificate that is rejected fails the request with the reason, for example `no response: TLS with 10.0.0.5:443: certificate verification failed: The certificate is not correctly signed by the trusted CA`. A server behind mutual TLS asks for a client certificate: `--client-cert client.pem --client-key client.key` presents one to every `https://`, `grpcs://`, `wss://` and `mqtts://` server that asks (with `--insecure` too). The key must be PEM and not encrypted; a file that can't be read, or a key of another certificate, stops the run with exit status 2. Without one, such a server fails the request, for example `no response: TLS with api.example.com:443: the peer refused the connection: the server requires a client certificate`. TLS sessions aren't resumed (every connection does a full handshake), and certificates aren't checked for revocation (no CRL or OCSP). | Directive | Meaning | | --- | --- | | `# @name list` | Names the request, so that others can refer to its response | | `# @ref list` | Runs `list` first, unless it already ran | | `# @forceRef list` | Runs `list` first, every time | | `# @operation getPet` | Checks the request as the operation `getPet` of `--spec` (an AsyncAPI document's operation of an HTTP, WS or MQTT channel); for a GraphQL request, the operation to run (`operationName`) | | `# @operation off` | Doesn't check the request against `--spec`, nor count it in the coverage | | `# @channel pickupDesk` | WS and MQTT: checks the messages against that channel of the AsyncAPI document | | `# @timeout 8000` | WS and MQTT, GraphQL subscriptions, gRPC client and bidi streams: waits up to 8000 ms for messages (`--message-timeout`, 5000 by default) | | `# @expect 2` | WS and MQTT, GraphQL subscriptions: stops waiting after 2 messages; `0` doesn't wait | | `# @property content-type application/json` | MQTT 5: a property of the messages the region publishes (see [MQTT 5 properties](/docs/reference/cli/test/websocket-mqtt#mqtt-5-properties)) | | `# @disabled` | Skips the request | | `# @postman` | Enables the collection-import compatibility API for this file | | `# @title`, `# @description`, `# @tag`, `# @no-log`, `# @no-redirect`, `# @verbose`, ... | Accepted and ignored | Any other directive is a warning: the request still runs. --- # Variables and OAuth 2 Source: https://apigenie.pl/docs/reference/cli/test/variables Part of the reference of [test](https://apigenie.pl/docs/reference/cli/test.md). Its other pages: [Request files](https://apigenie.pl/docs/reference/cli/test/requests.md), [Assertions and scripts](https://apigenie.pl/docs/reference/cli/test/assertions.md), [Validation](https://apigenie.pl/docs/reference/cli/test/validation.md), [Generated requests](https://apigenie.pl/docs/reference/cli/test/generate.md), [GraphQL requests](https://apigenie.pl/docs/reference/cli/test/graphql.md), [WebSocket and MQTT requests](https://apigenie.pl/docs/reference/cli/test/websocket-mqtt.md), [Kafka requests](https://apigenie.pl/docs/reference/cli/test/kafka.md), [AMQP requests](https://apigenie.pl/docs/reference/cli/test/amqp.md), [gRPC requests](https://apigenie.pl/docs/reference/cli/test/grpc.md), [Importing collections](https://apigenie.pl/docs/reference/cli/test/import.md), [httpYac compatibility](https://apigenie.pl/docs/reference/cli/test/httpyac.md). Where the values of `{{name}}` come from, and how a request gets a token from an OAuth 2 token endpoint. ## Environments and variables `{{name}}` is replaced by the variable `name`. Variables come from, the later winning: 1. the environment files of the request file's directory or, when it has none, the working directory: `http-client.env.json` (its `$shared` object, then the object of `--env`), `http-client.private.env.json` (the same), `.env` and `.env.NAME`; 2. `--env-file` files (JSON like `http-client.env.json`, or `KEY=VALUE` lines); 3. `@name = value` lines outside of requests; 4. what scripts set (`exports`, `client.global.set`); 5. `@name = value` lines of the request's region; 6. `--var NAME=VALUE`. Responses of named requests can be used in the requests after them: | Reference | Value | | --- | --- | | `{{list.response.status}}` | The status | | `{{list.response.headers.Location}}` | A header | | `{{list.response.body.$[0].id}}`, `{{list.response.body./0/id}}` | A value of the JSON body (a path or a JSON pointer) | | `{{list.response.body}}` | The body | | `{{list.id}}` | httpYac's form: a value of the JSON body | Built-in variables: `{{$uuid}}` (and `$guid`, `$random.uuid`), `{{$timestamp}}`, `{{$isoTimestamp}}`, `{{$datetime iso8601}}`, `{{$datetime rfc1123}}`, `{{$randomInt MIN MAX}}`, `{{$processEnv NAME}}` and `{{$dotenv NAME}}`. A variable that isn't defined is a warning and stays as it is. `\{{` is a literal `{{`. `Authorization: Basic user:password` (or `Basic user password`) is sent base64-encoded, as httpYac and the JetBrains client do. ## OAuth 2 `Authorization: oauth2 [GRANT] [PREFIX]` gets a token from the token endpoint and sends `Authorization: Bearer TOKEN` instead, with httpYac's syntax and variables: ```http GET {{host}}/pets Authorization: oauth2 client_credentials ``` | Grant | Sent to the token endpoint | | --- | --- | | `client_credentials` (when no grant is written) | The client's credentials | | `password` | `PREFIX_username` and `PREFIX_password` too | | `refresh_token` | `PREFIX_refreshToken` | The token request is configured by variables named after the prefix (`oauth2` when no prefix is written; `Authorization: oauth2 password keycloak` reads `keycloak_tokenEndpoint` and so on). They come from environment files, `@` variables and `--var`, like any other variable: | Variable | Meaning | | --- | --- | | `oauth2_tokenEndpoint` | The token endpoint's URL (required) | | `oauth2_clientId` | The client's id (required) | | `oauth2_clientSecret` | The client's secret; none for a public client | | `oauth2_scope` | Space-separated scopes | | `oauth2_audience`, `oauth2_resource` | Sent as `audience` and `resource` when set | | `oauth2_username`, `oauth2_password` | The `password` grant's user | | `oauth2_refreshToken` | The `refresh_token` grant's refresh token | | `oauth2_useAuthorizationHeader` | `true` (the default): the client's id and secret go in a `Basic` `Authorization` header; `false`: in the form | | `oauth2_issuer` | `openid` only: the token endpoint is read from `ISSUER/.well-known/openid-configuration` when `oauth2_tokenEndpoint` isn't set | `Authorization: openid ...` is the same, with the OpenID Connect discovery of `oauth2_issuer`. The token is requested once per run for each configuration (the endpoint, the client, the scopes, the user) and requested again, with its refresh token when it has one, shortly before its `expires_in` runs out. The token endpoint is reached like any request: `https://` is verified as `--ca-cert` and `--insecure` say. A token endpoint that refuses fails the request, which isn't sent: ```text FAIL GET http://localhost:8080/pets no OAuth 2 token: the OAuth 2 token endpoint http://localhost:8080/token answered 401 (invalid_client: unknown client) ``` The `authorization_code` (or `code`), `implicit` and `device_code` grants need a browser or a person, and token exchange isn't supported: those requests are skipped with a warning. Tokens, refresh tokens, client secrets, passwords and the credentials of `Authorization` headers are shown as `[redacted]` wherever they would appear: in URLs, errors, assertion messages, script logs, warnings and the reports. --- # Assertions and scripts Source: https://apigenie.pl/docs/reference/cli/test/assertions Part of the reference of [test](https://apigenie.pl/docs/reference/cli/test.md). Its other pages: [Request files](https://apigenie.pl/docs/reference/cli/test/requests.md), [Variables and OAuth 2](https://apigenie.pl/docs/reference/cli/test/variables.md), [Validation](https://apigenie.pl/docs/reference/cli/test/validation.md), [Generated requests](https://apigenie.pl/docs/reference/cli/test/generate.md), [GraphQL requests](https://apigenie.pl/docs/reference/cli/test/graphql.md), [WebSocket and MQTT requests](https://apigenie.pl/docs/reference/cli/test/websocket-mqtt.md), [Kafka requests](https://apigenie.pl/docs/reference/cli/test/kafka.md), [AMQP requests](https://apigenie.pl/docs/reference/cli/test/amqp.md), [gRPC requests](https://apigenie.pl/docs/reference/cli/test/grpc.md), [Importing collections](https://apigenie.pl/docs/reference/cli/test/import.md), [httpYac compatibility](https://apigenie.pl/docs/reference/cli/test/httpyac.md). What a request checks about its response, and the JavaScript that runs before a request is sent and after its response came. ## Assertions A line `?? SUBJECT [ARGUMENT] PREDICATE [VALUE]` checks the response: | Subject | Value | | --- | --- | | `status` | The status | | `header NAME` | The header's value | | `body` | The body; `body PATH` a value of the JSON body (`$.items[0].id`, `items[0].id` or `/items/0/id`) | | `duration` | The time to the response, in milliseconds | | `js EXPRESSION` | The value of a JavaScript expression with the scripts' API | Predicates: `==`, `!=`, `>`, `>=`, `<`, `<=` (numbers when both sides are numbers), `startsWith`, `endsWith`, `includes` (or `contains`), `matches` (a regular expression, `/.../flags` too), `exists`, `isArray`, `isBoolean`, `isNumber`, `isString`, `isTrue` and `isFalse`. A `js` subject without a predicate must be true. Variables are substituted in the argument and the value. ## Scripts `{{` and `}}` on lines of their own enclose an httpYac script: before the request line it runs before the request is sent, after it once the response came. JetBrains handlers work too: `< {% ... %}` before the request line, `> {% ... %}` after it. Scripts run in a sandboxed JavaScript engine (QuickJS) with no file system or network access, five seconds each. Both flavours get the same API: | Name | What it is | | --- | --- | | `response.status`, `response.statusCode` | The status | | `response.headers` | Headers by lower-case name; `headers.valueOf(name)`, `headers.valuesOf(name)` | | `response.body` | The body, parsed when it is JSON; `response.parsedBody`, `response.rawBody` | | `response.contentType.mimeType`, `.charset` | The media type | | `response.duration` | Milliseconds | | `request.method`, `request.url`, `request.headers`, `request.body` | The request as written | | `request.variables.set(name, value)`, `.get(name)` | Variables of this request (pre-request scripts) | | `exports.name = value`, `client.global.set(name, value)` | Variables of the following requests | | `client.global.get(name)`, `request.environment.get(name)` | A variable | | `test(name, fn)`, `client.test(name, fn)` | A named check: it fails when `fn` throws (or its promise rejects) | | `test.status(code)`, `test.header(name, value)`, `test.headerContains(name, text)`, `test.hasResponseBody()`, `test.totalTime(ms)` | httpYac's shortcuts | | `assert(value, message)`, `client.assert(...)`, `assert.equal`, `assert.strictEqual`, `assert.deepStrictEqual`, `assert.notEqual`, `assert.fail` | Throws when the check fails | | `console.log`, `console.warn`, ..., `client.log` | Lines of the request's log (`--verbose`, the reports) | Variables are also local names of scripts when they are identifiers. A script that throws fails its request. Changes an ordinary pre-request script makes to `request` are not sent: set variables instead. Imported files opt into the header-addition API described below. --- # Validation Source: https://apigenie.pl/docs/reference/cli/test/validation Part of the reference of [test](https://apigenie.pl/docs/reference/cli/test.md). Its other pages: [Request files](https://apigenie.pl/docs/reference/cli/test/requests.md), [Variables and OAuth 2](https://apigenie.pl/docs/reference/cli/test/variables.md), [Assertions and scripts](https://apigenie.pl/docs/reference/cli/test/assertions.md), [Generated requests](https://apigenie.pl/docs/reference/cli/test/generate.md), [GraphQL requests](https://apigenie.pl/docs/reference/cli/test/graphql.md), [WebSocket and MQTT requests](https://apigenie.pl/docs/reference/cli/test/websocket-mqtt.md), [Kafka requests](https://apigenie.pl/docs/reference/cli/test/kafka.md), [AMQP requests](https://apigenie.pl/docs/reference/cli/test/amqp.md), [gRPC requests](https://apigenie.pl/docs/reference/cli/test/grpc.md), [Importing collections](https://apigenie.pl/docs/reference/cli/test/import.md), [httpYac compatibility](https://apigenie.pl/docs/reference/cli/test/httpyac.md). With `--spec`, every request, response and message is checked against the document with the checks of the [validating proxy](/docs/reference/server): an OpenAPI or Swagger 2.0 document for HTTP requests, a GraphQL schema for GraphQL requests, a `.proto` file for `GRPC` requests, and an AsyncAPI document for WebSocket, MQTT, Kafka and AMQP requests and the requests of its HTTP channels. With `--spec`, each request is bound to an operation by its method and path, as the validating proxy does, then checked: parameters, body, security (credentials must be present), and the response's status, media type, headers and body. The checks, their severities and `--severity` are those of [contract testing](/docs/reference/server/contract-testing). XML request and response bodies are mapped by the schema's `xml` objects and checked like JSON ones (see [XML bodies](/docs/reference/server/validation#xml-bodies)). The coverage counts each operation, its request body and each declared response. A request sent with an [OAuth 2](/docs/reference/cli/test/variables#oauth-2) token is also checked against the operation's security requirements (or the document's), as warnings by default: | Check | Default | Meaning | | --- | --- | --- | | `request.authorization.oauth2-scheme` | `warn` | The operation has no `oauth2` or `openIdConnect` scheme (or no security at all) | | `request.authorization.oauth2-scope` | `warn` | A scope of `oauth2_scope` isn't declared for the operation, or no requirement has all its scopes in `oauth2_scope` | When several OAuth 2 schemes apply, the one whose flow's `tokenUrl` is the token endpoint is used. Without `oauth2_scope` the scopes aren't checked. A Swagger 2.0 specification is converted to OpenAPI 3.2 in memory, as `apigenie-server` does (see [Swagger 2.0 documents](/docs/reference/server#swagger-20-documents)); no file is written. What the conversion can only approximate is told once before the requests are sent, as `SPEC:LINE: info: POINTER: MESSAGE` lines on the standard error (`{"event":"info",...}` with `--formatter json`), and the report's operation pointers point into the Swagger file. With a GraphQL schema as `--spec` (`.graphql`, `.graphqls` or `.gql`), the GraphQL requests are checked by the [GraphQL validating proxy](/docs/reference/server/graphql#contract-testing-of-a-graphql-api)'s checks. The operation is validated against the schema before it is sent: an invalid one (a syntax error, an unknown field or argument, an unknown `operationName`, variables of the wrong type) fails the request, which isn't sent, with the errors the server would give (`invalid request: Cannot query field "nope" on type "Book".`), and the run goes on. The response is checked against the request's selection set: the shape of `data` and `errors`, the type of each value, `null` in non-null fields that no error's `path` explains (`null-in-non-null`), `__typename` of abstract types, and errors of operations the schema allows (`response.schema-drift`). Each event of a subscription is checked the same way, at `next[0]`, `next[1]`, ... (`next[1]/data/storyAdded/title: Story.title is an Int`). Deprecated fields selected are notes (`request.field.deprecated`). Requests that aren't GraphQL requests aren't checked. An answer with `errors` next to `data` is valid GraphQL: the operation ran, but fields failed. Each of those errors is a warning (`response.field-error`), so a server that answers every field with an error doesn't pass unnoticed. `--fail-on warnings` fails such requests, and `--severity response.field-error=error` makes them errors. The coverage counts the fields of the schema's types that requests selected, whether or not the answers had them, and each root field; `--min-coverage` is the share of fields. ```text PASS GRAPHQL http://localhost:4000/graphql -> 200 (7 ms) GetBook FAIL GRAPHQL http://localhost:4000/graphql Broken invalid request: Cannot query field "nope" on type "Book". Requests: 1 passed, 1 failed, 0 skipped Contract: 2 requests (0 to other paths), 1 errors, 0 warnings Coverage: 40.0% of 15 fields, 1 of 5 root fields not tested: Query.books, Query.node, Mutation.addBook, Mutation.deleteBook ``` With an AsyncAPI 3.x `--spec`, WS and MQTT requests are checked against the document's channels. The channel of a `WS` request is the one served at its URL's path; that of an `MQTT` request is the one of the topic it publishes to (or of its first subscription without wildcards), and each message received is matched by its own topic. `# @channel` names the channel when its address can't be matched (`address: null`, wildcard filters), `# @operation` checks the messages sent as that operation, and `# @operation off` checks nothing. A path or topic of no channel is a note, and its messages aren't checked. The messages sent are the client's: they are checked against the channel's `receive` operations. The messages received are the application's: they are checked against its `send` operations or, when they answer a request, against the reply's messages. When a message sent matched an operation with a `reply`, the first later message on the reply's channel that is one of the reply's messages is its reply: | Check | Default | Meaning | | --- | --- | --- | | `message.reply.missing` | `warn` | No reply came while the request waited | | `message.reply.uncorrelated` | `error` | The reply's `correlationId` (in the payload, or in a header over MQTT 5) isn't the request's, or is missing; over MQTT 5, the reply doesn't repeat the request's Correlation Data | | `message.properties.invalid` | `error` | MQTT 5: a message's properties don't match its MQTT bindings (see [MQTT 5 properties](/docs/reference/cli/test/websocket-mqtt#mqtt-5-properties)) | Violations are located in the message: `sent[0]/message/carrier`, `received[1]/message/requestId`, `sent[0]/message/property.contentType`. Over MQTT 5 a message's user properties are its headers: a `correlationId` or a reply address in `$message.header#/...` is read from them, and they are checked against the message's `headers` (`message.headers.invalid`). MQTT 3.1.1 has no message headers: such a `correlationId` or reply address can't be checked, and the request gets a note saying so. WS and MQTT requests aren't checked against an OpenAPI document. The coverage counts each message of each operation, those of HTTP channels included, as the [AsyncAPI validating proxy](/docs/reference/server/asyncapi#contract-testing-of-a-websocket-api) does. ## Requests of HTTP channels HTTP requests are checked against the AsyncAPI document's HTTP channels (the channels of `http` and `https` servers) with the checks of the [validating proxy](/docs/reference/server/asyncapi#contract-testing-of-http-channels), so both report the same violations: - The channel and operation are found by the request's path (under a server's `pathname` or not) and method: a `receive` operation's method is its HTTP binding's (`POST` by default); a `send` operation is asked for with `GET`, as the mock serves it. `# @operation` names the operation instead, whatever the method; a path that isn't its channel's is an error. - A `receive` operation's request: the body against the operation's messages (`body/...`), the query against the HTTP binding's `query` schema, and the header fields against the message's `headers` and its HTTP binding's `headers` (its traits' too). Its 2XX response: the body and header fields against the reply's messages (`response/...`). - A `send` operation's 2XX response with a body: against the operation's messages. Its header fields aren't checked: they are those of the webhook the application sends, which doesn't pass `apigenie test`. - Responses of other statuses, and the reply's `statusCode` binding, aren't checked. | Check | Default | Meaning | | --- | --- | --- | | `operation.query.invalid` | `error` | The query doesn't match the HTTP binding's `query` (`query.dryRun`) | | `message.headers.invalid` | `error` | The header fields the message's header schemas name don't match them (`header.X-Batch-Size`) | Query parameters and header fields are read as the type their schema says (`integer`, `number`, `boolean`, an `array` from repeated parameters); header fields the schemas don't name are left out. A path of no HTTP channel, or a method its channel doesn't take, is a note, and the request isn't checked. ```http ### A carrier's status batch POST {{http}}/http/carriers/dhl/events?dryRun=true Content-Type: application/json {"events":[{"trackingNumber":"CE1234567890","statusCode":"DLV","occurredAt":"2026-10-08T10:00:00Z"}]} ### The webhooks, asked for as the mock serves send operations GET {{http}}/http/ ``` --- # Generated requests Source: https://apigenie.pl/docs/reference/cli/test/generate Part of the reference of [test](https://apigenie.pl/docs/reference/cli/test.md). Its other pages: [Request files](https://apigenie.pl/docs/reference/cli/test/requests.md), [Variables and OAuth 2](https://apigenie.pl/docs/reference/cli/test/variables.md), [Assertions and scripts](https://apigenie.pl/docs/reference/cli/test/assertions.md), [Validation](https://apigenie.pl/docs/reference/cli/test/validation.md), [GraphQL requests](https://apigenie.pl/docs/reference/cli/test/graphql.md), [WebSocket and MQTT requests](https://apigenie.pl/docs/reference/cli/test/websocket-mqtt.md), [Kafka requests](https://apigenie.pl/docs/reference/cli/test/kafka.md), [AMQP requests](https://apigenie.pl/docs/reference/cli/test/amqp.md), [gRPC requests](https://apigenie.pl/docs/reference/cli/test/grpc.md), [Importing collections](https://apigenie.pl/docs/reference/cli/test/import.md), [httpYac compatibility](https://apigenie.pl/docs/reference/cli/test/httpyac.md). `--generate` sends one request per operation of `--spec`, checked as that operation: path parameters, required query, header and cookie parameters, and a body of the first media type (JSON first), each from the document's examples or generated from its schemas (`readOnly` properties left out). An XML media type gets an XML body, written as the schema's `xml` objects describe it. The URL is `--base-url` (or the document's first server) followed by the operation's path. Request files and `--generate` can be combined. With an AsyncAPI document, `--generate` sends one region per WebSocket or MQTT channel, bound with `# @channel` (and `# @operation` when the channel has one receive operation): WebSocket channels at `--base-url` (`ws://host:port`) followed by the channel's address, MQTT channels at `--mqtt-url`, publishing to the address and subscribing to it when the application sends there. Parameters of the address take their default, first enum value or example. The messages are those of the channel's receive operations, from their examples or generated from their schemas; MQTT regions get the `# @property` lines of the first one's bindings and headers (correlation data and response topics generated from their schemas, user properties from the first example's headers or generated); `# @expect` is the number of replies, plus one when the application sends on the channel. HTTP channels get one request per operation, bound with `# @operation`, at `--base-url` (a `ws://` URL is taken as `http://`) followed by the channel's address: a `receive` operation's with its HTTP binding's method and its first message (an example, else generated) as the body, a `send` operation's a `GET`. Channels without an address are left out with a warning, as are the channels of a protocol whose URL wasn't given. Kafka channels get one `KAFKA` region per operation at `--kafka-url`, bound with `# @operation`. A `receive` operation's region produces its first message (an example, else generated) to the channel's topic, with a key made from the message's Kafka binding and `# @property` headers from its headers; it reads the reply's topic for one record (`# @expect 1`) when the operation has a reply, and ends once the record is produced otherwise. A `send` operation's region only reads the topic, for one record the application produces. AMQP channels get one `AMQP` region per operation at `--amqp-url`, bound with `# @operation`. A `receive` operation's region publishes its first message to the channel's exchange and routing key (a queue channel's queue through the default exchange) with the properties its bindings say and its headers; it reads the reply's channel, its queue or a queue bound to its exchange, when the operation has a reply. A `send` operation's region reads the channel for one message the application publishes. With a `.proto` file, `--generate` sends one `GRPC` request per method of its services (the built-in reflection and health services aside) to `--base-url`, which is then required and is `HOST:PORT`, `grpc://HOST:PORT` or `grpcs://HOST:PORT` (TLS). The message is generated from the input type as the mock generates answers (`{}` for `google.protobuf.Empty`): REQUIRED fields set, `OUTPUT_ONLY` fields left out. Client- and bidi-streaming methods get a stream of two generated messages. With a GraphQL schema, `--generate` sends one `GRAPHQL` request per field of `Query`, `Mutation` and `Subscription` (deprecated fields left out), named after the field (`Query.book`) and bound to its operation (`QueryBook`). A subscription goes over graphql-ws with `# @expect 1`: the first event is enough. Required arguments get values made up from their types as `apigenie-server` makes up values (the scalar's or the argument's name: a UUID for `ID`, an email for `email`, a date for `DateTime`, an enum value that isn't deprecated, an input object with its required fields); optional ones are left out. The selection set has the leaf fields without required arguments, objects two levels down, and `__typename` with a fragment per type of an interface or a union. `--base-url` is required: it is the endpoint, with `/graphql` added when it has no path. ```graphql mutation MutationAddBook { addBook(input: {title: "Twenty Years After", genre: POETRY}) { id title genre pages author { id name email } } } ``` --- # GraphQL requests Source: https://apigenie.pl/docs/reference/cli/test/graphql Part of the reference of [test](https://apigenie.pl/docs/reference/cli/test.md). Its other pages: [Request files](https://apigenie.pl/docs/reference/cli/test/requests.md), [Variables and OAuth 2](https://apigenie.pl/docs/reference/cli/test/variables.md), [Assertions and scripts](https://apigenie.pl/docs/reference/cli/test/assertions.md), [Validation](https://apigenie.pl/docs/reference/cli/test/validation.md), [Generated requests](https://apigenie.pl/docs/reference/cli/test/generate.md), [WebSocket and MQTT requests](https://apigenie.pl/docs/reference/cli/test/websocket-mqtt.md), [Kafka requests](https://apigenie.pl/docs/reference/cli/test/kafka.md), [AMQP requests](https://apigenie.pl/docs/reference/cli/test/amqp.md), [gRPC requests](https://apigenie.pl/docs/reference/cli/test/grpc.md), [Importing collections](https://apigenie.pl/docs/reference/cli/test/import.md), [httpYac compatibility](https://apigenie.pl/docs/reference/cli/test/httpyac.md). A `GRAPHQL` request has the GraphQL document as its body and, after a blank line, its variables as a JSON object, as in httpYac and the JetBrains HTTP client. It is sent as a `POST` of `{"query", "variables", "operationName"}` with `Content-Type: application/json`; `# @operation` gives the `operationName`. The query can also come from a file (`< ./book.graphql`), without inline variables then. ```http # @operation GetBook GRAPHQL {{host}}/graphql query GetBook($id: ID!) { book(id: $id) { title author { name } } } { "id": "1" } ``` A `POST` whose body starts with `query`, `mutation`, `subscription` or `fragment` is sent the same way, when it has no `Content-Type` or a JSON or `application/graphql` one; with another `Content-Type` (`text/plain`) it is sent as written. A `POST` of a JSON body that has a `query` (or a batch of them) and a `GET` with a `query` parameter are GraphQL requests as they are. Without `--spec`, GraphQL requests are only sent and asserted on. ## Subscriptions A `GRAPHQL` request (or a `POST` of a query) whose operation is a `subscription` goes over WebSocket with the graphql-ws protocol (the `graphql-transport-ws` subprotocol of Apollo Client, urql and GraphiQL). The URL's `http://` becomes `ws://` and `https://` becomes `wss://`; `ws://` and `wss://` URLs are taken as written. The headers go with the handshake and, as an object, as the payload of `connection_init`, where servers look for credentials. The events are the response, as for a [`WS` region](/docs/reference/cli/test/websocket-mqtt): - The body is the JSON array of the events (`{"data": ...}` each). - The status is 101. - Scripts get `response.messages`. The subscription ends when the server completes it, after `# @expect` events, or when `# @timeout` (`--message-timeout`, 5000 ms) has passed; then the client completes it. An `error` message from the server fails the request with its errors. ```http # @expect 3 GRAPHQL {{host}}/graphql Authorization: Bearer {{token}} subscription OnStory($topic: String!) { storyAdded(topic: $topic) { id title } } { "topic": "space" } ?? body $.length == 3 ?? body $[0].data.storyAdded.id == 1 ``` ```text PASS GRAPHQL http://localhost:4000/graphql -> 1 sent, 3 received (162 ms) OnStory ``` A server that doesn't offer `graphql-transport-ws` fails the request (`no connection: the server doesn't speak graphql-transport-ws (graphql-ws)`). The legacy `graphql-ws` subprotocol of `subscriptions-transport-ws` and server-sent events aren't spoken. --- # WebSocket and MQTT requests Source: https://apigenie.pl/docs/reference/cli/test/websocket-mqtt Part of the reference of [test](https://apigenie.pl/docs/reference/cli/test.md). Its other pages: [Request files](https://apigenie.pl/docs/reference/cli/test/requests.md), [Variables and OAuth 2](https://apigenie.pl/docs/reference/cli/test/variables.md), [Assertions and scripts](https://apigenie.pl/docs/reference/cli/test/assertions.md), [Validation](https://apigenie.pl/docs/reference/cli/test/validation.md), [Generated requests](https://apigenie.pl/docs/reference/cli/test/generate.md), [GraphQL requests](https://apigenie.pl/docs/reference/cli/test/graphql.md), [Kafka requests](https://apigenie.pl/docs/reference/cli/test/kafka.md), [AMQP requests](https://apigenie.pl/docs/reference/cli/test/amqp.md), [gRPC requests](https://apigenie.pl/docs/reference/cli/test/grpc.md), [Importing collections](https://apigenie.pl/docs/reference/cli/test/import.md), [httpYac compatibility](https://apigenie.pl/docs/reference/cli/test/httpyac.md). A `WS` (or `WEBSOCKET`) region connects to a `ws://` or `wss://` URL, its headers going with the handshake; an `MQTT` region connects to an `mqtt://host:port` broker, or `mqtts://host:port` (also `ssl://`) over TLS (MQTT 5, or 3.1.1 when the broker refuses it). Without a port, `wss://` uses 443, `mqtt://` 1883 and `mqtts://` 8883. Over TLS the certificate is checked as for `https://`: `--ca-cert` and `--insecure` apply. The body is the message to send; lines `===` separate several messages, and `=== wait-for-server` waits for a message of the server before sending the next one, as in httpYac. Then the region waits for the server's messages until it has `# @expect` of them or `# @timeout` (`--message-timeout`, 5000 ms) has passed. The messages received are the response: its body is their JSON array, each message parsed when it is JSON. ```http ### Request a pickup: the reply carries the request's id # @expect 1 WS ws://localhost:4010/pickups {"type":"pickup.request","requestId":"6f1c2b9e-7f8a-4c35-9a51-2d1e8b7f0c11","carrier":"dhl", ...} ?? body $[0].type == pickup.confirmed ?? body $[0].requestId == 6f1c2b9e-7f8a-4c35-9a51-2d1e8b7f0c11 ### Report a courier's position # @expect 0 # @property content-type application/json # @property payload-format-indicator utf-8 MQTT mqtt://localhost:1883 publish: couriers/cou_4821/position qos: 1 {"courierId":"cou_4821","at":"2026-10-06T07:41:02Z","position":{"type":"Point","coordinates":[21.0067,52.2319]}} ### Receive a job offer # @channel courierJobOffers # @expect 1 MQTT mqtt://localhost:1883 subscribe: couriers/+/offers ?? body $.length == 1 ``` ```text PASS WS ws://localhost:4010/pickups -> 1 sent, 1 received (12 ms) requestPickup PASS MQTT mqtt://localhost:1883 -> 1 sent, 0 received (3 ms) receiveCourierPositions PASS MQTT mqtt://localhost:1883 -> 0 sent, 1 received (6 ms) offerPickupJob ``` The headers of an `MQTT` region are its settings: | Header | Meaning | | --- | --- | | `topic` | The topic messages are published to, also subscribed to (unless `subscribe` is given) | | `publish` | The topic messages are published to | | `subscribe` | The topic filters subscribed to before publishing, comma-separated (`couriers/+/offers, hubs/#`) | | `qos` | `0` (the default), `1` or `2`, for publishing and subscribing | | `retain` | `true` to publish retained messages | | `clientId`, `keepAlive`, `clean` | The connection's client id (a random one by default), keep-alive in seconds (60) and clean session (`true`) | | `username`, `password` | The CONNECT's user name and password; without them, `APIGENIE_MQTT_USERNAME` and `APIGENIE_MQTT_PASSWORD` | | `version` | `auto` (the default: MQTT 5, else 3.1.1 when the broker refuses it), `5` or `3.1.1` | The client's own messages coming back on a topic it subscribed to are left out. Retained messages of a subscription count as received. Settings are substituted like any header, so a password can stay out of the file: `password: {{$processEnv BROKER_PASSWORD}}`, or a variable of an environment file. A setting the region doesn't give comes from `APIGENIE_MQTT_USERNAME` or `APIGENIE_MQTT_PASSWORD`. MQTT 5 sends a password without a user name; MQTT 3.1.1 sends one only with a user name, so with `version: 3.1.1` a password alone is a warning and isn't sent. A broker that refuses them fails the request with `the broker refused the connection (reason code 0x86) (bad user name or password)` (MQTT 5), or `(return code 4) (bad user name or password)` (MQTT 3.1.1). Credentials never show in the output or the reports: wherever they would, they read `[redacted]`, and a URL's `user:password@` is shown as `***@`. The user name and password of the URL itself aren't sent. | In checks and scripts | Value | | --- | --- | | `?? body $.length == 2` | How many messages came (`.length` also gives the size of any array or string) | | `?? body $[0].type == pickup.confirmed` | A value of the first message | | `?? status == 101` | The handshake's status (WS); the CONNACK's return code, `0` (MQTT) | | `response.messages[i]` | In scripts: `topic` (the topic, or the WebSocket's path), `body` (parsed when JSON), `rawBody`, `binary` | ## MQTT 5 properties An `MQTT` region connects with MQTT 5. A broker that refuses it (reason code 0x84, a 3.1.1 broker's return code 1, or a connection closed before the CONNACK) gets a second connection with MQTT 3.1.1, and the request notes `the broker refused MQTT 5`. `version: 5` doesn't fall back; `version: 3.1.1` doesn't try MQTT 5. `# @property` gives the properties of every message the region publishes: | Directive | Property | | --- | --- | | `# @property content-type application/json` | Content Type | | `# @property response-topic clients/{{client}}/quotes` | Response Topic (no wildcards); the region also subscribes to it | | `# @property correlation-data {{$uuid}}` | Correlation Data | | `# @property payload-format-indicator utf-8` | Payload Format Indicator: `utf-8` or `1`, `bytes` or `0` | | `# @property message-expiry-interval 60` | Message Expiry Interval, in seconds | | `# @property user replyTo dispatch/d-1/replies` | A user property (repeat the line for more; the value may be empty) | Values are substituted like headers. An unknown property, a missing value or a bad value is a warning, and that property isn't sent. Over MQTT 3.1.1 none is sent, and the request notes it. Over MQTT 5 the messages sent and received are checked with their properties, against the message's and the operation's MQTT bindings (0.2.0), as `message.properties.invalid` (`error`): | Binding | Checked | | --- | --- | | message `payloadFormatIndicator` | The Payload Format Indicator is the same (absent counts as 0) | | message `contentType` | The Content Type is the same, ignoring case | | message `correlationData` | Correlation Data is present and matches the schema | | message `responseTopic` | A Response Topic is present, the string given or matching the schema | | operation `messageExpiryInterval` | A Message Expiry Interval is present and no longer | A request whose reply address is in a header (`$message.header#/replyTo`) is answered on the topic in that user property; one whose reply channel has `address: null` is answered on its Response Topic. Either way the region waits for the reply on that topic, checks it as the reply, and compares its correlation id (header or payload) and, when a binding declares `correlationData`, its Correlation Data with the request's. ```http ### Ask for a quote: the reply comes to the Response Topic # @expect 1 # @property content-type application/json # @property response-topic clients/7/quotes # @property correlation-data {{$uuid}} # @property user correlationId c-42 MQTT mqtt://localhost:1883 publish: quotes qos: 1 {"parcel":"P1"} ?? body $[0].price exists ``` A message whose bindings state properties counts in the coverage as checked (MQTT 5) or unchecked (MQTT 3.1.1): `summary.properties` and `operations[].properties` in the report, `MQTT 5 properties: checked on 2 messages, not on 0 (MQTT 3.1.1)` in the summary. --- # Kafka requests Source: https://apigenie.pl/docs/reference/cli/test/kafka Part of the reference of [test](https://apigenie.pl/docs/reference/cli/test.md). Its other pages: [Request files](https://apigenie.pl/docs/reference/cli/test/requests.md), [Variables and OAuth 2](https://apigenie.pl/docs/reference/cli/test/variables.md), [Assertions and scripts](https://apigenie.pl/docs/reference/cli/test/assertions.md), [Validation](https://apigenie.pl/docs/reference/cli/test/validation.md), [Generated requests](https://apigenie.pl/docs/reference/cli/test/generate.md), [GraphQL requests](https://apigenie.pl/docs/reference/cli/test/graphql.md), [WebSocket and MQTT requests](https://apigenie.pl/docs/reference/cli/test/websocket-mqtt.md), [AMQP requests](https://apigenie.pl/docs/reference/cli/test/amqp.md), [gRPC requests](https://apigenie.pl/docs/reference/cli/test/grpc.md), [Importing collections](https://apigenie.pl/docs/reference/cli/test/import.md), [httpYac compatibility](https://apigenie.pl/docs/reference/cli/test/httpyac.md). A `KAFKA` region produces records to a Kafka cluster and reads what comes on its topics (ADR-170). The URL names a broker, `kafka://host:port` (port 9092 by default) or `kafkas://host:port` (9093, over TLS, verified as `https://` with `--ca-cert`, `--insecure` and `--client-cert`); several bootstrap servers are separated by commas. The cluster needs Kafka 2.3 or later. A cluster that creates topics on first use creates the region's topic, as Kafka's producers ask it to. ```http ### Place an order: the confirmation carries its correlation id # @expect 1 # @timeout 10000 # @property correlationId {{$uuid}} KAFKA kafka://localhost:9092 topic: shop.orders subscribe: shop.confirmations key: cust-1 {"sku": "A-1"} ?? body $[0].accepted == true ### Await a shipment the application produces # @channel shipments # @expect 1 KAFKA kafka://localhost:9092 subscribe: shop.shipments ``` | Header | Meaning | | --- | --- | | `topic` | The topic the records are produced to; also read, unless `subscribe` is given | | `subscribe` | The topics read, separated by commas | | `key` | The records' key | | `partition` | The records' partition; without it, the key's (murmur2, as Kafka's producers choose), else the next in turn | | `username`, `password` | SASL PLAIN credentials; without them `APIGENIE_KAFKA_USERNAME` and `APIGENIE_KAFKA_PASSWORD`. They are `[redacted]` in the output and reports | `# @property NAME VALUE` lines are the records' headers, the name as written (`# @property user NAME VALUE` too). The body's parts (`===`) are the records; `=== wait-for-server` waits for a record before the next part. Before the first record is produced, the region takes the latest offsets of the topics it reads, so a reply can't come too early; then it reads until it has `# @expect` records or `# @timeout` has passed. Its own records are left out. The records read are the response, as an MQTT region's messages are. With an AsyncAPI `--spec`, what is produced is checked against the receive operations of the topic's channel and what is read against its send operations, or as the reply to a request: the value, the headers against the message's `headers`, the key against the message's Kafka binding `key` (`message.key.invalid`) and the partition against the channel's Kafka binding `partitions` (`message.partition.invalid`). A channel's topic is its Kafka binding's `topic`, else its address. A reply is paired with its request by the correlation id in a header (`$message.header#/...`) or the payload, and a reply address in a header is followed, as for MQTT 5. Compressed records aren't read; they are reported as errors. --- # AMQP requests Source: https://apigenie.pl/docs/reference/cli/test/amqp Part of the reference of [test](https://apigenie.pl/docs/reference/cli/test.md). Its other pages: [Request files](https://apigenie.pl/docs/reference/cli/test/requests.md), [Variables and OAuth 2](https://apigenie.pl/docs/reference/cli/test/variables.md), [Assertions and scripts](https://apigenie.pl/docs/reference/cli/test/assertions.md), [Validation](https://apigenie.pl/docs/reference/cli/test/validation.md), [Generated requests](https://apigenie.pl/docs/reference/cli/test/generate.md), [GraphQL requests](https://apigenie.pl/docs/reference/cli/test/graphql.md), [WebSocket and MQTT requests](https://apigenie.pl/docs/reference/cli/test/websocket-mqtt.md), [Kafka requests](https://apigenie.pl/docs/reference/cli/test/kafka.md), [gRPC requests](https://apigenie.pl/docs/reference/cli/test/grpc.md), [Importing collections](https://apigenie.pl/docs/reference/cli/test/import.md), [httpYac compatibility](https://apigenie.pl/docs/reference/cli/test/httpyac.md). An `AMQP` region publishes to an AMQP 0-9-1 broker and reads what comes to its queues (ADR-171). The URL is `amqp://[user:password@]host[:port][/vhost]` (port 5672, the virtual host percent-encoded: `/%2Fcarpet-express`), or `amqps://` (5671, over TLS, verified as `https://`). ```http ### File a declaration: the decision comes to the decisions queue # @expect 1 # @property delivery-mode 2 # @property correlationId {{$uuid}} AMQP amqp://localhost:5672/%2Fcarpet-express exchange: customs routing-key: customs.GB.filing subscribe: customs.decisions {"destinationCountry": "GB"} ### Await what the application publishes to the customs exchange # @expect 1 AMQP amqp://localhost:5672/%2Fcarpet-express bind: customs customs.*.filing ``` | Header | Meaning | | --- | --- | | `exchange` | The exchange the messages go to; without it, the default exchange (routing keys are queue names) | | `routing-key` | The messages' routing key | | `subscribe` | Queues consumed, separated by commas; a queue's messages go to the region, not to the application | | `bind` | `EXCHANGE KEY`: a queue of the region's own, bound to the exchange with that binding key (none for fanout); can be repeated | | `mandatory` | `false`: a message no queue takes isn't an error (`true` by default) | | `username`, `password` | PLAIN credentials; without them the URL's, then `APIGENIE_AMQP_USERNAME` and `APIGENIE_AMQP_PASSWORD`, then `guest`. They are `[redacted]` in the output and reports | `# @property NAME VALUE` lines with the name of a basic property set it: `content-type`, `content-encoding`, `delivery-mode`, `priority`, `correlation-id`, `reply-to`, `expiration` (milliseconds), `message-id`, `timestamp` (seconds since the epoch, or `now`), `type`, `user-id` and `app-id`. Other names, and `# @property user NAME VALUE`, are application headers. The region consumes its queues before it publishes, then reads until it has `# @expect` messages or `# @timeout` has passed; its own messages coming back are left out. RabbitMQ's direct reply-to works: `subscribe: amq.rabbitmq.reply-to` with `# @property reply-to amq.rabbitmq.reply-to`. With an AsyncAPI `--spec`, the channel is the one of the exchange and routing key (a queue channel's for the default exchange and its queue's name), and a message read from a queue is that queue's channel's. What is published is checked against the channel's receive operations and what is read against its send operations or as a reply: the body, the headers against the message's `headers`, and the properties against the AMQP bindings (`message.properties.invalid`). A reply is paired with its request by its correlation id in a header or a property: properties are seen by their AMQP and AsyncAPI names (`correlation_id` and `correlationId`, `reply_to` and `replyTo`), so `$message.header#/correlationId` finds either. --- # gRPC requests Source: https://apigenie.pl/docs/reference/cli/test/grpc Part of the reference of [test](https://apigenie.pl/docs/reference/cli/test.md). Its other pages: [Request files](https://apigenie.pl/docs/reference/cli/test/requests.md), [Variables and OAuth 2](https://apigenie.pl/docs/reference/cli/test/variables.md), [Assertions and scripts](https://apigenie.pl/docs/reference/cli/test/assertions.md), [Validation](https://apigenie.pl/docs/reference/cli/test/validation.md), [Generated requests](https://apigenie.pl/docs/reference/cli/test/generate.md), [GraphQL requests](https://apigenie.pl/docs/reference/cli/test/graphql.md), [WebSocket and MQTT requests](https://apigenie.pl/docs/reference/cli/test/websocket-mqtt.md), [Kafka requests](https://apigenie.pl/docs/reference/cli/test/kafka.md), [AMQP requests](https://apigenie.pl/docs/reference/cli/test/amqp.md), [Importing collections](https://apigenie.pl/docs/reference/cli/test/import.md), [httpYac compatibility](https://apigenie.pl/docs/reference/cli/test/httpyac.md). `GRPC` requests call the methods of the services of the `.proto` file given as `--spec`: the request line names the method, the headers are the call's metadata, the body is the message as JSON, and the assertions check the status, the response metadata and the response message. A request is written as httpYac writes it: ```http @host = localhost:50051 ### say hello GRPC {{host}}/acme.greeter.v1.Greeter/SayHello x-tenant: acme {"name": "Ann"} ?? status == 0 ?? body message == Hello Ann ?? header grpc-status == 0 ``` ```sh apigenie test --spec greeter.proto greeter.http ``` ```text PASS GRPC localhost:50051/acme.greeter.v1.Greeter/SayHello -> OK (6 ms) acme.greeter.v1.Greeter/SayHello Requests: 1 passed, 0 failed, 0 skipped Contract: 1 calls (0 undocumented), 0 errors, 0 warnings Coverage: 33.3% of 3 methods not tested: acme.greeter.v1.Greeter/SayHelloToAll, acme.greeter.v1.Greeter/Ping ``` - **The request line** is `GRPC HOST:PORT/package.Service/Method`, or a URL with `grpc://`, or with `grpcs://` for TLS. The method must be one of the file's: another is a failed request. - **Headers** are the call's metadata (names in lower case); `-bin` values are sent as written, base64-encoded. - **The body** is the request message in its proto3 JSON form (field names or their JSON names, 64-bit integers as numbers or strings, enum names, base64 bytes, the well-known types in their own forms); no body is `{}`. A body that isn't a valid message fails the request before anything is sent, naming the field: `the body isn't a valid acme.greeter.v1.HelloRequest: name: expected a string`. - **The `.proto` file is `--spec`**, with its imports looked up in `--proto-path` directories, then next to the file, then among the standard files (`google/protobuf/*`, `google/api/*`, `google/rpc/*`), as `apigenie-server --proto-path` does. httpYac's `proto < ./file.proto` line is read and ignored with a warning. - **Assertions and scripts** see the call as a response: `status` is the gRPC status code (`0` for OK, `5` for NOT_FOUND) and the status text its name, the headers are the response metadata and the trailers (`grpc-status`, `grpc-message` among them), and the body is the response message as JSON. A server-streaming or bidi-streaming call's body is a JSON array of its messages. - **Every kind of method.** Client- and bidi-streaming methods take a stream of messages, written as for [WS regions](/docs/reference/cli/test/websocket-mqtt): lines `===` separate them, and `=== wait-for-server` waits for a message of the server before the next one is sent (bidi methods only). After the last message the call is half-closed, and its end (the trailers) is awaited for `# @timeout` (`--message-timeout`, 5000 ms); a call that doesn't end in time is cancelled and fails. Unary and server-streaming methods take one message: more fail the request. - **HTTP/2**, cleartext with prior knowledge (h2c), or over TLS with ALPN `h2` for `grpcs://` (and `https://`) URLs, verified as `https://` requests are (`--ca-cert`, `--insecure`). `--timeout` bounds the connection and each wait for the server, and is sent as `grpc-timeout`. ```http ### a client stream: the messages, then one answer GRPC {{host}}/acme.chat.v1.Chat/Upload {"author": "Ann", "text": "hi"} === {"author": "Bob", "text": "hello"} ?? body lines == 2 ### a bidi stream that waits for each answer before it goes on GRPC {{host}}/acme.chat.v1.Chat/Talk {"author": "Ann", "text": "hi"} === wait-for-server {"author": "Ann", "text": "bye"} ?? body $.length == 2 ?? body $[1].text == re: bye ``` Each call is checked with the checks of [gRPC contract testing](/docs/reference/server/grpc#contract-testing-of-a-grpc-api): the request and response messages against their types (fields marked `[(google.api.field_behavior) = REQUIRED]` included), each message of a stream at `message[0]`, `message[1]`, ..., the status and its `google.rpc` details, the number of messages of a unary or client-streaming call. The coverage counts the file's methods. Without a `.proto` file as `--spec`, `GRPC` requests are skipped; HTTP requests in the same files are sent but not checked. --- # Importing collections Source: https://apigenie.pl/docs/reference/cli/test/import Part of the reference of [test](https://apigenie.pl/docs/reference/cli/test.md). Its other pages: [Request files](https://apigenie.pl/docs/reference/cli/test/requests.md), [Variables and OAuth 2](https://apigenie.pl/docs/reference/cli/test/variables.md), [Assertions and scripts](https://apigenie.pl/docs/reference/cli/test/assertions.md), [Validation](https://apigenie.pl/docs/reference/cli/test/validation.md), [Generated requests](https://apigenie.pl/docs/reference/cli/test/generate.md), [GraphQL requests](https://apigenie.pl/docs/reference/cli/test/graphql.md), [WebSocket and MQTT requests](https://apigenie.pl/docs/reference/cli/test/websocket-mqtt.md), [Kafka requests](https://apigenie.pl/docs/reference/cli/test/kafka.md), [AMQP requests](https://apigenie.pl/docs/reference/cli/test/amqp.md), [gRPC requests](https://apigenie.pl/docs/reference/cli/test/grpc.md), [httpYac compatibility](https://apigenie.pl/docs/reference/cli/test/httpyac.md). `apigenie test import` reads a Postman Collection Format v2.0 or v2.1 JSON export and writes request files that `apigenie test` can run. It uses an independently implemented reader, not Postman's JavaScript or the `postman-collection` SDK. Collection v1 is not supported: export as v2.1 from Postman. ```sh apigenie test import carpet-express.collection.json -o requests \ --environment mock.environment.json --spec carpet-express.openapi.yaml apigenie test requests --env mock --spec carpet-express.openapi.yaml \ --var baseUrl=http://localhost:4010/v2 ``` | Import option | Meaning | | --- | --- | | `COLLECTION` | Collection JSON file to import | | `-o DIR`, `--output DIR` | Required output directory | | `--environment FILE` | An exported environment JSON file; can be repeated | | `--spec SPEC` | Bind matching requests to operation IDs and write saved response examples as an OpenAPI overlay | | `--force` | Replace existing generated files; never delete unrelated files | The collection's root requests go into `.http`. A folder `Shipping` becomes `shipping.http`; its nested folder `Tracking` becomes `shipping/tracking.http`. Every request is a `###` region with a stable `# @name` slug. Collection and inherited folder variables are written as `@name = value` defaults at the top of each file. Slug collisions get deterministic suffixes. Collection and folder auth and pre-request/test scripts are inherited by descendant requests; explicit `noauth` disables inherited authentication. URLs and variables retain `{{name}}` references. Active headers and query parameters, raw, urlencoded, multipart form-data, GraphQL and file bodies are mapped. GraphQL becomes an HTTP POST with a JSON envelope, not the unsupported `GRAPHQL` pseudo-method and not GraphQL-specific contract validation. Available upload files are copied into the output with relative `< ./path` references; missing files are kept as references and reported as warnings. Relative source upload paths are resolved against the collection file's directory. Multipart file references are read as binary data when the request runs. Exported environments become named entries in `http-client.env.json`. Bearer, basic and API-key authentication becomes headers or query parameters with environment-variable references. Literal credentials and known credential defaults are stored only in the generated `http-client.private.env.json` (with the same `$shared` and environment entries), not in `http-client.env.json`, request files, overlays or the import summary; `apigenie test` reads both files. **The private environment file contains secrets: protect it and do not commit it to source control.** The importer cannot discover arbitrary secrets hidden in unrelated application data. OAuth 2 auth with the client credentials or password grant becomes `Authorization: oauth2 client_credentials` (or `password`) and the [OAuth 2 variables](/docs/reference/cli/test/variables#oauth-2): the access token URL, client id, scope, audience and client authentication (`header` or `body`) in `http-client.env.json`, the client secret, user name and password in `http-client.private.env.json`. Each distinct OAuth 2 configuration gets its own prefix (`oauth2`, `oauth2_2`, ...). A token stored in the collection isn't used: a new one is requested. The authorization code, PKCE and implicit grants need a browser: those requests are written disabled, their auth kept as a comment without its secrets, with a warning. Adding the token to the query and header prefixes other than `Bearer` are warnings; the token is sent in the `Authorization` header with the type the token endpoint gives. Imported files follow the ordinary `.http` variable precedence: file defaults override environment values, and `--var` overrides both. This differs from Postman's precedence. For marked files, environment discovery searches parent directories too, so nested request files can find the generated root environment. Script changes are in memory only, not saved back to the environment file. Files are run in the existing explicit-file or sorted-directory order; splitting folders into separate files does not preserve arbitrary cross-folder collection order. With `--spec`, requests that bind by method and path to an operation with an ID get `# @operation `. Saved responses become additive examples in `.overlay.json`; the specification is never edited. Apply the overlay explicitly: ```sh apigenie overlay carpet-express.openapi.yaml \ --overlay requests/carpet-express.overlay.json -o carpet-express.with-examples.yaml ``` Without a specification or a usable binding, examples are preserved as comments. Unresolved bindings or overlay targets produce warnings rather than guessed operation IDs. ## Imported script API Files carrying `# @postman` get a small compatibility shim in QuickJS. Unmarked files do not get a `pm` global. Pre-request blocks go before the request; test blocks go after it. Scripts containing their own standalone `}}` line are JSON-escaped inside the block so that multiline strings and JavaScript tokens remain intact. Simple `pm.test` callbacks that only assert a literal response status become `?? status == N` instead, so they do not require scripting support. | API | Supported subset | | --- | --- | | `pm.test(name, fn)` | Records a named check; a thrown assertion fails it | | `pm.expect(value)` | `to.equal`, `to.eql`, `to.be.true`, `to.be.false`, `to.have.property`, `to.have.status`, `to.include`, `to.be.oneOf`, `to.be.a` | | `pm.response` | `code`, `status`, `json()`, `text()`, case-insensitive `headers.get(name)`, `to.have.status(code)` | | `pm.environment` | `get`, `set`, `unset` | | `pm.collectionVariables` | `get`, `set` | | `pm.variables` | `get`, `set`; request-local changes | | `pm.globals` | `get`, `set` | | `pm.request.headers.add({key, value})` | Adds a header before sending a marked request | This is not the full SDK or Chai. `pm.sendRequest`, `postman.setNextRequest`, `pm.cookies` and `pm.visualizer` cause the **whole affected script block** to be kept as comments, with warnings that name the call and its source line. OAuth 2 auth with a grant that needs a browser is preserved as comments and the request is disabled. The summary lists unsupported features; they are never silently dropped. Other unknown script APIs fail explicitly at runtime. Scripts remain subject to the existing QuickJS time limit and lack of filesystem/network access. Imported `https://` URLs are sent over TLS like any other request (see `--ca-cert` and `--insecure`). Import returns 0 after a successful conversion, including one with reported warnings, 2 for bad command usage, and 3 for input or output failures. Existing generated filenames are refused unless `--force` is supplied. A directory literally named `import` can still be run with `apigenie test -- import`. --- # httpYac compatibility Source: https://apigenie.pl/docs/reference/cli/test/httpyac Part of the reference of [test](https://apigenie.pl/docs/reference/cli/test.md). Its other pages: [Request files](https://apigenie.pl/docs/reference/cli/test/requests.md), [Variables and OAuth 2](https://apigenie.pl/docs/reference/cli/test/variables.md), [Assertions and scripts](https://apigenie.pl/docs/reference/cli/test/assertions.md), [Validation](https://apigenie.pl/docs/reference/cli/test/validation.md), [Generated requests](https://apigenie.pl/docs/reference/cli/test/generate.md), [GraphQL requests](https://apigenie.pl/docs/reference/cli/test/graphql.md), [WebSocket and MQTT requests](https://apigenie.pl/docs/reference/cli/test/websocket-mqtt.md), [Kafka requests](https://apigenie.pl/docs/reference/cli/test/kafka.md), [AMQP requests](https://apigenie.pl/docs/reference/cli/test/amqp.md), [gRPC requests](https://apigenie.pl/docs/reference/cli/test/grpc.md), [Importing collections](https://apigenie.pl/docs/reference/cli/test/import.md). What of the httpYac `.http` format `apigenie test` reads, and what it does with the rest. **Supported** | Feature | Notes | | --- | --- | | `###` regions with titles, `#` and `//` comments | | | `GRPC` requests | Every method of the `.proto` file of `--spec` (streams of messages separated by `===`), over HTTP/2 (cleartext, or TLS for `grpcs://`); `proto <` lines are ignored with a warning | | Request line with or without method and HTTP version, multi-line query (`?`, `&`) | | | Headers, inline bodies, `< file` and `<@ file` bodies | `<@utf8 file`: the encoding is ignored | | `@name = value` variables | Outside of requests (file) or in a request's region | | `{{name}}`, `{{$uuid}}`, `{{$timestamp}}`, `{{$datetime}}`, `{{$randomInt}}`, `{{$processEnv}}`, `{{$dotenv}}` | See [Environments and variables](/docs/reference/cli/test/variables#environments-and-variables) | | `# @name`, `# @ref`, `# @forceRef`, `# @disabled` | Named responses are kept per file | | `{{ }}` scripts before and after the request | `exports`, `test`, `assert`, `console`, `request`, `response` | | JetBrains `< {% %}` and `> {% %}` handlers | `client.global`, `client.test`, `client.assert`, `client.log`, `request.variables` | | `??` assertions | `status`, `header`, `body`, `duration` and `js` subjects | | `WS` and `WEBSOCKET` requests | `ws://` and `wss://`; headers go with the handshake; text messages | | `MQTT` requests | `mqtt://` and `mqtts://`, MQTT 3.1.1; `topic`, `publish`, `subscribe`, `qos`, `retain`, `clientId`, `keepAlive`, `clean`, `username` and `password` headers | | `===` and `=== wait-for-server` between messages | | | `.env`, `.env.NAME`, `http-client.env.json`, `http-client.private.env.json` | `$shared` and the `--env` environment | | `Authorization: Basic user:password` | Encoded before sending | | `Authorization: oauth2` and `openid` with the `client_credentials`, `password` and `refresh_token` grants | See [OAuth 2](/docs/reference/cli/test/variables#oauth-2); `refresh_token` and OpenID Connect discovery are additions of `apigenie test` | | `GRAPHQL` requests, `POST` requests of a query | Variables after a blank line; `# @operation` is the `operationName`; subscriptions over graphql-ws | **Not supported yet** | Feature | What happens | | --- | --- | | Server-sent events (`SSE`), AMQP | Not request lines | | `gql` fragment imports (`# @import ./fragments.gql`) | A warning; the request runs without them | | GraphQL subscriptions over the legacy `graphql-ws` subprotocol or SSE | The request fails: only `graphql-transport-ws` is spoken | | MQTT 5, client certificates | MQTT is 3.1.1; no certificate of the client is sent | | `# @keepStreaming`, binary WebSocket messages sent | A warning; messages are sent as text | | Redirects | Not followed: a 3xx response is checked as it is | | OAuth 2 and OpenID `authorization_code`, `implicit` and `device_code` grants, token exchange, `oauth2_keepAlive`, `oauth2_interceptRequest` | The request is skipped with a warning (the variables are ignored) | | AWS and digest authorization | The request is skipped with a warning | | `# @import`, `# @loop`, `# @sleep`, `# @jwt`, `# @keepStreaming`, other directives | A warning; the request runs | | `xpath` assertions, `sha256`/`md5` predicates | A warning; the assertion is ignored | | Offsets of `$datetime` and `$timestamp`, `$localDatetime` time zones | A warning; the current time in UTC is used | | `{{ expression }}` JavaScript inside a line, global `{{ }}` scripts outside of requests | Not evaluated (the latter with a warning) | | `require()`, npm packages, `client.exit()` in scripts | The script fails | | Response handler files (`> ./handler.js`) | A warning | | Changes a pre-request script makes to `request` | Not sent for ordinary files; marked imports support `pm.request.headers.add` | | `.httpyac.js`, `.httpyac.json`, `httpyac.config.js` | Not read | | Cookie jars | No cookies are kept between requests | --- # Configuration Source: https://apigenie.pl/docs/reference/cli/configuration See also: [Formats](https://apigenie.pl/docs/reference/cli/formats.md), [Specification extensions](https://apigenie.pl/docs/reference/cli/extensions.md), [faker](https://apigenie.pl/docs/reference/cli/faker.md), [Compatibility](https://apigenie.pl/docs/reference/cli/compatibility.md), [apigenie-mcp](https://apigenie.pl/docs/reference/cli/mcp.md). One file, `apigenie.yaml`, holds the settings of `apigenie`, `apigenie-generator`, `apigenie-server` and `apigenie-catalog`: the rules of the linter and the differ, the layout of the formatter, the specifications of the catalog, the options of every code generator and, for `apigenie-server`, the document, the address and the rest of what the server needs. The commands find it in the repository without an option, check it against its JSON Schema before reading it, and run with their defaults without it. ## Structure The file is JSON or YAML, with four top-level keys: | Key | Holds | Read by | | ---------- | ----------------------------------------------------------------------------------------------------------- | --------------------------------------------- | | `version` | The string `'1.0'`, quoted in YAML, where `1.0` is a number. Required. | `apigenie`, `apigenie-generator`, `apigenie-server`, `apigenie-catalog` | | `openapi` | Settings of OpenAPI documents that every command shares: [custom_formats](#openapicustom_formats) | `apigenie`, `apigenie-server`, `apigenie-generator` | | `catalog` | The specifications of the repository and their owners | `apigenie-catalog` | | `commands` | A section per command: `format`, `lint`, `diff`, `mock` and `generate`, the last with a section per generator | the command | ```yaml # yaml-language-server: $schema=https://apigenie.pl/schemas/apigenie-config/latest.json version: '1.0' openapi: custom_formats: - name: x-id type: integer catalog: specs: - name: orders-api path: apis/orders/openapi.yaml owner: team-commerce commands: format: extends: [recommended] lint: extends: [recommended] rules: info-defined: off diff: extends: [recommended] mock: server: port: 4010 generate: server_spring: overlay: - overlays/spring.overlay.yaml ``` The first line names the schema for editors that read it (see [editor support](/docs/reference/cli#editor-support)). `apigenie-server` also reads a file of its own, `apigenie-server.yaml` (or `apigenie-mock.yaml`), with the keys of `commands.mock` at its root next to `version` and `openapi`; see [server configuration](/docs/reference/server/configuration). ## Where the file is found When no `--config` is given, `apigenie`, `apigenie-generator`, `apigenie-server` and `apigenie-catalog` use the first of `apigenie.yaml`, `apigenie.yml`, `apigenie.json`, `.apigenie.yaml`, `.apigenie.yml` and `.apigenie.json` found in the current directory or one of its parents, stopping at the root of the Git repository (the directory holding `.git`). `apigenie-server` looks for `apigenie-server.yaml`, then `apigenie-mock.yaml` (and their variants) in the current directory first. `--config FILE` uses FILE instead of the file found this way: the two are never merged. `--no-config` uses no file at all, so the commands run with their defaults. [Where `apigenie.yaml` is found and how settings merge](/docs/concepts/where-the-configuration-is-found) explains the lookup, the check that precedes every command and the merging, with examples. ## Validation Every file is checked against the JSON Schema of the configuration (draft-7) before any command reads it, whichever command loads it. A setting the schema doesn't know, a value of the wrong type or one outside its allowed values is an error that names the line, the column and the JSON pointer of the value, with a suggestion for a misspelled name: ```text apigenie.yaml:12:7: /commands/lint/rulez: unknown property 'rulez'; did you mean 'rules'? ``` `version` must be the string `'1.0'`: quote it in YAML, where `1.0` is a number. Sections of commands without settings (`bundle`, `convert`, `overlay`, `i18n`, `test`) are errors too; `changelog` uses the `diff` section. [`apigenie config check`](/docs/reference/cli/config) checks a file, and `apigenie config schema` prints the schema for an editor (see [editor support](/docs/reference/cli#editor-support)). ## openapi Settings of OpenAPI documents that every command shares. ### openapi.custom_formats API Genie knows the formats of the [OpenAPI format registry](https://spec.openapis.org/registry/format/). This section declares the formats the documents use beyond it, so that they are accepted as they are: an array of objects with `name`, the format's name, unique in the file, and `type`, the JSON Schema type the format applies to (`string`, `integer`, `number`, `boolean`, `object` or `array`). ```yaml openapi: custom_formats: - {name: currency-code, type: string} # the registry's decimal is a string or a number; here it is always a string - {name: decimal, type: string} ``` A format of the registry listed here takes the type given and is no longer checked. `apigenie-server` uses these formats when it validates requests and responses, and the linters' format rules accept them. The [Formats](/docs/reference/cli/formats) page lists the registry's formats and what API Genie does with each. ## catalog The specifications of the repository's API catalog, for [`apigenie-catalog`](/docs/reference/catalog), which writes it with `apigenie-catalog init`. Every setting is optional: specifications found in the repository but not listed here are still in the catalog, with derived names. ```yaml catalog: exclude: - "**/examples/**" tags: pattern: "{name}-{version}" specs: - name: orders-api path: apis/orders/openapi.yaml owner: team-commerce - name: legacy-billing path: apis/legacy/billing.yaml owner: team-finance lifecycle: deprecated sunset: 2027-03-31 ``` | Setting | Description | | ------- | ----------- | | `exclude` | Glob patterns of files left out of the catalog, relative to the directory of the configuration file: `*` matches within a directory, `**` across directories. Files ignored by git are always left out. | | `tags.pattern` | How [`apigenie-catalog release`](/docs/reference/catalog#apigenie-catalog-release) names the Git tag of a release and `apigenie-catalog versions` finds it, with `{name}` and `{version}` each once. Defaults to `{name}-{version}` (`orders-api-1.4.0`); `{name}/v{version}` gives `orders-api/v1.4.0`. Tags made with another pattern are not releases: after a change, `versions` doesn't list them and `release` doesn't check against them. Since 0.12.0. | | `specs` | One entry per specification file. | | `specs[].path` | Required. The file, relative to the directory of the configuration file, with `/` separators. | | `specs[].name` | The name in the catalog, which stays when the file moves: lower-case letters, digits and dashes. Derived from `info.title`, the Protobuf package or the file name when left out. | | `specs[].owner` | The team or person owning the specification, or `null`. | | `specs[].lifecycle` | `draft` (still being designed), `active` (the default), `deprecated` (consumers should move away; see `sunset`) or `retired`. `apigenie-catalog list` shows it; `apigenie-catalog release` reads only `retired`, which it refuses. Since 0.12.0. | | `specs[].sunset` | The day a deprecated specification goes away, as `YYYY-MM-DD`. Since 0.12.0. | ## commands A section per command, named after it. Every section is optional, and each command reads only its own; the sections of commands without settings (`bundle`, `convert`, `overlay`, `i18n`, `test`) are errors. ### commands.format The settings of the `format` command: the presets of `extends`, and the `openapi`, `swagger`, `asyncapi`, `protobuf` and `graphql` sections that format each kind of file. See [format](/docs/reference/cli/format#configuration). ### commands.lint The settings of the `lint` command: the rulesets and rules of the OpenAPI linter, and the `swagger`, `asyncapi`, `protobuf` and `graphql` sections of the other linters. See [lint](/docs/reference/cli/lint#configuration). ### commands.diff The settings of the `diff` and `changelog` commands: the rules of the OpenAPI differ, and the `swagger`, `asyncapi`, `protobuf` and `graphql` sections of the other differs. See [diff](/docs/reference/cli/diff#configuration). ### commands.mock Configuration of the mock server, `apigenie-server`: the document, the address, responses, validation, security, network simulation, scenarios, AsyncAPI channels, gRPC services (`grpc`: proto paths, stub files, limits, reflection, health and the proxy), the validating proxy (`proxy`, whose `target` may be `https://` or `wss://`), TLS (`tls`: the certificate and key to serve HTTPS with, `client_ca` to require client certificates, the authorities trusted for upstreams, `insecure`, and `client_cert` and `client_key` to present to them), scripts, the admin API and the log. The same keys at the top level of a file of its own (`apigenie-server.yaml`, or `apigenie-mock.yaml`) work too. For more details, see [server configuration](/docs/reference/server/configuration). ### commands.generate A section per code generator of [`apigenie-generator`](/docs/reference/generator), which reads the file found in the repository or given with `--config`. Every section of a target of OpenAPI or AsyncAPI documents (not `docs`, `server_absinthe` or `server_elixir_grpc`) also takes `overlay`: a list of [overlays](/docs/reference/generator#overlays) applied to the input before generating, with paths relative to the configuration file. The `--overlay` arguments apply after them. ```yaml version: '1.0' commands: generate: server_spring: overlay: - overlays/spring.overlay.yaml ``` | Key | Configuration details (link) | | ---------------------------------- | -------------------------------------------------------------------------------------------------------- | | `commands.generate.data` | [`apigenie-generator data` configuration](/docs/reference/generator/data#configuration) | | `commands.generate.client_csharp` | [`apigenie-generator client csharp` configuration](/docs/reference/generator/client-csharp#configuration) | | `commands.generate.client_csharp.asyncapi` | [`apigenie-generator client csharp` (AsyncAPI) configuration](/docs/reference/generator/client-csharp-asyncapi#configuration) | | `commands.generate.client_elixir` | [`apigenie-generator client elixir` configuration](/docs/reference/generator/client-elixir#configuration) | | `commands.generate.client_elixir.asyncapi` | [`apigenie-generator client elixir` (AsyncAPI) configuration](/docs/reference/generator/client-elixir-asyncapi#configuration) | | `commands.generate.client_elixir.protobuf` | [`apigenie-generator client elixir` (Protobuf) configuration](/docs/reference/generator/client-elixir-protobuf#configuration) | | `commands.generate.client_fetch` | [`apigenie-generator client fetch` configuration](/docs/reference/generator/client-fetch#configuration) | | `commands.generate.client_go` | [`apigenie-generator client go` configuration](/docs/reference/generator/client-go#configuration) | | `commands.generate.client_go.asyncapi` | [`apigenie-generator client go` (AsyncAPI) configuration](/docs/reference/generator/client-go-asyncapi#configuration) | | `commands.generate.client_java` | [`apigenie-generator client java` configuration](/docs/reference/generator/client-java#configuration) | | `commands.generate.client_java.asyncapi` | [`apigenie-generator client java` (AsyncAPI) configuration](/docs/reference/generator/client-java-asyncapi#configuration) | | `commands.generate.client_python` | [`apigenie-generator client python` configuration](/docs/reference/generator/client-python#configuration) | | `commands.generate.client_python.asyncapi` | [`apigenie-generator client python` (AsyncAPI) configuration](/docs/reference/generator/client-python-asyncapi#configuration) | | `commands.generate.client_rust` | [`apigenie-generator client rust` configuration](/docs/reference/generator/client-rust#configuration) | | `commands.generate.client_swift` | [`apigenie-generator client swift` configuration](/docs/reference/generator/client-swift#configuration) | | `commands.generate.server_express` | [`apigenie-generator server express` configuration](/docs/reference/generator/server-express#configuration) | | `commands.generate.docs` | [`apigenie-generator docs` configuration](/docs/reference/generator/docs#configuration) | | `commands.generate.server_fastapi` | [`apigenie-generator server fastapi` configuration](/docs/reference/generator/server-fastapi#configuration) | | `commands.generate.server_faststream` | [`apigenie-generator server faststream` configuration](/docs/reference/generator/server-faststream#configuration) | | `commands.generate.server_go` | [`apigenie-generator server go` configuration](/docs/reference/generator/server-go#configuration) | | `commands.generate.server_go.asyncapi` | [`apigenie-generator server go` (AsyncAPI) configuration](/docs/reference/generator/server-go-asyncapi#configuration) | | `commands.generate.server_hummingbird` | [`apigenie-generator server hummingbird` configuration](/docs/reference/generator/server-hummingbird#configuration) | | `commands.generate.server_mcp` | [`apigenie-generator server mcp` configuration](/docs/reference/generator/server-mcp#configuration) | | `commands.generate.server_orpc` | [`apigenie-generator server orpc` configuration](/docs/reference/generator/server-orpc#configuration) | | `commands.generate.server_phoenix` | [`apigenie-generator server phoenix` configuration](/docs/reference/generator/server-phoenix#configuration) | | `commands.generate.server_phoenix.asyncapi` | [`apigenie-generator server phoenix` (AsyncAPI) configuration](/docs/reference/generator/server-phoenix-asyncapi#configuration) | | `commands.generate.server_elixir_grpc` | [`apigenie-generator server elixir-grpc` configuration](/docs/reference/generator/server-elixir-grpc#configuration) | | `commands.generate.server_spring` | [`apigenie-generator server spring` configuration](/docs/reference/generator/server-spring#configuration) | | `commands.generate.server_spring.asyncapi` | [`apigenie-generator server spring` (AsyncAPI) configuration](/docs/reference/generator/server-spring-asyncapi#configuration) | | `commands.generate.server_vapor` | [`apigenie-generator server vapor` configuration](/docs/reference/generator/server-vapor#configuration) | | `commands.generate.server_absinthe` | [`apigenie-generator server absinthe` configuration](/docs/reference/generator/server-absinthe#configuration) | | `commands.generate.server_aspnet` | [`apigenie-generator server aspnet` configuration](/docs/reference/generator/server-aspnet#configuration) | | `commands.generate.server_aspnet.asyncapi` | [`apigenie-generator server aspnet` (AsyncAPI) configuration](/docs/reference/generator/server-aspnet-asyncapi#configuration) | | `commands.generate.server_axum` | [`apigenie-generator server axum` configuration](/docs/reference/generator/server-axum#configuration) | | `commands.generate.client_kafkajs` | [`apigenie-generator client kafkajs` configuration](/docs/reference/generator/client-kafkajs#configuration) | | `commands.generate.server_kafkajs` | [`apigenie-generator server kafkajs` configuration](/docs/reference/generator/server-kafkajs#configuration) | | `commands.generate.client_ws` | [`apigenie-generator client ws` configuration](/docs/reference/generator/client-ws#configuration) | | `commands.generate.server_ws` | [`apigenie-generator server ws` configuration](/docs/reference/generator/server-ws#configuration) | | `commands.generate.schema_zod` | [`apigenie-generator schema zod` configuration](/docs/reference/generator/schema-zod#configuration) | ## See also - [config](/docs/reference/cli/config): Checks a file, and prints the schema. - [Formats](/docs/reference/cli/formats): The format registry that `openapi.custom_formats` extends. - [Server configuration](/docs/reference/server/configuration): The keys of `commands.mock`. - [`apigenie-catalog`](/docs/reference/catalog): Writes the `catalog` section. --- # Formats Source: https://apigenie.pl/docs/reference/cli/formats See also: [Configuration](https://apigenie.pl/docs/reference/cli/configuration.md), [Specification extensions](https://apigenie.pl/docs/reference/cli/extensions.md), [faker](https://apigenie.pl/docs/reference/cli/faker.md), [Compatibility](https://apigenie.pl/docs/reference/cli/compatibility.md), [apigenie-mcp](https://apigenie.pl/docs/reference/cli/mcp.md). API Genie follows the [OpenAPI format registry](https://spec.openapis.org/registry/format/), the list of `format` values the OpenAPI Initiative keeps, with the JSON types each applies to. The same list drives every part of API Genie (docs/adrs/166): - **Validation.** [`apigenie-server`](/docs/reference/server) checks the formats of requests and responses (mock and `--proxy-to`), as do the contract checks of `apigenie test`. A format applies to its JSON types only: `format: int32` checks numbers, and leaves a string to `type`. `validation.formats: false` turns format checks off. - **Lint.** [schema-format-type-mismatch](/docs/linter/openapi/rules/schema-format-type-mismatch) checks that a schema's `type` is one of its format's JSON types, [schema-format-deprecated](/docs/linter/openapi/rules/schema-format-deprecated) reports the deprecated formats with their replacement, and [schema-format-unknown](/docs/linter/openapi/rules/schema-format-unknown) (in the `strict` ruleset) reports formats that are neither in the registry nor declared. - **Code and data generation.** The generators map formats to the language's types (the table says which), and `apigenie-generator data` and the server's generated responses make values that pass the checks. - **Documentation.** The documentation components link a registry format to its registry page. Formats of your own are declared in [`openapi.custom_formats`](/docs/reference/cli/configuration#openapicustom_formats), with the JSON type they apply to; they are accepted as they are. An entry naming a registry format replaces that format's type and turns its check off. ## The registry | Format | JSON types | Validated | Generated code | Notes | | ------ | ---------- | --------- | -------------- | ----- | | [`base64url`](https://spec.openapis.org/registry/format/base64url.html) | string | yes | string | **Deprecated** from OpenAPI 3.1: use `contentEncoding: base64url`. Binary data encoded as a url-safe string as defined in RFC4648 | | [`binary`](https://spec.openapis.org/registry/format/binary.html) | string | no | bytes or a file | **Deprecated** from OpenAPI 3.1: use `contentMediaType`. any sequence of octets | | [`byte`](https://spec.openapis.org/registry/format/byte.html) | string | yes | bytes | **Deprecated** from OpenAPI 3.1: use `contentEncoding: base64`. base64 encoded data as defined in RFC4648 | | [`char`](https://spec.openapis.org/registry/format/char.html) | string | yes | string | A single character | | [`commonmark`](https://spec.openapis.org/registry/format/commonmark.html) | string | no | string | commonmark-formatted text | | [`date`](https://spec.openapis.org/registry/format/date.html) | string | yes | date | date as defined by full-date - RFC3339 | | [`date-time`](https://spec.openapis.org/registry/format/date-time.html) | string | yes | date-time with offset | date and time as defined by date-time - RFC3339 | | [`date-time-local`](https://spec.openapis.org/registry/format/date-time-local.html) | string | yes | local date-time (Java `LocalDateTime`, C# `DateTime`, Python `NaiveDatetime`) | RFC3339 date-time without the timezone component | | [`decimal`](https://spec.openapis.org/registry/format/decimal.html) | string, number | yes | decimal (Java `BigDecimal`, C# `decimal`, Python `Decimal`) | A fixed point decimal number of unspecified precision and range | | [`decimal128`](https://spec.openapis.org/registry/format/decimal128.html) | string, number | yes | decimal (Java `BigDecimal`, C# `decimal`, Python `Decimal`) | A decimal floating-point number with 34 significant decimal digits | | [`double`](https://spec.openapis.org/registry/format/double.html) | number | yes | double-precision float | double precision floating point number | | [`double-int`](https://spec.openapis.org/registry/format/double-int.html) | number | yes | 64-bit integer | an integer that can be stored in an IEEE 754 double-precision number without loss of precision | | [`duration`](https://spec.openapis.org/registry/format/duration.html) | string | yes | duration (Python `timedelta`) | duration as defined by duration - RFC3339 | | [`email`](https://spec.openapis.org/registry/format/email.html) | string | yes | string (FastAPI `EmailStr`) | An email address as defined as Mailbox in RFC5321 | | [`float`](https://spec.openapis.org/registry/format/float.html) | number | yes | single-precision float | single precision floating point number | | [`hostname`](https://spec.openapis.org/registry/format/hostname.html) | string | yes | string | A host name as defined by RFC1123 | | [`html`](https://spec.openapis.org/registry/format/html.html) | string | no | string | HTML-formatted text | | [`http-date`](https://spec.openapis.org/registry/format/http-date.html) | string | yes | string | date and time as defined by HTTP-date - RFC7231 | | [`idn-email`](https://spec.openapis.org/registry/format/idn-email.html) | string | yes | string | An email address as defined as Mailbox in RFC6531 | | [`idn-hostname`](https://spec.openapis.org/registry/format/idn-hostname.html) | string | yes | string | An internationalized host name as defined by RFC5890 | | [`int16`](https://spec.openapis.org/registry/format/int16.html) | number | yes | integer (C# `short`, Go `int16`) | signed 16-bit integer | | [`int32`](https://spec.openapis.org/registry/format/int32.html) | number | yes | integer | signed 32-bit integer | | [`int64`](https://spec.openapis.org/registry/format/int64.html) | number, string | yes | 64-bit integer | signed 64-bit integer | | [`int8`](https://spec.openapis.org/registry/format/int8.html) | number | yes | integer (C# `sbyte`, Go `int8`) | signed 8-bit integer | | [`ipv4`](https://spec.openapis.org/registry/format/ipv4.html) | string | yes | string (FastAPI `IPv4Address`) | An IPv4 address as defined as dotted-quad by RFC2673 | | [`ipv4-cidr`](https://spec.openapis.org/registry/format/ipv4-cidr.html) | string | yes | string | An IPv4 address in CIDR notation | | [`ipv6`](https://spec.openapis.org/registry/format/ipv6.html) | string | yes | string (FastAPI `IPv6Address`) | An IPv6 address as defined by RFC4673 | | [`ipv6-cidr`](https://spec.openapis.org/registry/format/ipv6-cidr.html) | string | yes | string | An IPv6 address in CIDR-style notation | | [`iri`](https://spec.openapis.org/registry/format/iri.html) | string | yes | string | A Internationalized Resource Identifier as defined in RFC3987 | | [`iri-reference`](https://spec.openapis.org/registry/format/iri-reference.html) | string | yes | string | A Internationalized Resource Identifier as defined in RFC3987 | | [`json-pointer`](https://spec.openapis.org/registry/format/json-pointer.html) | string | yes | string | A JSON string representation of a JSON Pointer as defined in RFC6901 | | [`language`](https://spec.openapis.org/registry/format/language.html) | string | yes | string | language tag as defined in RFC5646 | | [`media-range`](https://spec.openapis.org/registry/format/media-range.html) | string | yes | string | A media type as defined by the media-range ABNF production in RFC9110. | | [`password`](https://spec.openapis.org/registry/format/password.html) | string | no | string | a string that hints to obscure the value. | | [`regex`](https://spec.openapis.org/registry/format/regex.html) | string | yes | string | A regular expression as defined in ECMA-262 | | [`relative-json-pointer`](https://spec.openapis.org/registry/format/relative-json-pointer.html) | string | yes | string | A JSON string representation of a relative JSON Pointer as defined in draft RFC 01 | | [`sf-binary`](https://spec.openapis.org/registry/format/sf-binary.html) | string | yes | string | structured fields byte sequence as defined in RFC8941 | | [`sf-boolean`](https://spec.openapis.org/registry/format/sf-boolean.html) | string | yes | string | structured fields boolean as defined in RFC8941 | | [`sf-decimal`](https://spec.openapis.org/registry/format/sf-decimal.html) | number | yes | string | structured fields decimal as defined in RFC8941 | | [`sf-integer`](https://spec.openapis.org/registry/format/sf-integer.html) | number | yes | 64-bit integer | structured fields integer as defined in RFC8941 | | [`sf-string`](https://spec.openapis.org/registry/format/sf-string.html) | string | yes | string | structured fields string as defined in RFC8941 | | [`sf-token`](https://spec.openapis.org/registry/format/sf-token.html) | string | yes | string | structured fields token as defined in RFC8941 | | [`time`](https://spec.openapis.org/registry/format/time.html) | string | yes | time | time as defined by full-time - RFC3339 | | [`time-local`](https://spec.openapis.org/registry/format/time-local.html) | string | yes | local time (Java `LocalTime`, C# `TimeOnly`, Python `time`) | RFC3339 time without the timezone component | | [`uint16`](https://spec.openapis.org/registry/format/uint16.html) | number | yes | integer (C# `ushort`, Go `uint16`) | unsigned 16-bit integer | | [`uint32`](https://spec.openapis.org/registry/format/uint32.html) | number | yes | integer (Java `Long`, C# `uint`) | unsigned 32-bit integer | | [`uint64`](https://spec.openapis.org/registry/format/uint64.html) | number, string | yes | integer (Java `BigInteger`, C# `ulong`) | unsigned 64-bit integer | | [`uint8`](https://spec.openapis.org/registry/format/uint8.html) | number | yes | integer (C# `byte`, Go `uint8`) | unsigned 8-bit integer | | [`unixtime`](https://spec.openapis.org/registry/format/unixtime.html) | number, string | yes | 64-bit integer (epoch seconds) | seconds since Jan 1st 1970 - IEEE1003.1-2024/POSIX.1-2024 | | [`uri`](https://spec.openapis.org/registry/format/uri.html) | string | yes | URI (Java, C#) | A Uniform Resource Identifier as defined in RFC3986 | | [`uri-reference`](https://spec.openapis.org/registry/format/uri-reference.html) | string | yes | string | A URI reference as defined in RFC3986 | | [`uri-template`](https://spec.openapis.org/registry/format/uri-template.html) | string | yes | string | A URI Template as defined in RFC6570 | | [`uuid`](https://spec.openapis.org/registry/format/uuid.html) | string | yes | UUID | A Universally Unique IDentifier as defined in RFC4122 | "Generated code" names the type most generators use; the TypeScript and Zod generators keep JSON's `number` and `string`, adding range checks for the integer formats. commonmark, html, password and binary have no syntax to check. The registry is vendored into API Genie and refreshed with `src/jv_schema/scripts/update-format-registry`; a format added to the registry after an API Genie release is unknown to it until the next one, and can be declared in `openapi.custom_formats` meanwhile. --- # Specification extensions Source: https://apigenie.pl/docs/reference/cli/extensions See also: [Configuration](https://apigenie.pl/docs/reference/cli/configuration.md), [Formats](https://apigenie.pl/docs/reference/cli/formats.md), [faker](https://apigenie.pl/docs/reference/cli/faker.md), [Compatibility](https://apigenie.pl/docs/reference/cli/compatibility.md), [apigenie-mcp](https://apigenie.pl/docs/reference/cli/mcp.md). OpenAPI, Swagger 2.0 and AsyncAPI documents keep what the specification has no field for in `x-` fields, the specification extensions. This page lists the extensions API Genie reads: its own, under `x-apigenie`, and those of other tools that its generators, linters, differ and mock server understand. Each entry says where the extension goes, the value it takes and which tools read it; the page of each tool holds the details. An extension that is not listed here is kept as it is, and read by no tool: - [`apigenie format`](/docs/reference/cli/format) keeps it. An order of properties never lists extensions, so they follow the listed fields, and the `extension` order applies inside their values ([Property order](/docs/reference/cli/format/property-order#objects)). - [`apigenie diff`](/docs/reference/cli/diff) reports an extension added, removed or changed, and rates the change with the `extensions` map of the node type's rules, `*` for the names not listed, or with `defaults.extensions`. - [`apigenie convert`](/docs/reference/cli/convert) copies extensions from a Swagger 2.0 document to the OpenAPI document it writes. - The documentation components show none of these. The Redoc extensions (`x-tagGroups`, `x-displayName`, `x-logo`, `x-codeSamples`) are not read. The extensions a generator reads can live in an overlay of that generator instead of in the document, passed with `--overlay` ([Overlays](/docs/reference/generator#overlays)). ## API Genie's own | Extension | Where it goes, its value, and the tools that read it | | --------- | ---------------------------------------------------- | | `x-apigenie.codegen.name` | **Where:** A component schema; in AsyncAPI also a channel, a message or an operation.
**Value:** The name of the generated type, class, module or schema; on a channel or a message, the base of its names; on an operation, the name of its function.
**Read by:** The generators: client [elixir](/docs/reference/generator/client-elixir), [fetch](/docs/reference/generator/client-fetch), [go](/docs/reference/generator/client-go), [go (AsyncAPI)](/docs/reference/generator/client-go-asyncapi), [java (AsyncAPI)](/docs/reference/generator/client-java-asyncapi), [kafkajs](/docs/reference/generator/client-kafkajs), [python](/docs/reference/generator/client-python), [python (AsyncAPI)](/docs/reference/generator/client-python-asyncapi), [rust](/docs/reference/generator/client-rust), [swift](/docs/reference/generator/client-swift), [ws](/docs/reference/generator/client-ws); server [axum](/docs/reference/generator/server-axum), [express](/docs/reference/generator/server-express), [faststream](/docs/reference/generator/server-faststream), [go](/docs/reference/generator/server-go), [go (AsyncAPI)](/docs/reference/generator/server-go-asyncapi), [hummingbird](/docs/reference/generator/server-hummingbird), [kafkajs](/docs/reference/generator/server-kafkajs), [orpc](/docs/reference/generator/server-orpc), [phoenix](/docs/reference/generator/server-phoenix), [spring (AsyncAPI)](/docs/reference/generator/server-spring-asyncapi), [vapor](/docs/reference/generator/server-vapor), [ws](/docs/reference/generator/server-ws); [schema zod](/docs/reference/generator/schema-zod) | | `x-apigenie.codegen.controller-name` | **Where:** An operation or its path item.
**Value:** The class, module, resource or interface the operation goes into, instead of its tag or path.
**Read by:** client [csharp](/docs/reference/generator/client-csharp), [java](/docs/reference/generator/client-java), [python](/docs/reference/generator/client-python) (since 0.12.0); server [aspnet](/docs/reference/generator/server-aspnet), [express](/docs/reference/generator/server-express), [fastapi](/docs/reference/generator/server-fastapi), [spring](/docs/reference/generator/server-spring) | | `x-apigenie.codegen.action-name` | **Where:** An operation.
**Value:** The name of the method, function, handler or procedure, or of a webhook sender, instead of the `operationId`.
**Read by:** client [csharp](/docs/reference/generator/client-csharp), [elixir](/docs/reference/generator/client-elixir), [fetch](/docs/reference/generator/client-fetch), [go](/docs/reference/generator/client-go), [java](/docs/reference/generator/client-java), [python](/docs/reference/generator/client-python), [rust](/docs/reference/generator/client-rust), [swift](/docs/reference/generator/client-swift); server [aspnet](/docs/reference/generator/server-aspnet), [axum](/docs/reference/generator/server-axum), [express](/docs/reference/generator/server-express), [fastapi](/docs/reference/generator/server-fastapi), [go](/docs/reference/generator/server-go), [hummingbird](/docs/reference/generator/server-hummingbird), [orpc](/docs/reference/generator/server-orpc), [phoenix](/docs/reference/generator/server-phoenix), [spring](/docs/reference/generator/server-spring), [vapor](/docs/reference/generator/server-vapor) | | `x-apigenie.codegen.disabled` | **Where:** An operation or its path item; in AsyncAPI a channel or an operation.
**Value:** `true` leaves it out of the generated code.
**Read by:** The generators of clients and servers from OpenAPI and AsyncAPI documents, except client [elixir (AsyncAPI)](/docs/reference/generator/client-elixir-asyncapi), and server [orpc](/docs/reference/generator/server-orpc) and [phoenix (AsyncAPI)](/docs/reference/generator/server-phoenix-asyncapi) | | `x-apigenie-lint-disable`, alias `x-lint-disable` | **Where:** Any object, the root included.
**Value:** A list of rule ids, disabled for the object and everything nested in it.
**Read by:** [`apigenie lint`](/docs/reference/cli/lint#disabling-rules-in-a-document) of OpenAPI, Swagger 2.0 and AsyncAPI documents | | `x-apigenie-mock` | **Where:** An OpenAPI operation or its path item.
**Value:** `status`, `example`, `dynamic`, `body`, `body_file`, `headers`, `latency`, `jitter`, `drop`, `bandwidth`, `delay`, `probability`, `validate_request`, `scenarios`, `resource`.
**Read by:** [`apigenie-server`](/docs/reference/server/scenarios); `resource` makes a [CRUD resource](/docs/reference/server/store#crud-resources) | | `x-apigenie-mock` | **Where:** An OpenAPI response.
**Value:** `delay`, `latency`, `jitter`, `headers`.
**Read by:** [`apigenie-server`](/docs/reference/server/scenarios) | | `x-apigenie-mock` | **Where:** An AsyncAPI `send` operation.
**Value:** `interval` (milliseconds), `count`, `jitter`, `messages`, `publish: false`.
**Read by:** [`apigenie-server`](/docs/reference/server/asyncapi) | | `x-apigenie-mock-faker`, alias `x-faker` | **Where:** A schema.
**Value:** A [faker provider](/docs/reference/cli/faker): a name, `{name: [arguments]}`, or `{provider, args, options}`; `x-apigenie-mock-faker` wins over `x-faker`.
**Read by:** [`apigenie-server`](/docs/reference/server/scenarios), [data](/docs/reference/generator/data) | | `x-apigenie-broadway` | **Where:** The Kafka binding of an AsyncAPI operation or channel.
**Value:** `batch_size` and `batch_timeout` of the Broadway pipeline.
**Read by:** [server phoenix (AsyncAPI)](/docs/reference/generator/server-phoenix-asyncapi) | `x-apigenie-lint-disable`, `x-apigenie-mock`, `x-apigenie-mock-faker` and the `codegen` members of `x-apigenie` are part of the [compatibility promise](/docs/reference/cli/compatibility#what-the-promise-covers). `X-Apigenie-Mock-*` and `X-Apigenie-Test` are HTTP headers and gRPC metadata, not extensions: see [Responses](/docs/reference/server/responses), [Protobuf and gRPC](/docs/reference/server/grpc) and [Recording](/docs/reference/server/recording). ## Lifecycle and governance | Extension | Where it goes, its value, and the tools that read it | | --------- | ---------------------------------------------------- | | `x-sunset` | **Where:** Next to `deprecated: true`: an operation, a parameter, a schema, a property (beside its `$ref` or where it is defined).
**Value:** An RFC 3339 date (`2027-01-31`) or date-time after which the element may go.
**Read by:** [`apigenie diff`](/docs/reference/cli/diff), the `sunset_passed` condition of OpenAPI and Swagger 2.0 rules; written by [`apigenie evolve plan`](/docs/reference/cli/evolve) | | `x-deprecated-enum` | **Where:** A schema with an `enum`.
**Value:** The enum values that are deprecated; the schema's `x-sunset` says when they may go.
**Read by:** [`apigenie diff`](/docs/reference/cli/diff), the `deprecated` condition; written by [`apigenie evolve plan`](/docs/reference/cli/evolve) | | `x-audience` | **Where:** `info`.
**Value:** `internal-team`, `internal-company`, `partner` or `public`.
**Read by:** The `audience-defined` rule of [OpenAPI](/docs/linter/openapi/rules/audience-defined), [Swagger 2.0](/docs/linter/swagger/rules/audience-defined) and [AsyncAPI](/docs/linter/asyncapi/rules/audience-defined) | | `x-id` | **Where:** `info`.
**Value:** A UUID, or a value matching the rule's `pattern`; the rule's `attribute` can name another extension.
**Read by:** The `id-defined` rule of [OpenAPI](/docs/linter/openapi/rules/id-defined) and [Swagger 2.0](/docs/linter/swagger/rules/id-defined) | ## OpenAPI 3.2 fields in 3.0 and 3.1 documents The OpenAPI reader reads these extensions as the field of a later version they stand for: `x-webhooks` in a 3.0 document, the others in a 3.0 or 3.1 document. The tools that write such a document write the field back as the extension. | Extension | Where it goes, its value, and the tools that read it | | --------- | ---------------------------------------------------- | | `x-itemSchema` | **Where:** A media type.
**Value:** `itemSchema`: the schema of each item of a streamed body.
**Read by:** client [csharp](/docs/reference/generator/client-csharp), [fetch](/docs/reference/generator/client-fetch), [go](/docs/reference/generator/client-go), [java](/docs/reference/generator/client-java), [rust](/docs/reference/generator/client-rust), [swift](/docs/reference/generator/client-swift); server [aspnet](/docs/reference/generator/server-aspnet), [axum](/docs/reference/generator/server-axum), [express](/docs/reference/generator/server-express), [hummingbird](/docs/reference/generator/server-hummingbird), [orpc](/docs/reference/generator/server-orpc), [vapor](/docs/reference/generator/server-vapor) | | `x-defaultMapping` | **Where:** A discriminator.
**Value:** `defaultMapping`: the schema of the values the `mapping` does not list.
**Read by:** client [csharp](/docs/reference/generator/client-csharp), [elixir](/docs/reference/generator/client-elixir), [fetch](/docs/reference/generator/client-fetch), [go](/docs/reference/generator/client-go), [java](/docs/reference/generator/client-java), [python](/docs/reference/generator/client-python), [rust](/docs/reference/generator/client-rust), [swift](/docs/reference/generator/client-swift); server [aspnet](/docs/reference/generator/server-aspnet), [axum](/docs/reference/generator/server-axum), [express](/docs/reference/generator/server-express), [fastapi](/docs/reference/generator/server-fastapi), [go](/docs/reference/generator/server-go), [hummingbird](/docs/reference/generator/server-hummingbird), [orpc](/docs/reference/generator/server-orpc), [phoenix](/docs/reference/generator/server-phoenix), [spring](/docs/reference/generator/server-spring), [vapor](/docs/reference/generator/server-vapor) | | `x-webhooks` | **Where:** The root of an OpenAPI 3.0 document.
**Value:** An object: `webhooks` (OpenAPI 3.1), the requests the API sends to its subscribers. Another value stays an extension.
**Read by:** The OpenAPI reader, so the linter, `diff`, `changelog` and the generators see them; server [aspnet](/docs/reference/generator/server-aspnet), [express](/docs/reference/generator/server-express) and [orpc](/docs/reference/generator/server-orpc) generate their senders | | `x-nodeType` | **Where:** An XML object.
**Value:** `nodeType`: `element`, `attribute`, `text`, `cdata` or `none`.
**Read by:** [`apigenie-server`](/docs/reference/server/validation#xml-bodies) for XML bodies; written by [`apigenie convert`](/docs/reference/cli/convert) from WSDL | ## Code generation Most of these are the names of [OpenAPI Generator](https://openapi-generator.tech/docs/templating/) and, for Go, of [oapi-codegen](https://github.com/oapi-codegen/oapi-codegen#openapi-extensions), read by the API Genie generators of the same languages. | Extension | Where it goes, its value, and the tools that read it | | --------- | ---------------------------------------------------- | | `x-internal` | **Where:** An operation or its path item.
**Value:** `true` leaves the operation out; client fetch, go and elixir, server phoenix and mcp and, since 0.12.0, client python, server go, client swift and the Swift servers (vapor, hummingbird) keep it with `internal_operations`; since 0.12.0, server fastapi serves it but leaves it out of the served OpenAPI document. Client rust and server axum generate it behind the cargo feature `internal` (`internal_operations: include` or `exclude` instead).
**Read by:** client [csharp](/docs/reference/generator/client-csharp), [elixir](/docs/reference/generator/client-elixir), [fetch](/docs/reference/generator/client-fetch), [go](/docs/reference/generator/client-go), [java](/docs/reference/generator/client-java), [python](/docs/reference/generator/client-python), [rust](/docs/reference/generator/client-rust), [swift](/docs/reference/generator/client-swift); server [aspnet](/docs/reference/generator/server-aspnet), [axum](/docs/reference/generator/server-axum), [fastapi](/docs/reference/generator/server-fastapi) (since 0.12.0), [go](/docs/reference/generator/server-go) (since 0.12.0), [hummingbird](/docs/reference/generator/server-hummingbird), [mcp](/docs/reference/generator/server-mcp), [phoenix](/docs/reference/generator/server-phoenix), [spring](/docs/reference/generator/server-spring), [vapor](/docs/reference/generator/server-vapor). The other targets generate the operation. | | `x-mcp` | **Where:** An operation or its path item.
**Value:** `false`: the operation is not a tool.
**Read by:** [server mcp](/docs/reference/generator/server-mcp) | | `x-codegen-request-body-name` | **Where:** An operation or its request body.
**Value:** The name of the body parameter.
**Read by:** [client java](/docs/reference/generator/client-java), server [fastapi](/docs/reference/generator/server-fastapi), [spring](/docs/reference/generator/server-spring); written by the editor's Swagger 2.0 import | | `x-enum-varnames` | **Where:** A schema with an `enum`.
**Value:** The names of the constants, in the order of the values.
**Read by:** client [csharp](/docs/reference/generator/client-csharp), [csharp (AsyncAPI)](/docs/reference/generator/client-csharp-asyncapi), [go](/docs/reference/generator/client-go), [go (AsyncAPI)](/docs/reference/generator/client-go-asyncapi), [java](/docs/reference/generator/client-java), [python](/docs/reference/generator/client-python), [python (AsyncAPI)](/docs/reference/generator/client-python-asyncapi), [rust](/docs/reference/generator/client-rust), [swift](/docs/reference/generator/client-swift); server [aspnet](/docs/reference/generator/server-aspnet), [axum](/docs/reference/generator/server-axum), [aspnet (AsyncAPI)](/docs/reference/generator/server-aspnet-asyncapi), [faststream](/docs/reference/generator/server-faststream), [go](/docs/reference/generator/server-go), [go (AsyncAPI)](/docs/reference/generator/server-go-asyncapi), [hummingbird](/docs/reference/generator/server-hummingbird), [spring](/docs/reference/generator/server-spring), [vapor](/docs/reference/generator/server-vapor) | | `x-enumNames` | **Where:** A schema with an `enum`.
**Value:** The same as `x-enum-varnames`.
**Read by:** client [go](/docs/reference/generator/client-go), [go (AsyncAPI)](/docs/reference/generator/client-go-asyncapi), [python](/docs/reference/generator/client-python), [python (AsyncAPI)](/docs/reference/generator/client-python-asyncapi), [rust](/docs/reference/generator/client-rust), [swift](/docs/reference/generator/client-swift); server [axum](/docs/reference/generator/server-axum), [faststream](/docs/reference/generator/server-faststream), [go](/docs/reference/generator/server-go), [go (AsyncAPI)](/docs/reference/generator/server-go-asyncapi), [hummingbird](/docs/reference/generator/server-hummingbird), [vapor](/docs/reference/generator/server-vapor) | | `x-enum-names` | **Where:** A schema with an `enum`.
**Value:** The same as `x-enum-varnames`.
**Read by:** client [csharp](/docs/reference/generator/client-csharp), [csharp (AsyncAPI)](/docs/reference/generator/client-csharp-asyncapi); server [aspnet](/docs/reference/generator/server-aspnet), [aspnet (AsyncAPI)](/docs/reference/generator/server-aspnet-asyncapi) | | `x-enum-descriptions` | **Where:** A schema with an `enum`.
**Value:** The documentation comments of the constants, in the order of the values.
**Read by:** client [csharp](/docs/reference/generator/client-csharp), [csharp (AsyncAPI)](/docs/reference/generator/client-csharp-asyncapi), [go](/docs/reference/generator/client-go), [go (AsyncAPI)](/docs/reference/generator/client-go-asyncapi), [java](/docs/reference/generator/client-java), [rust](/docs/reference/generator/client-rust), [swift](/docs/reference/generator/client-swift); server [aspnet](/docs/reference/generator/server-aspnet), [axum](/docs/reference/generator/server-axum), [aspnet (AsyncAPI)](/docs/reference/generator/server-aspnet-asyncapi), [go](/docs/reference/generator/server-go), [go (AsyncAPI)](/docs/reference/generator/server-go-asyncapi), [hummingbird](/docs/reference/generator/server-hummingbird), [spring](/docs/reference/generator/server-spring), [vapor](/docs/reference/generator/server-vapor) | | `x-enumDescriptions` | **Where:** A schema with an `enum`.
**Value:** The same as `x-enum-descriptions`.
**Read by:** client [csharp](/docs/reference/generator/client-csharp), [csharp (AsyncAPI)](/docs/reference/generator/client-csharp-asyncapi); server [aspnet](/docs/reference/generator/server-aspnet), [aspnet (AsyncAPI)](/docs/reference/generator/server-aspnet-asyncapi) | ### Go Read by client [go](/docs/reference/generator/client-go) and [go (AsyncAPI)](/docs/reference/generator/client-go-asyncapi), and server [go](/docs/reference/generator/server-go) and [go (AsyncAPI)](/docs/reference/generator/server-go-asyncapi). | Extension | Where | Value | | --------- | ----- | ----- | | `x-go-name` | A schema or a property | The name of the type or of the field | | `x-go-type` | A schema | The Go type to use, e.g. `decimal.Decimal` | | `x-go-type-import` | A schema with `x-go-type` | `{path: ...}`: the package of the type | | `x-go-type-skip-optional-pointer` | A property | `true`: the optional field is not a pointer | | `x-go-json-ignore` | A property | `true`: the field gets the tag `json:"-"` | | `x-omitempty` | A property | `true` or `false` overrides the `omitempty` of the field | ### Rust Read by [client rust](/docs/reference/generator/client-rust) and [server axum](/docs/reference/generator/server-axum), since 0.12.0. | Extension | Where | Value | | --------- | ----- | ----- | | `x-rust-name` | A schema | The name of its type | | `x-rust-type` | A schema | The Rust type to use, a path such as `my_crate::Money`, or a name `type_mappings` maps to one | ### Swift Read by client [swift](/docs/reference/generator/client-swift) and server [hummingbird](/docs/reference/generator/server-hummingbird) and [vapor](/docs/reference/generator/server-vapor). | Extension | Where | Value | | --------- | ----- | ----- | | `x-swift-name` | A schema or a property | The name of the type or of the property | ### Java and Spring Read by [client java](/docs/reference/generator/client-java) and [server spring](/docs/reference/generator/server-spring); a value that is a list of annotations or arguments can also be one string. | Extension | Where | Value | | --------- | ----- | ----- | | `x-class-extra-annotation` | A schema | Annotations of its class, e.g. `['@Entity']` | | `x-implements` | A schema | Interfaces its class implements | | `x-field-extra-annotation` | A property or a parameter | Annotations of the field or of the method parameter | | `x-extra-annotation` | A property | Annotations of the getter | | `x-setter-extra-annotation` | A property | Annotations of the setter | | `x-pattern-message`, `x-size-message`, `x-minimum-message`, `x-maximum-message` | A property | The `message` of `@Pattern`, `@Size`, `@Min` or `@DecimalMin`, `@Max` or `@DecimalMax` | | `x-jackson-json-include-policy` | A property | The `@JsonInclude` policy, e.g. `non_empty`; `none` for no annotation | | `x-jackson-json-setter-nulls` | A property | `@JsonSetter(nulls = ...)`, e.g. `skip`; `none` for no annotation | | `x-parent` | A schema | `true`: the superclass of the schemas extending it with `allOf`, without a discriminator | | `x-discriminator-value` | A schema extending one with a discriminator | Its value in `@JsonSubTypes`; the name of the schema by default | | `x-jackson-default-impl` | A schema with a discriminator | The `defaultImpl` of its `@JsonTypeInfo` | | `x-operation-extra-annotation` | An operation | Annotations of its method; not with `spring-http-interface` | | `x-version-param` | A header or query parameter | `true` adds it to the `headers` or `params` of `@RequestMapping`; not with `spring-http-interface` | | `x-spring-paginated` | An operation | `true` replaces `page`, `size` and `sort` with a `Pageable`; `false` keeps them with `autoXSpringPaginated`. Spring only | | `x-spring-provide-args` | An operation | Further arguments of its method, e.g. `['@RequestAttribute("tenant") String tenant']`. Spring only, not with `spring-http-interface` | ## Swagger 2.0 | Extension | Where it goes, its value, and the tools that read it | | --------- | ---------------------------------------------------- | | `x-nullable` | **Where:** A schema.
**Value:** `true`: `null` is a valid value.
**Read by:** [`apigenie convert`](/docs/reference/cli/convert) (adds `null` to the type), [schema zod](/docs/reference/generator/schema-zod), the documentation components, the editor's Swagger 2.0 import | | `x-example` | **Where:** A parameter or a schema.
**Value:** An example value.
**Read by:** [`apigenie convert`](/docs/reference/cli/convert) (becomes `example`), the editor's Swagger 2.0 import; the documentation components, on a parameter | ## Written by `apigenie convert` A document [converted from WSDL](/docs/reference/cli/convert) keeps what OpenAPI has no field for in extensions. No tool reads them back. | Extension | Where | Value | | --------- | ----- | ----- | | `x-wsdl-target-namespace` | `info` | The `targetNamespace` of the WSDL | | `x-soap-address` | An operation | The address of the port | | `x-soap-action` | An operation | The SOAPAction of the operation | --- # faker Source: https://apigenie.pl/docs/reference/cli/faker See also: [Configuration](https://apigenie.pl/docs/reference/cli/configuration.md), [Formats](https://apigenie.pl/docs/reference/cli/formats.md), [Specification extensions](https://apigenie.pl/docs/reference/cli/extensions.md), [Compatibility](https://apigenie.pl/docs/reference/cli/compatibility.md), [apigenie-mcp](https://apigenie.pl/docs/reference/cli/mcp.md). API Genie makes realistic values (names, emails, addresses, IBANs, dates...) with its own faker library. Its providers are named like those of [faker.js](https://fakerjs.dev/api/) (`person.firstName`, `internet.email`) and are used by: - the `x-faker` (or `x-apigenie-mock-faker`) extension of schemas, in [`apigenie-server`](/docs/reference/server/scenarios) and [`data`](/docs/reference/generator/data); - `@mock(faker:, args:)` and `graphql.fields..faker` of the GraphQL mock; - `fake(name, ...arguments)` of mock scripts and `{{fake:name}}` of gRPC templates; - smart names: string properties called like `email`, `first_name` or `city`. ## Arguments A provider takes arguments by position or by name, and checks them: an argument it doesn't take, of the wrong type, out of its bounds or not one of its choices is an error naming the provider and the parameter (`faker: number.int: parameter min: expects an integer, not a string`). ```yaml properties: owner: {type: string, x-faker: person.fullName} age: {type: integer, x-faker: {number.int: [18, 90]}} code: {type: string, x-faker: {string.alpha: {length: 6, casing: upper}}} email: type: string x-faker: {provider: internet.email, args: [Ada, Lovelace], options: {provider: example.org}} ``` Arguments are numbers, strings and booleans. Whole numbers given as decimals (JavaScript and YAML give `6.0`) are integers. ## Records Some providers make related values together, as a record (an object): `person.profile` (a person's sex, first and last names of that sex, full name, a username made of the names, an email of that username and an adult's birth date), `location.address` (an address of one country, with its code and a time zone of it; city, state and postal code are of the country but not of each other), `finance.card` (an issuer's number, verification value length and expiration), `finance.currency` and `commerce.product`. A record is an object in JSON responses and data, and its JSON text where the schema wants a string. ## Countries Names exist for 61 countries; addresses and phone numbers for 15 of them (US, PL, FR, DE, IT, RU, IN, FI, ES, CZ, UA, DK, BR, AU and EE). Providers taking a `country` use the USA's data when not given one, except IBANs, BICs and national ids, which are then of a random country that has them. Usernames and emails are ASCII: names in Latin, Cyrillic or Greek letters are transliterated (`Łukasz` is `Lukasz`, `Иван` is `Ivan`); names in other scripts give usernames of American names. ## Validity IBANs have valid ISO 13616 check digits, routing numbers a valid ABA checksum, card numbers and IMEIs a valid Luhn check digit, and EAN and ISBN codes their check digits. National ids (`person.ssn`) are valid for Poland (PESEL), the USA, Spain (NIE) and the United Kingdom (National Insurance number), and only format-shaped for Germany, France, Italy and India. Bitcoin, Litecoin and Ethereum addresses and VINs are format-shaped. ## Reproducibility `--seed` repeats a run. Faker and the mocks draw their values with algorithms of their own, so a seed gives the same values on every platform: faker values and the other choices of a mock (numbers, list lengths, which optional properties, simulated failures) alike. Relative dates (`date.past`, `date.recent`, birth dates) count from a reference time and repeat when it does too. Values may change between versions of API Genie. ## Providers ### airline | Provider | Returns | Description | | --- | --- | --- | | `airline.aircraftTypeName` | string | An aircraft type: regional, narrowbody or widebody. | | `airline.airline` | string | The name of an airline. | | `airline.airplane` | string | The name of an airplane model. | | `airline.airport` | string | The name of an airport. | | `airline.flightNumber` | string | A flight number. `length` (integer, 1 to 10, default `4`): the number of digits. `addLeadingZeros` (boolean, default `false`): pad with zeros to the length. | | `airline.recordLocator` | string | A six-character booking reference. `allowNumbers` (boolean, default `false`): digits next to letters. | | `airline.seat` | string | A seat, e.g. 23C, of an aircraft of the type. `aircraftType` (one of `regional`, `narrowbody`, `widebody`, default `narrowbody`): regional, narrowbody or widebody. | ### animal | Provider | Returns | Description | | --- | --- | --- | | `animal.bear` | string | A bear species. | | `animal.bird` | string | A bird species. | | `animal.cat` | string | A cat breed. | | `animal.cetacean` | string | A cetacean species. | | `animal.cow` | string | A cattle breed. | | `animal.crocodilia` | string | A crocodilian species. | | `animal.dog` | string | A dog breed. | | `animal.fish` | string | A fish species. | | `animal.horse` | string | A horse breed. | | `animal.insect` | string | An insect species. | | `animal.lion` | string | A lion subspecies. | | `animal.rabbit` | string | A rabbit breed. | | `animal.rodent` | string | A rodent species. | | `animal.snake` | string | A snake species. | | `animal.type` | string | A kind of animal. | ### book | Provider | Returns | Description | | --- | --- | --- | | `book.author` | string | The name of an author. | | `book.format` | string | A book format, e.g. hardcover. | | `book.genre` | string | A literary genre. | | `book.isbn` | string | An ISBN-13 with its check digit. | | `book.page` | integer | A page number. | | `book.publisher` | string | The name of a publisher. | | `book.releaseYear` | integer | The year of a release. | | `book.series` | string | The name of a book series. | | `book.title` | string | The title of a book. | | `book.translator` | string | The name of a translator. | ### color | Provider | Returns | Description | | --- | --- | --- | | `color.cmyk` | string | A CMYK color. | | `color.hex` | string | A hexadecimal color, e.g. #a3c2f0. `casing` (one of `lower`, `upper`, default `lower`): lower or upper. `prefix` (one of `0x`, `#`, nothing, default `#`): 0x, # or nothing. `includeAlpha` (boolean, default `false`): add an alpha channel. Also `internet.color`. | | `color.hsb` | string | An HSB color. | | `color.hsl` | string | An HSL color. `includeAlpha` (boolean, default `false`): add an alpha channel. | | `color.hsv` | string | An HSV color. | | `color.lab` | string | A CIELAB color. | | `color.lch` | string | An LCH color. `includeAlpha` (boolean, default `false`): add an alpha channel. | | `color.name` | string | The name of a color. | | `color.rgb` | string | An RGB color. `includeAlpha` (boolean, default `false`): add an alpha channel. | | `color.yuv` | string | A YUV color. | ### commerce | Provider | Returns | Description | | --- | --- | --- | | `commerce.department` | string | A store department. | | `commerce.discountAmount` | number | A discount amount. | | `commerce.discountCode` | string | A discount code. | | `commerce.discountPercentage` | number | A discount percentage. | | `commerce.discountType` | string | A kind of discount. | | `commerce.ean13` | string | An EAN-13 barcode with its check digit. | | `commerce.ean8` | string | An EAN-8 barcode with its check digit. | | `commerce.isbn10` | string | An ISBN-10 with its check digit. | | `commerce.isbn13` | string | An ISBN-13 with its check digit. | | `commerce.paymentProvider` | string | A payment provider. | | `commerce.paymentType` | string | A payment method. | | `commerce.price` | string | A price with two decimals, as text. `min` (number, default `0`): the lowest price. `max` (number, default `1000`): the highest price. | | `commerce.product` | record | A product whose name, description, department, price and SKU belong together, a record. | | `commerce.productAdjective` | string | An adjective for a product. | | `commerce.productCategory` | string | A product category. | | `commerce.productDescription` | string | A product description. | | `commerce.productFullName` | string | A product name with an adjective and a material. | | `commerce.productId` | string | A product identifier. | | `commerce.productMaterial` | string | A material of a product. | | `commerce.productName` | string | The name of a product. | | `commerce.productRating` | number | A product rating. | | `commerce.productReview` | string | A product review. | | `commerce.sku` | string | A stock keeping unit of digits. `length` (integer, 1 to 64, default `4`): the number of digits. | ### company | Provider | Returns | Description | | --- | --- | --- | | `company.buzzAdjective` | string | A business buzzword adjective. | | `company.buzzNoun` | string | A business buzzword noun. | | `company.buzzPhrase` | string | A business buzzword phrase. Also `company.bs`. | | `company.buzzVerb` | string | A business buzzword verb. | | `company.catchPhrase` | string | A company catch phrase. | | `company.catchPhraseAdjective` | string | An adjective of a catch phrase. | | `company.catchPhraseDescriptor` | string | A descriptor of a catch phrase. | | `company.catchPhraseNoun` | string | A noun of a catch phrase. | | `company.industry` | string | An industry. | | `company.name` | string | The name of a company. Also `company.companyName`. | | `company.type` | string | A legal form of a company. | ### computer | Provider | Returns | Description | | --- | --- | --- | | `computer.cpuManufacturer` | string | A CPU manufacturer. | | `computer.cpuModel` | string | A CPU model. | | `computer.cpuType` | string | A CPU type. | | `computer.gpuManufacturer` | string | A GPU manufacturer. | | `computer.gpuModel` | string | A GPU model. | | `computer.gpuType` | string | A GPU type. | | `computer.manufacturer` | string | A computer manufacturer. | | `computer.model` | string | A computer model. | | `computer.type` | string | A kind of computer. | ### crypto | Provider | Returns | Description | | --- | --- | --- | | `crypto.md5` | string | The MD5 digest of the data, or of a random word. `data` (string): the data to hash. | | `crypto.sha256` | string | The SHA-256 digest of the data, or of a random word. `data` (string): the data to hash. | ### database | Provider | Returns | Description | | --- | --- | --- | | `database.collation` | string | A database collation. | | `database.columnName` | string | A column name. | | `database.columnType` | string | A column type. | | `database.engine` | string | A database engine. | | `database.mongodbObjectId` | string | A MongoDB ObjectId. | ### datatype | Provider | Returns | Description | | --- | --- | --- | | `datatype.boolean` | boolean | true with the probability. `probability` (number, 0 to 1, default `0.5`): the probability of true, 0 to 1. | ### date | Provider | Returns | Description | | --- | --- | --- | | `date.between` | string | A moment between two RFC 3339 dates or date-times, both included. `from` (string, required): the first moment, e.g. 2024-01-01 or 2024-01-01T10:00:00Z. `to` (string, required): the last moment. `format` (one of `iso`, `timestamp`, `date`, `time`, default `iso`): iso (an RFC 3339 date-time), timestamp (Unix seconds), date or time. | | `date.birthdate` | string | The birth moment of someone of an age on the reference date. `minAge` (integer, 0 to 150, default `18`): the lowest age in years. `maxAge` (integer, 0 to 150, default `80`): the highest age in years. `format` (one of `iso`, `timestamp`, `date`, `time`, default `iso`): iso (an RFC 3339 date-time), timestamp (Unix seconds), date or time. | | `date.birthdateByYear` | string | A birth moment within the years. `minYear` (integer, 0 to 9999, default `1920`): the first year. `maxYear` (integer, 0 to 9999, default `2000`): the last year. `format` (one of `iso`, `timestamp`, `date`, `time`, default `iso`): iso (an RFC 3339 date-time), timestamp (Unix seconds), date or time. | | `date.future` | string | A moment within calendar years after the reference time. `years` (integer, 1 to 1000, default `1`): how many years ahead. `format` (one of `iso`, `timestamp`, `date`, `time`, default `iso`): iso (an RFC 3339 date-time), timestamp (Unix seconds), date or time. | | `date.month` | string | The name of a month. `abbreviated` (boolean, default `false`): Jan rather than January. | | `date.past` | string | A moment within calendar years before the reference time. `years` (integer, 1 to 1000, default `1`): how many years back. `format` (one of `iso`, `timestamp`, `date`, `time`, default `iso`): iso (an RFC 3339 date-time), timestamp (Unix seconds), date or time. | | `date.recent` | string | A moment within days before the reference time. `days` (integer, 1 to 365000, default `3`): how many days back. `format` (one of `iso`, `timestamp`, `date`, `time`, default `iso`): iso (an RFC 3339 date-time), timestamp (Unix seconds), date or time. | | `date.soon` | string | A moment within days after the reference time. `days` (integer, 1 to 365000, default `3`): how many days ahead. `format` (one of `iso`, `timestamp`, `date`, `time`, default `iso`): iso (an RFC 3339 date-time), timestamp (Unix seconds), date or time. | | `date.weekday` | string | The name of a day of the week. `abbreviated` (boolean, default `false`): Mon rather than Monday. | ### finance | Provider | Returns | Description | | --- | --- | --- | | `finance.accountNumber` | string | A bank account number of digits. `length` (integer, 1 to 64, default `8`): the number of digits. Also `finance.account`. | | `finance.accountType` | string | A kind of bank account. | | `finance.amount` | string | An amount with two decimals, as text. `min` (number, default `0`): the lowest amount. `max` (number, default `1000`): the highest amount. `symbol` (string): a currency symbol to put first. | | `finance.bic` | string | A BIC (SWIFT code) of a bank of the country. `country` (one of `PL`, `US`, `GB`, `DE`, `RO`, `FR`, `IN`, `IT`, `NL`, `ES`): the ISO 3166-1 code of the country; the context's, or any, when not given. | | `finance.bitcoinAddress` | string | A Bitcoin address (format-shaped, no checksum). | | `finance.card` | record | A payment card whose number, verification value and expiration belong to one issuer, a record. `issuer` (one of `amex`, `discover`, `mastercard`, `visa`): amex, discover, mastercard or visa, any when not given. | | `finance.creditCardCvv` | string | A three-digit card verification value. | | `finance.creditCardExpirationDate` | string | An expiration date MM/YY within three years of the reference time. | | `finance.creditCardNumber` | string | A card number with a valid Luhn check digit. `issuer` (one of `amex`, `discover`, `mastercard`, `visa`): amex, discover, mastercard or visa, any when not given. | | `finance.currency` | record | A currency's name, ISO 4217 code and symbol, a record. | | `finance.currencyCode` | string | An ISO 4217 currency code. | | `finance.currencyName` | string | The name of a currency. | | `finance.currencySymbol` | string | The symbol of a currency, empty for some. | | `finance.ethereumAddress` | string | An Ethereum address (format-shaped, no checksum). | | `finance.iban` | string | An IBAN with valid ISO 13616 check digits. `country` (one of 27 codes): the ISO 3166-1 code of the country; the context's, or any, when not given. | | `finance.litecoinAddress` | string | A Litecoin address (format-shaped, no checksum). | | `finance.pin` | string | A PIN of digits. `length` (integer, 1 to 64, default `4`): the number of digits. | | `finance.routingNumber` | string | An ABA routing number with a valid checksum. | ### food | Provider | Returns | Description | | --- | --- | --- | | `food.alcoholicBeverage` | string | An alcoholic beverage. | | `food.category` | string | A food category. | | `food.dish` | string | The name of a dish. | | `food.fruit` | string | A fruit. | | `food.grain` | string | A grain. | | `food.meat` | string | A meat. | | `food.milkProduct` | string | A milk product. | | `food.nonAlcoholicBeverage` | string | A non-alcoholic beverage. | | `food.nut` | string | A nut. | | `food.oil` | string | A cooking oil. | | `food.seafood` | string | A seafood. | | `food.seed` | string | An edible seed. | | `food.sugarProduct` | string | A sugar product. | | `food.vegetable` | string | A vegetable. | ### git | Provider | Returns | Description | | --- | --- | --- | | `git.branch` | string | A branch name. `maxIssueNumber` (integer, 1 to 1000000000, default `100`): the highest issue number in a name. | | `git.commitDate` | string | A commit date as git prints it, in the local time of its offset. `maxYearsAgo` (integer, 1 to 1000, default `15`): how many years back. | | `git.commitEntry` | string | A commit as git log prints it. | | `git.commitMessage` | string | A commit message. | | `git.commitSha` | string | A commit hash of hexadecimal digits. `length` (integer, 1 to 40, default `40`): the number of digits. | ### hacker | Provider | Returns | Description | | --- | --- | --- | | `hacker.abbreviation` | string | A technical abbreviation. | | `hacker.adjective` | string | A technical adjective. | | `hacker.ingverb` | string | A technical verb ending in -ing. | | `hacker.noun` | string | A technical noun. | | `hacker.phrase` | string | A technical phrase. | | `hacker.verb` | string | A technical verb. | ### helpers | Provider | Returns | Description | | --- | --- | --- | | `helpers.fromPattern` | string | A string from a pattern of a subset of regular expressions. `pattern` (string, required): # a digit, ? a letter, * either, [A-Z0-9] a class, {n} or {min,max} a repetition, \ a literal character. Also `helpers.fromRegExp`. | | `helpers.replaceSymbols` | string | A pattern with its symbols replaced by random characters. `pattern` (string, required): # becomes a digit, ? a letter, * either. | ### image | Provider | Returns | Description | | --- | --- | --- | | `image.avatar` | string | The URL of a GitHub avatar. Also `image.avatarGitHub`, `internet.avatar`. | | `image.dimensions` | string | Image dimensions, e.g. 640x480. | | `image.type` | string | An image file type. | | `image.url` | string | The URL of a placeholder image. `width` (integer, 1 to 10000, default `640`): the width in pixels. `height` (integer, 1 to 10000, default `480`): the height in pixels. `category` (one of `animals`, `business`, `cats`, `city`, `food`, `nightlife`, `fashion`, `people`, `nature`, `sports`, `technics`, `transport`): a picture category, any when not given. Also `image.imageUrl`. | ### internet | Provider | Returns | Description | | --- | --- | --- | | `internet.domainName` | string | A domain name. | | `internet.domainSuffix` | string | A top-level domain. | | `internet.domainWord` | string | A word of a domain name. | | `internet.email` | string | An email address, from the names when given. `firstName` (string): the first name to use, a random one when not given. `lastName` (string): the last name to use, a random one when not given. `provider` (string): the host after @, a free mail provider when not given. | | `internet.emailProvider` | string | The domain of a free email provider. | | `internet.emoji` | string | An emoji. `type` (one of `smiley`, `body`, `person`, `nature`, `food`, `travel`, `activity`, `object`, `symbol`, `flag`): smiley, body, person, nature, food, travel, activity, object, symbol or flag; any when not given. | | `internet.exampleEmail` | string | An email address at an example domain. `firstName` (string): the first name to use, a random one when not given. `lastName` (string): the last name to use, a random one when not given. | | `internet.httpMethod` | string | An HTTP method. | | `internet.httpRequestHeader` | string | The name of an HTTP request header. | | `internet.httpResponseHeader` | string | The name of an HTTP response header. | | `internet.httpStatusCode` | integer | An HTTP status code. `type` (one of `informational`, `success`, `redirection`, `clientError`, `serverError`): informational, success, redirection, clientError or serverError; any when not given. | | `internet.ipv4` | string | An IPv4 address. `class` (one of `a`, `b`, `c`, default `c`): the address class a, b or c. Also `internet.ip`. | | `internet.ipv6` | string | An IPv6 address. | | `internet.mac` | string | A MAC address. `separator` (string, default `:`): between the bytes. | | `internet.mimeType` | string | A media type. | | `internet.password` | string | A password of letters, digits and symbols. `length` (integer, 1 to 256, default `15`): the number of characters. | | `internet.port` | integer | A port number. | | `internet.protocol` | string | http or https. | | `internet.url` | string | A URL. `protocol` (one of `http`, `https`, default `https`): http or https. | | `internet.username` | string | A username, from the names when given. `firstName` (string): the first name to use, a random one when not given. `lastName` (string): the last name to use, a random one when not given. Also `internet.userName`. | ### location | Provider | Returns | Description | | --- | --- | --- | | `location.address` | record | An address whose parts are of one country, with its code and a time zone, a record. `country` (one of 15 codes): the ISO 3166-1 code of the country of the address, the context's (or US) when not given. | | `location.buildingNumber` | string | A building number. `country` (one of 15 codes): the ISO 3166-1 code of the country of the address, the context's (or US) when not given. Also `address.buildingNumber`. | | `location.city` | string | A city. `country` (one of 15 codes): the ISO 3166-1 code of the country of the address, the context's (or US) when not given. Also `address.city`. | | `location.country` | string | The name of a country. Also `address.country`. | | `location.countryCode` | string | An ISO 3166-1 country code. Also `address.countryCode`. | | `location.county` | string | A county; FakerError for countries without counties. `country` (one of 15 codes, default `ES`): the ISO 3166-1 code of a country with counties: EE or ES. Also `address.county`. | | `location.direction` | string | A compass direction. | | `location.latitude` | string | A latitude, as text. `precision` (integer, 0 to 7, default `4`): the number of decimals. Also `address.latitude`. | | `location.longitude` | string | A longitude, as text. `precision` (integer, 0 to 7, default `4`): the number of decimals. Also `address.longitude`. | | `location.secondaryAddress` | string | An apartment or suite. `country` (one of 15 codes): the ISO 3166-1 code of the country of the address, the context's (or US) when not given. Also `address.secondaryAddress`. | | `location.state` | string | A state or region. `country` (one of 15 codes): the ISO 3166-1 code of the country of the address, the context's (or US) when not given. Also `address.state`. | | `location.street` | string | A street name. `country` (one of 15 codes): the ISO 3166-1 code of the country of the address, the context's (or US) when not given. Also `address.streetName`, `location.streetName`. | | `location.streetAddress` | string | A street with a building number. `country` (one of 15 codes): the ISO 3166-1 code of the country of the address, the context's (or US) when not given. Also `address.streetAddress`. | | `location.timeZone` | string | An IANA time zone. Also `address.timeZone`. | | `location.zipCode` | string | A postal code. `country` (one of 15 codes): the ISO 3166-1 code of the country of the address, the context's (or US) when not given. Also `address.zipCode`. | ### lorem | Provider | Returns | Description | | --- | --- | --- | | `lorem.paragraph` | string | A paragraph of placeholder text. `minSentences` (integer, 0 to 100, default `2`): the fewest sentences. `maxSentences` (integer, 0 to 100, default `6`): the most sentences. | | `lorem.paragraphs` | string | Paragraphs of placeholder text. `min` (integer, 0 to 100, default `2`): the fewest paragraphs. `max` (integer, 0 to 100, default `4`): the most paragraphs. | | `lorem.sentence` | string | A sentence of placeholder text. `minWords` (integer, 0 to 100, default `3`): the fewest words. `maxWords` (integer, 0 to 100, default `10`): the most words. | | `lorem.sentences` | string | Sentences of placeholder text. `min` (integer, 0 to 100, default `2`): the fewest sentences. `max` (integer, 0 to 100, default `6`): the most sentences. | | `lorem.slug` | string | Words joined by hyphens. `wordCount` (integer, 0 to 100, default `3`): the number of words. | | `lorem.word` | string | A word of placeholder text. Also `random.word`. | | `lorem.words` | string | Words of placeholder text. `count` (integer, 0 to 1000, default `3`): the number of words. Also `random.words`. | ### medicine | Provider | Returns | Description | | --- | --- | --- | | `medicine.condition` | string | A medical condition. | | `medicine.medicalTest` | string | A medical test. | | `medicine.specialty` | string | A medical specialty. | ### movie | Provider | Returns | Description | | --- | --- | --- | | `movie.actor` | string | The name of an actor. | | `movie.actress` | string | The name of an actress. | | `movie.director` | string | The name of a director. | | `movie.genre` | string | A film genre. | | `movie.title` | string | The title of a film. | | `movie.tvShow` | string | The title of a TV show. | ### music | Provider | Returns | Description | | --- | --- | --- | | `music.artist` | string | The name of a musical artist. | | `music.genre` | string | A musical genre. | | `music.songName` | string | The name of a song. | ### number | Provider | Returns | Description | | --- | --- | --- | | `number.float` | number | A number from min (included) to max (excluded). `min` (number, default `0`): the lowest number. `max` (number, default `1000`): the highest number. Also `datatype.float`. | | `number.hex` | string | A hexadecimal number. `min` (integer, 0 to 2147483647, default `0`): the lowest number. `max` (integer, 0 to 2147483647, default `15`): the highest number. | | `number.int` | integer | An integer from min to max, both included. `min` (integer, -9007199254740991 to 9007199254740991, default `0`): the lowest integer. `max` (integer, -9007199254740991 to 9007199254740991, default `1000`): the highest integer. Also `datatype.number`, `random.number`. | ### person | Provider | Returns | Description | | --- | --- | --- | | `person.bio` | string | A short biography. | | `person.chineseZodiac` | string | A Chinese zodiac sign. | | `person.firstName` | string | A first name. `sex` (one of `male`, `female`): male or female, either when not given. `country` (one of 61 codes): the ISO 3166-1 code of the country whose names to use, the context's when not given. Also `name.firstName`. | | `person.fullName` | string | A full name. `sex` (one of `male`, `female`): male or female, either when not given. `country` (one of 61 codes): the ISO 3166-1 code of the country whose names to use, the context's when not given. Also `name.findName`, `name.fullName`. | | `person.gender` | string | A gender identity. Also `name.gender`. | | `person.hobby` | string | A hobby. | | `person.jobArea` | string | An area of work. | | `person.jobDescriptor` | string | A descriptor of a job title. | | `person.jobTitle` | string | A job title. Also `name.jobTitle`. | | `person.jobType` | string | A kind of job. | | `person.language` | string | A language. | | `person.lastName` | string | A last name. `sex` (one of `male`, `female`): male or female, either when not given. `country` (one of 61 codes): the ISO 3166-1 code of the country whose names to use, the context's when not given. Also `name.lastName`. | | `person.middleName` | string | A middle name. `sex` (one of `male`, `female`): male or female, either when not given. Also `name.middleName`. | | `person.nationality` | string | A nationality. | | `person.prefix` | string | A name prefix, e.g. Mrs.. `sex` (one of `male`, `female`): male or female, either when not given. Also `name.prefix`. | | `person.profile` | record | A person whose sex, names, username, email and birth date belong together, a record. `sex` (one of `male`, `female`): male or female, either when not given. `country` (one of 61 codes): the ISO 3166-1 code of the country whose names to use, the context's when not given. | | `person.sex` | string | Male or Female. | | `person.ssn` | string | A national identification number: valid for PL, US, ES and GB, format-shaped for DE, FR, IT and IN. `country` (one of `PL`, `US`, `GB`, `DE`, `FR`, `IT`, `ES`, `IN`): the ISO 3166-1 code of the country; the context's, or any, when not given. | | `person.suffix` | string | A name suffix, e.g. Jr.. Also `name.suffix`. | | `person.zodiacSign` | string | A western zodiac sign. | ### phone | Provider | Returns | Description | | --- | --- | --- | | `phone.imei` | string | An IMEI with a valid Luhn check digit. | | `phone.manufacturer` | string | A phone manufacturer. | | `phone.modelName` | string | A phone model. | | `phone.number` | string | A phone number. `format` (string): a pattern whose # become digits, e.g. ###-###-####; a random format when not given. Also `phone.phoneNumber`. | | `phone.platform` | string | A mobile platform. | ### science | Provider | Returns | Description | | --- | --- | --- | | `science.chemicalElement` | string | The name of a chemical element. | | `science.currentUnit` | string | A unit of electric current. | | `science.distanceUnit` | string | A unit of distance. | | `science.massUnit` | string | A unit of mass. | | `science.temperatureUnit` | string | A unit of temperature. | | `science.timeUnit` | string | A unit of time. | | `science.unit` | string | A unit of measurement. | ### sport | Provider | Returns | Description | | --- | --- | --- | | `sport.athlete` | string | The name of an athlete. `sex` (one of `male`, `female`): male or female, either when not given. | | `sport.event` | string | A sport event. | | `sport.sport` | string | A sport. | | `sport.team` | string | A soccer team. | ### string | Provider | Returns | Description | | --- | --- | --- | | `string.alpha` | string | Letters. `length` (integer, 0 to 10000, default `1`): the number of characters. `casing` (one of `mixed`, `lower`, `upper`, default `mixed`): mixed, lower or upper. `exclude` (string): characters not to use. Also `random.alpha`. | | `string.alphanumeric` | string | Letters and digits. `length` (integer, 0 to 10000, default `1`): the number of characters. `casing` (one of `mixed`, `lower`, `upper`, default `mixed`): mixed, lower or upper. `exclude` (string): characters not to use. Also `random.alphaNumeric`, `string.alphaNumeric`. | | `string.binary` | string | Binary digits. `length` (integer, 0 to 10000, default `1`): the number of characters. | | `string.fromCharacters` | string | Characters picked from a set. `characters` (string, required): the characters to pick from. `length` (integer, 0 to 10000, default `1`): the number of characters. | | `string.hexadecimal` | string | Hexadecimal digits. `length` (integer, 0 to 10000, default `1`): the number of characters. `casing` (one of `lower`, `upper`, default `lower`): lower or upper. `prefix` (one of `0x`, `#`, nothing, default `0x`): 0x, # or nothing. Also `datatype.hexadecimal`. | | `string.numeric` | string | Decimal digits. `length` (integer, 0 to 10000, default `1`): the number of characters. `allowLeadingZeros` (boolean, default `true`): whether the first digit may be 0. Also `random.numeric`. | | `string.octal` | string | Octal digits. `length` (integer, 0 to 10000, default `1`): the number of characters. | | `string.sample` | string | Printable ASCII characters. `length` (integer, 0 to 10000, default `10`): the number of characters. | | `string.uuid` | string | A version 4 UUID. Also `datatype.uuid`, `random.uuid`. | ### system | Provider | Returns | Description | | --- | --- | --- | | `system.commonFileExt` | string | A common file extension. | | `system.commonFileName` | string | A file name with a common extension. `extension` (string): the extension, a common one when not given. | | `system.commonFileType` | string | A common file type. | | `system.cron` | string | A cron expression. | | `system.directoryPath` | string | A directory path. | | `system.fileExt` | string | A file extension of a media type. `type` (one of `video`, `audio`, `image`, `text`, `application`): video, audio, image, text or application; any when not given. | | `system.fileName` | string | A file name. | | `system.filePath` | string | A file path. | | `system.fileType` | string | A file type. | | `system.mimeType` | string | A media type. | | `system.networkInterface` | string | A network interface name. | | `system.semver` | string | A semantic version. | ### vehicle | Provider | Returns | Description | | --- | --- | --- | | `vehicle.bicycle` | string | A kind of bicycle. | | `vehicle.color` | string | A vehicle color. | | `vehicle.fuel` | string | A fuel type. | | `vehicle.manufacturer` | string | A vehicle manufacturer. | | `vehicle.model` | string | A vehicle model. | | `vehicle.type` | string | A kind of vehicle. | | `vehicle.vehicle` | string | A vehicle manufacturer and model. | | `vehicle.vin` | string | A vehicle identification number (format-shaped, no check digit). | | `vehicle.vrm` | string | A UK vehicle registration mark. | ### videoGame | Provider | Returns | Description | | --- | --- | --- | | `videoGame.genre` | string | A video game genre. | | `videoGame.platform` | string | A gaming platform. | | `videoGame.studioName` | string | A game studio. | | `videoGame.title` | string | The title of a video game. | ### weather | Provider | Returns | Description | | --- | --- | --- | | `weather.cloudCover` | integer | Cloud cover, percent. | | `weather.description` | string | A description of the weather. | | `weather.humidity` | integer | Relative humidity, percent. | | `weather.pressure` | number | Air pressure, hPa or inHg. `units` (one of `metric`, `imperial`, default `metric`): metric or imperial. | | `weather.temperature` | number | A temperature, Celsius or Fahrenheit. `units` (one of `metric`, `imperial`, default `metric`): metric or imperial. | | `weather.uvIndex` | integer | A UV index. | | `weather.visibility` | number | Visibility, km or miles. `units` (one of `metric`, `imperial`, default `metric`): metric or imperial. | | `weather.windSpeed` | number | Wind speed, km/h or mph. `units` (one of `metric`, `imperial`, default `metric`): metric or imperial. | ### word | Provider | Returns | Description | | --- | --- | --- | | `word.adjective` | string | An English adjective. `length` (integer, 1 to 100): the length of the word, any when not given. | | `word.adverb` | string | An English adverb. `length` (integer, 1 to 100): the length of the word, any when not given. | | `word.conjunction` | string | An English conjunction. `length` (integer, 1 to 100): the length of the word, any when not given. | | `word.interjection` | string | An English interjection. `length` (integer, 1 to 100): the length of the word, any when not given. | | `word.noun` | string | An English noun. `length` (integer, 1 to 100): the length of the word, any when not given. | | `word.preposition` | string | An English preposition. `length` (integer, 1 to 100): the length of the word, any when not given. | | `word.sample` | string | An English word. `length` (integer, 1 to 100): the length of the word, any when not given. | | `word.verb` | string | An English verb. `length` (integer, 1 to 100): the length of the word, any when not given. | | `word.words` | string | English words. `count` (integer, 0 to 1000, default `1`): the number of words. | --- # Compatibility Source: https://apigenie.pl/docs/reference/cli/compatibility See also: [Configuration](https://apigenie.pl/docs/reference/cli/configuration.md), [Formats](https://apigenie.pl/docs/reference/cli/formats.md), [Specification extensions](https://apigenie.pl/docs/reference/cli/extensions.md), [faker](https://apigenie.pl/docs/reference/cli/faker.md), [apigenie-mcp](https://apigenie.pl/docs/reference/cli/mcp.md). Scripts, CI jobs, Dockerfiles and dashboards call API Genie and read what it writes. This page says what they can rely on from one release to the next. From 1.0.0, `apigenie`, `apigenie-generator` and `apigenie-server` follow [semantic versioning](https://semver.org/spec/v2.0.0.html) for everything listed under [What the promise covers](#what-the-promise-covers): - a **patch** release (1.0.1) fixes bugs and changes nothing listed there; - a **minor** release (1.1.0) adds commands, options, settings and members, and may [deprecate](#deprecation) something, but keeps it working; - only a **major** release (2.0.0) removes or changes what is listed there. Two binaries, [`apigenie-catalog`](/docs/reference/catalog) and [`apigenie-mcp`](/docs/reference/cli/mcp), are experimental as a whole (see [What it doesn't cover](#what-it-doesnt-cover)) until they become stable. Versions below 1.0.0 make no such promise: the [changelog](https://github.com/mykulyak/api-genie/blob/main/CHANGELOG.md) lists what each one broke under "Upgrading". ## What the promise covers - **Command names and subcommands** of the three binaries: the commands of [`apigenie`](/docs/reference/cli), the targets of [`apigenie-generator`](/docs/reference/generator) (`client fetch`, `server spring`, ...), and [`apigenie-server`](/docs/reference/server). - **Option names and their meaning**: an option keeps its name, its short form, the values it accepts and what it does. A new option, or a new accepted value, is a minor change. - **Configuration keys and their schema**: the keys of [`apigenie.yaml`](/docs/reference/cli/configuration) and `apigenie-server.yaml`, their types and defaults, as the JSON Schema of each release (`https://apigenie.pl/schemas/apigenie-config/.json`) describes them. A file that is valid for 1.x stays valid for every later 1.y. - **Environment variables**: `APIGENIE_TELEMETRY_FILE`, the `APIGENIE_SERVER_*` variables of [`apigenie-server`](/docs/reference/server) (`HOST`, `PORT`, `TLS_CERT`, `TLS_KEY`, `CA_CERT`, `INSECURE`, `PROXY_TO`, `REPORT`, `REPORT_JUNIT`, `RECORD_DIR`, `RECORD_HAR`, `STUBS`, `PROTO_PATH`, `MQTT_PORT`), and `APIGENIE_MQTT_USERNAME` and `APIGENIE_MQTT_PASSWORD`. - **Exit statuses**: the [table](/docs/reference/cli#exit-status) shared by the three binaries. - **The `formatVersion` of each JSON report**: see [Versioned JSON outputs](#versioned-json-outputs) below. - **The docs bundle contract**: the layout of the bundle and its manifest `apigenie-docs.json` ([`apigenie-generator docs`](/docs/reference/generator/docs)), whose `apigenieDocs` and `formatVersion` say which `@mykulyak/apigenie-docs` versions can build it. - **The admin API of `apigenie-server`**: the paths and methods under `/__apigenie` listed in [Admin API](/docs/reference/server/dashboard#admin-api), and the JSON they answer with. New paths and new members are minor changes. - **The `x-apigenie-*` extensions the tools read**: `x-apigenie-lint-disable` ([lint](/docs/reference/cli/lint)), `x-apigenie-mock` and `x-apigenie-mock-faker` ([server](/docs/reference/server/scenarios)), and the `codegen` members of `x-apigenie` (`name`, `action-name`, `controller-name`, `disabled`) that the generators read ([Specification extensions](/docs/reference/cli/extensions) lists them with the others). ## What it doesn't cover - **The inside of generated code.** A generator keeps the options on its page and the shape of what it generates for your API: the names of the types, functions and routes. The generated files' layout, formatting, private helpers and comments, and the versions of the libraries they depend on, can change in a minor release, when a generator is fixed or improved. Commit generated code, or pin the API Genie version that generates it. - **Log and message text**: warnings, errors, progress lines and the text formatters (`stylish`, `compact`, `unix`, `visualstudio`, `html`, and the text and Markdown output of `diff` and `changelog`). Read the JSON reports, SARIF, checkstyle, TAP or JUnit XML instead. - **The wording of `--help`.** - **Experimental commands**: they say "(experimental, outside the 1.0 compatibility promise)" in their `--help` and on the first line they print, and the CLI overview lists them under [Experimental commands](/docs/reference/cli#experimental-commands). Their options and output can change, or they can go away, in a minor release. `apigenie-mcp`, whose standard output carries the protocol, says it only in its `--help`. When one becomes stable, the promise covers it from that release on. - **What a release fixes**: when API Genie accepted a document it shouldn't have, or reported a finding it shouldn't have, a minor or patch release can correct it, even though a script sees a different result. New lint rules in the built-in rulesets arrive in minor releases. ## Deprecation Something covered by the promise is removed or changed in two steps: 1. A **minor release announces it**: the changelog lists it under "Deprecated" with what to use instead, its reference page says so, and using it prints a one-line warning on the standard error (the standard output stays as it was). 2. It is **removed no earlier than the next minor release**, and only in a major release once 1.0 is out. The changelog lists the removal under "Removed" and "Upgrading". The rename of `apigenie-mock` to `apigenie-server` follows these rules: the `apigenie-mock` command, deprecated in 0.10, was removed in 1.0, and the other old names print a notice and keep working until 1.1 (see [Deprecated names](/docs/reference/server#deprecated-names)). ## Versions `apigenie`, `apigenie-generator`, `apigenie-server`, `apigenie-catalog` and (since 0.12.0) `apigenie-mcp` are built, released and installed together, always with the same version. `apigenie --version` prints its version on the first line and the versions of the others below it, so a mismatch shows. The [Docker images](/downloads), the npm package and the Homebrew formula carry that version too. Since 0.12.0 the **desktop editor** is released with the five binaries, at their version. The **VS Code extension** and the **docs package** (`@mykulyak/apigenie-docs`) are released on their own, each with its own version and changelog. This page covers the five binaries. The desktop editor shares their version but is not part of the promise above; the extension follows semantic versioning of its own version. ## Versioned JSON outputs Every JSON report of the CLI and the server has a top-level `formatVersion` member, an integer that started at 1, and a JSON Schema published on this site: | Output | Schema | | ------ | ------ | | [`apigenie lint --formatter json`](/docs/reference/cli/lint) | [`apigenie-lint-report.json`](https://apigenie.pl/schemas/apigenie-lint-report.json) | | [`apigenie diff --formatter json`](/docs/reference/cli/diff) (`status`, `changelog` and `detailed` reports) | [`apigenie-diff-report.json`](https://apigenie.pl/schemas/apigenie-diff-report.json) | | [`apigenie changelog --formatter json`](/docs/reference/cli/changelog) | [`apigenie-changelog-report.json`](https://apigenie.pl/schemas/apigenie-changelog-report.json) | | [`apigenie-catalog list --json`](/docs/reference/catalog) | [`apigenie-catalog-report.json`](https://apigenie.pl/schemas/apigenie-catalog-report.json) | | [`apigenie-catalog versions --json`](/docs/reference/catalog#apigenie-catalog-versions) | [`apigenie-catalog-versions-report.json`](https://apigenie.pl/schemas/apigenie-catalog-versions-report.json) | | [`apigenie-catalog release --json`](/docs/reference/catalog#apigenie-catalog-release) | [`apigenie-catalog-release-report.json`](https://apigenie.pl/schemas/apigenie-catalog-release-report.json) | | [`apigenie format --json`](/docs/reference/cli/format) | [`apigenie-format-report.json`](https://apigenie.pl/schemas/apigenie-format-report.json) | | [`apigenie init --json`](/docs/reference/cli/init) | [`apigenie-init-report.json`](https://apigenie.pl/schemas/apigenie-init-report.json) | | [`--json`](/docs/reference/cli#json-output) of a command without a report of its own | [`apigenie-status-report.json`](https://apigenie.pl/schemas/apigenie-status-report.json) | | [`apigenie test --report`](/docs/reference/cli/test) | [`apigenie-test-report.json`](https://apigenie.pl/schemas/apigenie-test-report.json) | | [`apigenie-server --report`, `GET /__apigenie/contract`, `GET /__apigenie/contract.json`](/docs/reference/server) | [`apigenie-contract-report.json`](https://apigenie.pl/schemas/apigenie-contract-report.json) | | [`apigenie-docs.json`](/docs/reference/generator/docs), the manifest of a docs bundle | [`apigenie-docs-manifest.json`](https://apigenie.pl/schemas/apigenie-docs-manifest.json) | The `apigenie test --formatter json` stream carries `formatVersion` in its `summary` line. The contract and test reports also have `version`, the former name of `formatVersion`; it is deprecated and will be removed in the next release. **Adding fields keeps the version; removing or changing one bumps it.** A new member, or a new value of a member documented as open (such as a new change type), keeps `formatVersion`, so readers should ignore members they don't know. Removing a member, renaming it, or changing its type or meaning increments `formatVersion`, and the schema of the new version is published next to the old one. After 1.0, a new `formatVersion` is a breaking change and waits for a major release. ### External formats SARIF, JUnit XML, checkstyle and TAP are defined elsewhere and keep their own versions: SARIF output says `"version": "2.1.0"`, and the others follow the formats their tools read. ## Reporting a break If a minor or patch release breaks something this page covers, it's a bug. Open an issue at [github.com/mykulyak/api-genie/issues](https://github.com/mykulyak/api-genie/issues) with the two versions (`apigenie --version`), the command line, and what it did before and after. The fix is a patch release that brings the old behaviour back. If something you rely on isn't listed here, ask for it in an issue too. --- # apigenie-mcp Source: https://apigenie.pl/docs/reference/cli/mcp See also: [Configuration](https://apigenie.pl/docs/reference/cli/configuration.md), [Formats](https://apigenie.pl/docs/reference/cli/formats.md), [Specification extensions](https://apigenie.pl/docs/reference/cli/extensions.md), [faker](https://apigenie.pl/docs/reference/cli/faker.md), [Compatibility](https://apigenie.pl/docs/reference/cli/compatibility.md). `apigenie-mcp` (since 0.12.0) gives coding agents the checks of the CLI as tools of the [Model Context Protocol](https://modelcontextprotocol.io): lint, breaking changes, changelogs, formatting, bundling and an outline of an API. It is installed next to `apigenie` by every archive and package, npm and Homebrew. `describe` reads the file itself; the other tools run `apigenie --json` for each call. `lint`, `check_breaking_changes`, `changelog` and `format` read the `apigenie.yaml` that the command finds from the directory of the file. > **(experimental, outside the 1.0 compatibility promise)** MCP is still moving: tool names, > arguments and results can change with it. Its `--help` says so; it prints nothing when it starts, > as the client reads its output. ## Usage ```sh apigenie-mcp [--allow-write] [--root DIR]... [--apigenie PATH] [--timeout SECONDS] apigenie-mcp --version | --credits | --license [LIBRARY] | --license-list ``` You don't run it yourself: the agent's client starts it and talks to it on the standard input and output. Add it to the client's MCP settings, for example in `.mcp.json` at the root of a repository for Claude Code: ```json { "mcpServers": { "api-genie": { "command": "apigenie-mcp", "args": [] } } } ``` Other clients take the same command and arguments in their own settings. ## Options | Option | Description | | ------ | ----------- | | `--allow-write` | Let `lint`, `format` and `bundle` write files. | | `--root DIR` | A directory the tools may work in, when the client gives no roots. Can be repeated; defaults to the current directory. | | `--apigenie PATH` | The `apigenie` binary to run. Defaults to the one next to `apigenie-mcp`, else the one in `PATH`. | | `--timeout SECONDS` | How long one run of `apigenie` may take (default 120). | ## Exit status | Status | Meaning | | ------ | ------- | | 0 | The client closed the standard input, which ends the session, or `--help`, `--version`, `--credits`, `--license` or `--license-list` printed its text. A tool that fails is a result of the call, not an exit status. | | 2 | `--timeout` isn't a positive number, a `--root` directory doesn't exist, the `--apigenie` binary doesn't exist (a bare name is looked up in `PATH`), or, without `--apigenie`, no `apigenie` is next to `apigenie-mcp` or in `PATH`, or another usage error. | See the [exit statuses](/docs/reference/cli#exit-status) shared by the five binaries; `apigenie-mcp` never exits with 1. ## Tools | Tool | Arguments | What it returns | | ---- | --------- | --------------- | | `lint` | `files`, `config`, (`fix`) | The [lint report](https://apigenie.pl/schemas/apigenie-lint-report.json): every problem with its rule, severity, line and column. | | `check_breaking_changes` | `file`, `base_file` or `base_ref`, `config` | The [diff report](https://apigenie.pl/schemas/apigenie-diff-report.json) of the file against an earlier version: another file, or the file at a git revision (`main`, `v1.2.0`, `HEAD~1`). | | `changelog` | `file`, `revisions`, `tag_pattern`, `from`, `to`, `config` | The [changelog report](https://apigenie.pl/schemas/apigenie-changelog-report.json) of the file through its git history. | | `format` | `file`, `config`, (`check`) | The [format report](https://apigenie.pl/schemas/apigenie-format-report.json), with the formatted text when the file isn't formatted. | | `bundle` | `file`, (`output`) | The file and the local files it references, as one document. | | `describe` | `file` | The outline of the API: names, without the schemas themselves (see [The outline](#the-outline)). | | Argument | Tools | Value | | -------- | ----- | ----- | | `files` | `lint` | Required: the files to lint, at least 1. | | `file` | all but `lint` | Required: the API description. | | `config` | `lint`, `check_breaking_changes`, `changelog`, `format` | The configuration file, inside the workspace. By default, the one found from the directory of the file (for `lint`, of the first file) up to the root of its repository. | | `base_file`, `base_ref` | `check_breaking_changes` | Exactly one: the earlier version as another file, or as the file at a git revision (a branch, a tag or a commit). | | `revisions` | `changelog` | `commits` (default): every commit that changes the file. `tags`: every release tag. | | `tag_pattern` | `changelog` | With `revisions: tags`: the glob of the release tags, e.g. `v*` (default `*`, every tag). | | `from`, `to` | `changelog` | The revision the changelog starts after (default: the first version of the file) and the last one (default: `HEAD`). Only committed versions are compared. | | `fix` | `lint`, with `--allow-write` | `true` applies the fixes in the files (default `false`). | | `check` | `format`, with `--allow-write` | `true` (default) leaves the file alone; `false` formats it in place. | | `output` | `bundle`, with `--allow-write` | The file to write the bundle to; its extension selects JSON or YAML for an OpenAPI, Swagger or AsyncAPI document. | The result of `lint`, `check_breaking_changes`, `changelog` and `format` starts with a sentence that sums up the report ("1 breaking change, 0 non-breaking and 2 non-functional. The check fails: clients of the earlier version may break."). The report follows as structured content and as JSON text. When the file isn't formatted and `check` is `true`, `format` adds the formatted text as an embedded resource; with `check: false` it rewrites the file and the sentence says so. `bundle` returns a sentence and the bundled document as an embedded resource, or only the sentence when it writes to `output`. `describe` returns the outline as structured content and as JSON text, with no sentence. Findings are ordinary results. A file that can't be read is a result marked as an error, with the messages of the command. ## The outline | Family | Members | | ------ | ------- | | OpenAPI, Swagger 2.0 | `specVersion`, `title`, `version`, `servers` (URLs; Swagger: host and base path), `operations` (`method`, `path`, `operationId`, `summary`, `tags`, `deprecated`), `schemas` (names) | | AsyncAPI 3.0, 3.1 | `specVersion`, `title`, `version`, `servers` (`name`, `host`, `protocol`), `channels` (`name`, `address`), `operations` (`name`, `action`, `channel`, `summary`), `messages` (names) | | Protobuf | `syntax`, `package`, `services` (`name`, `methods`: `name`, `input`, `output`, `clientStreaming`, `serverStreaming`), `messages`, `enums` (full names) | | GraphQL | `operations` (`type`: `query`, `mutation` or `subscription`; `name`: the field), `types` (`name`, `kind`) | Each outline also has `file`, `family` (`openapi`, `swagger`, `asyncapi`, `protobuf` or `graphql`) and `issues` (`severity`, `message`, `line`). An AsyncAPI 2.x document has no outline: `describe` returns a result marked as an error. `tags`, `deprecated`, `clientStreaming` and `serverStreaming` are left out when empty or false; the `issues` of an OpenAPI or Swagger outline are always empty. ## Writing files Without `--allow-write` no tool writes into the workspace: `format` and `bundle` return the document instead, and the arguments in parentheses above don't exist. With it, `lint` takes `fix`, `format` takes `check: false` to format the file in place, and `bundle` takes an `output` file. ## Where files may be The workspace is the roots the client gives, else the `--root` directories, else the directory the server runs in. A relative path is resolved against the first directory of the workspace, and an absolute path must be inside one of them. A path outside them is refused before anything runs. A client of MCP revision 2025-11-25 or later gets a result marked as an error; an older one gets a JSON-RPC "invalid params" error (-32602). Arguments the input schema rules out get the same answers. Everything the commands read stays inside the workspace too. A file that an OpenAPI, Swagger or AsyncAPI description references with `$ref` can't be read outside it, nor can a Protobuf import or a configured dictionary or import directory. The command fails on it. Two exceptions keep a workspace that is a directory of a larger repository working: - **The configuration file above the workspace.** The tools look for the configuration file as the commands do: from the directory of the file up to the root of its git repository, or of the file system outside a repository. The tools use the file they find even when it is above the workspace, such as the `apigenie.yaml` that [`apigenie init`](/docs/reference/cli/init) writes at the root of a repository. Only that file: a ruleset or a dictionary it names must be inside the workspace. - **The git repository the workspace is in.** `check_breaking_changes` with `base_ref` and `changelog` read the history of the repository, wherever it keeps it. A `.git` that leads out of the workspace is read only when it is the `.git` file of a worktree (`git worktree add`) or a submodule. A `.git` that leads to another repository is refused with a result marked as an error, and so are a `commondir` or `objects/info/alternates` that lead out. A partial clone (`git clone --filter=...`) whose `.git` is in the workspace is refused the same way, as it fetches missing objects by running what its configuration names. ## Configuration `apigenie-mcp` has no settings in `apigenie.yaml`; the tools read the file as the commands do (see [Where files may be](#where-files-may-be)). ## See also - [Work with AI agents](/docs/guides/work-with-ai-agents): the instructions and the loop of an agent that edits API descriptions. - [`apigenie init`](/docs/reference/cli/init): `apigenie.yaml` and the section of `AGENTS.md`. - [JSON output](/docs/reference/cli#json-output): the reports the tools return. --- # apigenie-generator Source: https://apigenie.pl/docs/reference/generator See also: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). `apigenie-generator` generates code and data from an OpenAPI or AsyncAPI document, servers from a GraphQL schema, gRPC code from a Protobuf file set, documentation sites from OpenAPI, Swagger, AsyncAPI, GraphQL and Protobuf files, and validation schemas from JSON Schemas. It is a separate executable, installed next to `apigenie` by every package, the npm package and the Docker image (run it there with `docker run --entrypoint apigenie-generator mykulyak/apigenie ...`). Before 0.9.0 the generators were the `apigenie generate` command: `apigenie generate client fetch ...` is now `apigenie-generator client fetch ...`, with the same options and configuration. ## Usage ```sh apigenie-generator GENERATOR [TARGET] [...OPTIONS] INPUT_FILE apigenie-generator --version | --credits | --license [LIBRARY] | --license-list ``` `client go`, `client csharp`, `client java`, `client python`, `server go`, `server spring` and `server aspnet` read both kinds of documents: the generator is picked by the document, OpenAPI (3.0, 3.1, 3.2) or AsyncAPI (3.x). Since 0.12.0, the client and server generators of OpenAPI documents also read Swagger 2.0 documents (see [Swagger 2.0 input](#swagger-20-input)). `server absinthe` reads a GraphQL schema (`.graphql`, `.graphqls` or `.gql`). Every code generator takes `-c, --config` (a configuration file, see [Configuration](/docs/reference/cli/configuration)), `-o, --output` (the output directory) and `--package-name` / `--package-version`; several take generator options as `-p name=value`. The pages below list the options of each target. ## Swagger 2.0 input Since 0.12.0, the client and server generators of OpenAPI documents read Swagger 2.0 documents too. They convert the document in memory to OpenAPI 3.2, as [`apigenie convert --to openapi32`](/docs/reference/cli/convert) does, and generate from the result. The `convert` command is [experimental](/docs/reference/cli#experimental-commands): the converted document can change between releases, while the code generated from it follows the [compatibility](/docs/reference/cli/compatibility) of each target. The in-memory conversion differs from the command in three ways: - **Polymorphism becomes a union.** A definition with a `discriminator` becomes the `oneOf` of its shapes, so the generators write a type or a class per shape; one that extends another definition with a discriminator stays an object, with a warning. The union keeps only its `title`, `description`, `discriminator` and `x-` extensions other than `x-nullable`. When some of the definitions extending it with `allOf` have an `x-discriminator-value`, only those are shapes, and their values are the discriminator's `mapping`. Without values, every definition extending it is a shape, told apart by its name. A shape gets the base's other keywords (`type`, `properties`, `required`, ...) in place of the reference. A definition that isn't a shape keeps the reference, so it combines the union with its own keywords. - **What it approximates or repairs is reported.** Each is a warning at its position in the Swagger document. - **A reference to another document is an error.** The command copies it unchanged; the generators stop with exit status 2 and generate nothing. Bundle the document first with [`apigenie bundle`](/docs/reference/cli/bundle). For example, with two definitions extending `Pet`: ```yaml definitions: Pet: type: object discriminator: kind required: [kind, name] properties: { kind: { type: string }, name: { type: string } } Cat: x-discriminator-value: cat allOf: - $ref: '#/definitions/Pet' - { type: object, properties: { indoor: { type: boolean } } } Dog: x-discriminator-value: dog allOf: - $ref: '#/definitions/Pet' - { type: object, properties: { breed: { type: string } } } ``` `client fetch` generates `Pet` as the union of `Cat` and `Dog`, told apart by `kind`: ```ts export type Pet = Cat | Dog; export type Cat = { kind: string; name: string } & { indoor?: boolean }; export type Dog = { kind: string; name: string } & { breed?: string }; ``` A warning names the file, line and column, e.g. `swagger.yaml:7:7 warning the schemes of an operation have no counterpart and are dropped`. The generators' own warnings point to the Swagger document too. A document with a `swagger` version other than `2.0` is rejected (`Unsupported Swagger version '1.2' in 'swagger.yaml', expected 2.0`), and one that isn't a valid Swagger 2.0 document is rejected with its problems listed (`Errors reading Swagger file`); both exit with status 2. Overlays given with `--overlay` apply to the Swagger document before it is converted, so their targets follow its structure, e.g. `$.definitions.Pet`. Swagger 2.0 can't express some of what the conformance fixture checks, such as callbacks, cookie parameters or a body schema per media type; the [conformance results](/docs/reference/generator/conformance) mark those features as out of scope for 2.0. ## Conformance checks The codegen conformance suite checks the generators at three levels: 1. **Snapshots and features.** Each generator's test suite generates from the shared fixtures, compares the output byte for byte with its snapshots, and checks each feature of the fixture against the target's manifest, which also lists the features the target doesn't support yet. 2. **Type checking and linting.** The generated code goes through the target language's type checker and linter, with pinned versions. 3. **Contract tests.** A generated client calls every operation of the fixture through the validating proxy, and a generated server receives generated requests and a hand-written request set; the traffic is validated against the fixture. Event-driven targets run against brokers. The fixtures model the fictional Carpet Express shipping service. Its [OpenAPI 3.1 definition](/samples/carpet-express.openapi-31.yaml) and [AsyncAPI 3.0 definition](/samples/carpet-express.asyncapi.yaml) are available as downloads. The suite generates from the OpenAPI 3.2 document. Level 1 runs on its 3.1, 3.0 and, since 0.12.0, Swagger 2.0 variants too; at Levels 2 and 3 they serve to look into a target whose 3.2 output fails early. Levels 2 and 3 run in the release gate on Linux, which a release can't skip: every generated client and server with Level 3 runs in contract tests before a release. The [conformance results](/docs/reference/generator/conformance) show each target's results, for the latest release and the development version, and the features the targets don't support yet with the reasons their manifests give; each target's page has the same in its Verification section. Coverage varies by target, and a snapshot match is not a guarantee of complete standard support. Each target has a [support tier](/docs/reference/generator/conformance#tiers), shown at the top of its page. Tier 1 targets go through all three levels, and their unsupported features are worked on first; today they are nine OpenAPI clients and servers. Tier 2 targets go through the same three levels and can leave features unsupported. The [MCP server](/docs/reference/generator/server-mcp) is a Tier 2 target labelled experimental, because MCP and its SDK are still changing. The [Zod generator](/docs/reference/generator/schema-zod), the [Rust client](/docs/reference/generator/client-rust) and the [axum server](/docs/reference/generator/server-axum) are experimental: they have no Level 3 contract tests yet. ## Overlays Every target reading OpenAPI or AsyncAPI documents takes `--overlay FILE`: an [OpenAPI Overlay](/docs/reference/cli/overlay) (1.0 to 1.2) applied to the input before generating. Repeat it to apply several, in order. The vendor extensions a target reads (each target's page lists them, and [Specification extensions](/docs/reference/cli/extensions) lists them all) can then live in an overlay of that target instead of in the API description: ```sh apigenie-generator server spring openapi.yaml --overlay spring.overlay.yaml -o server ``` - The overlays listed under `commands.generate..overlay` in the [configuration file](/docs/reference/cli/configuration#commandsgenerate), relative to it, apply first, then the `--overlay` ones. - An AsyncAPI document that references other files is bundled before the overlays apply. - An action whose target selects nothing prints a warning with its position, e.g. `spring.overlay.yaml:12:5: action #3 ($.paths['/pickups'].get) selects no nodes.`. With `--strict` it is an error: nothing is generated and the exit status is 2. - Warnings and errors about a value an overlay set point at the overlay (`spring.overlay.yaml:9:9 Warning ...`); the others keep their line in the input. `docs`, which reads several inputs, and the targets of GraphQL schemas and `.proto` files don't; for `docs`, apply the overlays with [`apigenie overlay`](/docs/reference/cli/overlay) first. ## Check that generated code is up to date Every target of `client`, `server` and `schema` takes `--check` (since 0.12.0): the generator runs as usual but keeps what it writes in memory, compares each file with the one in the output directory, and writes nothing. The files that would be created or changed are printed on standard output, one per line, relative to the current directory, after the generator's messages. When there are any, a summary follows on standard error and the exit status is 1; otherwise the exit status is 0. With `--json`, the status report holds the list in `output` and the summary in `messages`. After a value is added to an enum of the document: ```sh apigenie-generator client fetch openapi.yaml -o client --check ``` ```text client/src/types.ts 1 generated file(s) would change and 0 would be created. ``` - The generator sees the output directory as it is, so the files it writes only when they are missing (each target's page names them, for example the controllers of `server spring`) are left out of the comparison once they exist. - Files in the output directory that the generator doesn't write are not compared: a file left behind by an operation removed from the document is not reported. Delete the output directory before generating to drop such files. - Generating twice from the same input, configuration and generator version gives the same bytes: the files hold no date and no absolute path. A new generator version can change the files: `client java` and `server spring` write the version in the `comments` element of `@Generated`. Since 0.12.0 `client java` and `server spring` leave the date out of `@Generated`. `hideGenerationTimestamp: false` brings it back, with the date of `generationTimestamp` when it is set. [Generate a client and a server](/docs/guides/generate-a-client-and-a-server#check-the-generated-code-in-ci) runs the check in a pull request. ## Exit status `apigenie-generator` exits with 0 when the code was generated and with 2 when the options, the configuration, an overlay or the input document can't be used (with `--strict`, also when an overlay action selects nothing), or no generator is named (`apigenie-generator` or `apigenie-generator client` alone print the help). With `--check` it exits with 1 when a file would be created or changed; see the [exit statuses](/docs/reference/cli#exit-status) shared by the five binaries. `apigenie generate ...` exits with 2 and prints the `apigenie-generator` command to run instead. `schema zod`, `client rust` and `server axum` are [experimental](/docs/reference/cli#experimental-commands). ## From OpenAPI ### Clients | Name | Summary | | ---- | ------- | | [client csharp](/docs/reference/generator/client-csharp) | C# client for `HttpClient` (.NET 8) | | [client elixir](/docs/reference/generator/client-elixir) | Elixir client on Req | | [client fetch](/docs/reference/generator/client-fetch) | TypeScript client for the Fetch API | | [client go](/docs/reference/generator/client-go) | Go client for `net/http` | | [client java](/docs/reference/generator/client-java) | Java client for Spring `RestClient`, `RestTemplate`, OpenFeign or HTTP interfaces | | [client python](/docs/reference/generator/client-python) | Python client on httpx and Pydantic | | [client rust](/docs/reference/generator/client-rust) | Rust client crate on reqwest and serde (experimental) | | [client swift](/docs/reference/generator/client-swift) | Swift client on URLSession (experimental) | ### Servers | Name | Summary | | ---- | ------- | | [server aspnet](/docs/reference/generator/server-aspnet) | ASP.NET Core server (Minimal APIs) | | [server axum](/docs/reference/generator/server-axum) | Rust server crate on axum (experimental) | | [server express](/docs/reference/generator/server-express) | TypeScript Express server | | [server fastapi](/docs/reference/generator/server-fastapi) | Python FastAPI server | | [server go](/docs/reference/generator/server-go) | Go `net/http` server | | [server hummingbird](/docs/reference/generator/server-hummingbird) | Swift server on Hummingbird 2 (experimental) | | [server mcp](/docs/reference/generator/server-mcp) | MCP server in TypeScript: a tool per operation (experimental) | | [server orpc](/docs/reference/generator/server-orpc) | TypeScript server on oRPC | | [server phoenix](/docs/reference/generator/server-phoenix) | Elixir Phoenix 1.7 server | | [server spring](/docs/reference/generator/server-spring) | Spring Boot server | | [server vapor](/docs/reference/generator/server-vapor) | Swift server on Vapor 4 (experimental) | ### Documentation and data | Name | Summary | | ---- | ------- | | [docs](/docs/reference/generator/docs) | a documentation site; also from Swagger 2.0, AsyncAPI, GraphQL and Protobuf files, several at once | | [data](/docs/reference/generator/data) | example data for a schema of the document | ## From AsyncAPI | Name | Summary | | ---- | ------- | | [client csharp](/docs/reference/generator/client-csharp-asyncapi) | C# Kafka client library | | [client elixir](/docs/reference/generator/client-elixir-asyncapi) | Elixir client library (WebSocket channels on Mint.WebSocket, Kafka on brod) | | [client go](/docs/reference/generator/client-go-asyncapi) | Go Kafka client package | | [client java](/docs/reference/generator/client-java-asyncapi) | Java Kafka client library on the Apache Kafka client | | [client kafkajs](/docs/reference/generator/client-kafkajs) | TypeScript Kafka client on KafkaJS | | [client python](/docs/reference/generator/client-python-asyncapi) | Python asyncio Kafka client on aiokafka | | [client ws](/docs/reference/generator/client-ws) | TypeScript WebSocket client | | [server aspnet](/docs/reference/generator/server-aspnet-asyncapi) | ASP.NET Core Kafka application | | [server faststream](/docs/reference/generator/server-faststream) | Python FastStream application (Kafka, RabbitMQ, MQTT) | | [server go](/docs/reference/generator/server-go-asyncapi) | Go Kafka application | | [server kafkajs](/docs/reference/generator/server-kafkajs) | TypeScript Kafka application on KafkaJS | | [server phoenix](/docs/reference/generator/server-phoenix-asyncapi) | Elixir Phoenix application (WebSocket channels, Kafka on Broadway and brod) | | [server spring](/docs/reference/generator/server-spring-asyncapi) | Spring Boot Kafka application | | [server ws](/docs/reference/generator/server-ws) | Node.js WebSocket server | ## From GraphQL | Name | Summary | | ---- | ------- | | [server absinthe](/docs/reference/generator/server-absinthe) | Elixir Absinthe server of the schema (`import_sdl`) | ## From Protobuf | Name | Summary | | ---- | ------- | | [client elixir](/docs/reference/generator/client-elixir-protobuf) | Elixir gRPC client on elixir-grpc | | [server elixir-grpc](/docs/reference/generator/server-elixir-grpc) | Elixir gRPC server on elixir-grpc | ## From JSON Schema | Name | Summary | | ---- | ------- | | [schema zod](/docs/reference/generator/schema-zod) | Zod schemas | --- # Conformance results Source: https://apigenie.pl/docs/reference/generator/conformance Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). The results of the codegen conformance suite for each target of `apigenie-generator`, on the Carpet Express fixture. A ✗ is a feature or a check that fails today; the manifests' reasons are at the end of the page. The [overview](/docs/reference/generator#conformance-checks) describes the three levels. Level 1 runs with the rest of the test suite, on Linux, macOS and Windows, and generates the OpenAPI targets from the 3.2 document and its 3.1, 3.0 and, since 0.12.0, Swagger 2.0 variants; a feature the Swagger 2.0 variant can't express is out of scope there. Levels 2 and 3 need each target's toolchain and, for the event-driven targets, a broker, so they run on the 3.2 document in the release gate on Linux, which a release can't skip. The page shows two sets of results: the latest release's, from its gate run, and the development version's, from which this site is built. The development version's results are also published as data: [`docs/codegen_conformance.json`](https://github.com/mykulyak/api-tools/blob/main/docs/codegen_conformance.json). A release can carry its results among its assets, as `codegen-conformance-.json`; a release without that file, such as 0.11.1, shows no results on this page. Each target also has a support tier, which says whether its unsupported features are worked on first and whether every level runs on it. The Tiers section below defines the tiers and lists the targets in each. Both tables show each target's tier today, so the release's table can show a tier the target didn't have at that release. ## Tiers Each target has a support tier. The tier says which levels of the conformance suite run on the target, and whether its unsupported features are worked on first: - **Tier 1.** Goes through all three levels before every release, with the goal of supporting every feature of the fixture. Its unsupported features are worked on first. - **Tier 2.** Goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. - **Experimental.** Isn't run at every level yet. It is outside the [1.0 compatibility promise](/docs/reference/cli/compatibility): its options and the shape of its output can change, or it can go away, in a minor release. - **Tier 2, labelled experimental.** Goes through all three levels like Tier 2, but follows a specification and SDK that are still changing. It is outside the [1.0 compatibility promise](/docs/reference/cli/compatibility): its options and the shape of its output can change, or it can go away, in a minor release. | Tier | Standard | Targets | | --- | --- | --- | | Tier 1 | OpenAPI | [`client csharp`](/docs/reference/generator/client-csharp), [`client fetch`](/docs/reference/generator/client-fetch), [`client go`](/docs/reference/generator/client-go), [`client java`](/docs/reference/generator/client-java), [`client python`](/docs/reference/generator/client-python), [`server aspnet`](/docs/reference/generator/server-aspnet), [`server fastapi`](/docs/reference/generator/server-fastapi), [`server go`](/docs/reference/generator/server-go), [`server spring`](/docs/reference/generator/server-spring) | | Tier 2 | OpenAPI | [`client elixir`](/docs/reference/generator/client-elixir), [`server express`](/docs/reference/generator/server-express), [`server mcp` (labelled experimental)](/docs/reference/generator/server-mcp), [`server orpc`](/docs/reference/generator/server-orpc), [`server phoenix`](/docs/reference/generator/server-phoenix) | | Tier 2 | AsyncAPI | [`client csharp`](/docs/reference/generator/client-csharp-asyncapi), [`client elixir`](/docs/reference/generator/client-elixir-asyncapi), [`client go`](/docs/reference/generator/client-go-asyncapi), [`client java`](/docs/reference/generator/client-java-asyncapi), [`client kafkajs`](/docs/reference/generator/client-kafkajs), [`client python`](/docs/reference/generator/client-python-asyncapi), [`client ws`](/docs/reference/generator/client-ws), [`server aspnet`](/docs/reference/generator/server-aspnet-asyncapi), [`server faststream`](/docs/reference/generator/server-faststream), [`server go`](/docs/reference/generator/server-go-asyncapi), [`server kafkajs`](/docs/reference/generator/server-kafkajs), [`server phoenix`](/docs/reference/generator/server-phoenix-asyncapi), [`server spring`](/docs/reference/generator/server-spring-asyncapi), [`server ws`](/docs/reference/generator/server-ws) | | Tier 2 | GraphQL | [`server absinthe`](/docs/reference/generator/server-absinthe) | | Tier 2 | Protobuf | [`client elixir`](/docs/reference/generator/client-elixir-protobuf), [`server elixir-grpc`](/docs/reference/generator/server-elixir-grpc) | | Experimental | OpenAPI | [`client rust`](/docs/reference/generator/client-rust), [`client swift`](/docs/reference/generator/client-swift), [`schema zod`](/docs/reference/generator/schema-zod), [`server axum`](/docs/reference/generator/server-axum), [`server hummingbird`](/docs/reference/generator/server-hummingbird), [`server vapor`](/docs/reference/generator/server-vapor) | ## Release 0.12.0 The release gate of 0.12.0 ran all three levels on Linux before the release. ### OpenAPI | Target | Tier | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | --- | | `client csharp` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (.NET SDK 8.0.204) | ✓ 37 of 37 operations pass (dotnet) | | `client elixir` | Tier 2 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 37 of 37 operations pass (elixir) | | `client fetch` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 29 supported, 0 not yet, 5 not checked | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8) | ✓ 40 of 40 operations pass (node) | | `client go` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (go version go1.22.5 linux/amd64) | ✓ 37 of 37 operations pass (go) | | `client java` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | ✓ 39 of 39 operations pass (java) | | `client python` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (python 3.12.11 httpx 0.28.1 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | ✓ 38 of 38 operations pass (python) | | `client rust` | Experimental | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (rustc 1.99.1 (58cf8f9c3 2026-10-13)) | not run yet | | `client swift` | Experimental | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (Swift version 6.0.3 (swift-6.0.3-RELEASE)) | ✓ 37 of 37 operations pass (swift) | | `server express` | Tier 2 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet, 1 not checked | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, Express 5) | ✓ 72 of 77 operations pass (node) | | `server fastapi` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | ✓ pass (python 3.12.11 fastapi 0.142.2 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | ✓ 72 of 77 operations pass (python) | | `server go` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | ✓ pass (go version go1.22.5 linux/amd64) | ✓ 70 of 77 operations pass, 2 known failures (go) | | `server hummingbird` | Experimental | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | ✓ pass (Swift version 6.0.3 (swift-6.0.3-RELEASE)) | ✓ 70 of 77 operations pass, 2 known failures (swift) | | `server mcp` | Tier 2, experimental | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 34 supported, 1 not yet, 2 not checked | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, @modelcontextprotocol/server 2) | ✓ 38 of 39 operations pass, 1 known failure (node) | | `server orpc` | Tier 2 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 38 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, oRPC 1) | ✓ 72 of 77 operations pass (node) | | `server phoenix` | Tier 2 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 38 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 70 of 77 operations pass, 2 known failures (elixir) | | `server aspnet` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | ✓ pass (.NET SDK 8.0.204) | ✓ 70 of 77 operations pass, 2 known failures (dotnet) | | `server axum` | Experimental | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 2 not yet | ✓ pass (rustc 1.99.1 (58cf8f9c3 2026-10-13)) | not run yet | | `server spring` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 45 supported, 0 not yet, 1 not checked | ✓ pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | ✓ 70 of 77 operations pass, 2 known failures (java) | | `server vapor` | Experimental | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | ✓ pass (Swift version 6.0.3 (swift-6.0.3-RELEASE)) | ✓ 70 of 77 operations pass, 2 known failures (swift) | | `schema zod` | Experimental | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 11 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, zod 4) | not run yet | | `docs` | · | ✓ 4 files, 38 operations | · | · | | `data` | · | ✓ 3 values each of Shipment, Address, HandlingUnit, StorageLocation, Pickup, TrackingEvent | · | · | ### AsyncAPI | Target | Tier | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | --- | | `client ws` | Tier 2 | ✓ snapshots of 3.0; 32 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8) | ✓ 3 of 3 operations pass (node) | | `server ws` | Tier 2 | ✓ snapshots of 3.0; 30 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8) | ✓ 4 of 4 operations pass (node) | | `server kafkajs` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | ✓ 7 of 7 operations pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | | `server kafkajs (counterpart)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | ✓ 7 of 7 operations pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | | `client kafkajs` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | ✓ 14 of 14 operations pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | | `client kafkajs (application)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | ✓ 14 of 14 operations pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | | `server faststream` | Tier 2 | ✓ snapshots of 3.0; 50 supported, 0 not yet | ✓ pass (python 3.12.11 faststream 0.7.7 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | ✓ 10 of 10 operations pass (python 3.12.11 faststream 0.7.7 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | | `server spring` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | ✓ 5 of 5 operations pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | | `server go` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (go version go1.22.5 linux/amd64) | ✓ 7 of 7 operations pass (go version go1.22.5 linux/amd64) | | `server go (counterpart)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (go version go1.22.5 linux/amd64) | ✓ 7 of 7 operations pass (go version go1.22.5 linux/amd64) | | `client go` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (go version go1.22.5 linux/amd64) | ✓ 14 of 14 operations pass (go version go1.22.5 linux/amd64) | | `client go (application)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (go version go1.22.5 linux/amd64) | ✓ 14 of 14 operations pass (go version go1.22.5 linux/amd64) | | `server aspnet` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (.NET SDK 8.0.204) | ✓ 7 of 7 operations pass (.NET SDK 8.0.204) | | `server aspnet (counterpart)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (.NET SDK 8.0.204) | ✓ 7 of 7 operations pass (.NET SDK 8.0.204) | | `client csharp` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (.NET SDK 8.0.204) | ✓ 15 of 15 operations pass (.NET SDK 8.0.204) | | `client csharp (application)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (.NET SDK 8.0.204) | ✓ 15 of 15 operations pass (.NET SDK 8.0.204) | | `client java` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | ✓ 14 of 14 operations pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | | `client java (application)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | ✓ 14 of 14 operations pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | | `client python` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (python 3.12.11 aiokafka 0.14.0 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | ✓ 13 of 13 operations pass (python 3.12.11 aiokafka 0.14.0 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | | `client python (application)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (python 3.12.11 aiokafka 0.14.0 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | ✓ 13 of 13 operations pass (python 3.12.11 aiokafka 0.14.0 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | | `server phoenix` | Tier 2 | ✓ snapshots of 3.0; 41 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 11 of 11 operations pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | | `server phoenix (counterpart)` | Tier 2 | ✓ snapshots of 3.0; 30 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 11 of 11 operations pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | | `client elixir` | Tier 2 | ✓ snapshots of 3.0; 41 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 18 of 18 operations pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | | `client elixir (application)` | Tier 2 | ✓ snapshots of 3.0; 26 supported, 0 not yet, 4 not checked | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 18 of 18 operations pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ### GraphQL | Target | Tier | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | --- | | `server absinthe` | Tier 2 | ✓ snapshots of graphql; 22 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 39 of 39 operations pass (elixir) | ### Protobuf | Target | Tier | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | --- | | `client elixir` | Tier 2 | ✓ snapshots of proto3; 42 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 24 of 24 operations pass (elixir) | | `server elixir-grpc` | Tier 2 | ✓ snapshots of proto3; 42 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 31 of 31 operations pass (elixir) | ## Development version Level 1 comes from the test suite at this version. Levels 2 and 3 need each target's toolchain and run in the release gate, so their columns say which targets they cover and the failures they expect. ### OpenAPI | Target | Tier | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | --- | | `client csharp` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | runs before a release | | `client elixir` | Tier 2 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | runs before a release | | `client fetch` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 29 supported, 0 not yet, 5 not checked | runs before a release | runs before a release | | `client go` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | runs before a release | | `client java` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | runs before a release | | `client python` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | runs before a release | | `client rust` | Experimental | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | not run yet | | `client swift` | Experimental | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | runs before a release | | `server express` | Tier 2 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet, 1 not checked | runs before a release | runs before a release | | `server fastapi` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | runs before a release | runs before a release | | `server go` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | runs before a release | runs before a release, 2 known failures | | `server hummingbird` | Experimental | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | runs before a release | runs before a release, 2 known failures | | `server mcp` | Tier 2, experimental | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 34 supported, 1 not yet, 2 not checked | runs before a release | runs before a release, 1 known failure | | `server orpc` | Tier 2 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 38 supported, 0 not yet | runs before a release | runs before a release | | `server phoenix` | Tier 2 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 38 supported, 0 not yet | runs before a release | runs before a release, 2 known failures | | `server aspnet` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | runs before a release | runs before a release, 2 known failures | | `server axum` | Experimental | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 2 not yet | runs before a release | not run yet | | `server spring` | Tier 1 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 45 supported, 0 not yet, 1 not checked | runs before a release | runs before a release, 2 known failures | | `server vapor` | Experimental | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | runs before a release | runs before a release, 2 known failures | | `schema zod` | Experimental | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 11 supported, 0 not yet | runs before a release | not run yet | | `docs` | · | ✓ 4 files, 38 operations | · | · | | `data` | · | ✓ 3 values each of Shipment, Address, HandlingUnit, StorageLocation, Pickup, TrackingEvent | · | · | ### AsyncAPI | Target | Tier | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | --- | | `client ws` | Tier 2 | ✓ snapshots of 3.0; 32 supported, 0 not yet | runs before a release | runs before a release | | `server ws` | Tier 2 | ✓ snapshots of 3.0; 30 supported, 0 not yet | runs before a release | runs before a release | | `server kafkajs` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `server kafkajs (counterpart)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `client kafkajs` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `client kafkajs (application)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `server faststream` | Tier 2 | ✓ snapshots of 3.0; 50 supported, 0 not yet | runs before a release | runs before a release | | `server spring` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `server go` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `server go (counterpart)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `client go` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `client go (application)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `server aspnet` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `server aspnet (counterpart)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `client csharp` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `client csharp (application)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `client java` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `client java (application)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `client python` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `client python (application)` | Tier 2 | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | `server phoenix` | Tier 2 | ✓ snapshots of 3.0; 41 supported, 0 not yet | runs before a release | runs before a release | | `server phoenix (counterpart)` | Tier 2 | ✓ snapshots of 3.0; 30 supported, 0 not yet | runs before a release | runs before a release | | `client elixir` | Tier 2 | ✓ snapshots of 3.0; 41 supported, 0 not yet | runs before a release | runs before a release | | `client elixir (application)` | Tier 2 | ✓ snapshots of 3.0; 26 supported, 0 not yet, 4 not checked | runs before a release | runs before a release | ### GraphQL | Target | Tier | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | --- | | `server absinthe` | Tier 2 | ✓ snapshots of graphql; 22 supported, 0 not yet | runs before a release | runs before a release | ### Protobuf | Target | Tier | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | --- | | `client elixir` | Tier 2 | ✓ snapshots of proto3; 42 supported, 0 not yet | runs before a release | runs before a release | | `server elixir-grpc` | Tier 2 | ✓ snapshots of proto3; 42 supported, 0 not yet | runs before a release | runs before a release | ## Features Each feature of the fixture by target, from the development version. ✓ supported, ✗ not supported yet, ? not checked, · out of scope (the feature doesn't concern the target or can't be expressed in that version), ‼ the manifest is wrong. A cell shows the first fixture version, then the fixture versions that differ. ### OpenAPI features | Feature | client csharp | client elixir | client fetch | client go | client java | client python | client rust | client swift | server express | server fastapi | server go | server hummingbird | server mcp | server orpc | server phoenix | server aspnet | server axum | server spring | server vapor | schema zod | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `operations.classic-methods`: GET, POST, PUT, PATCH and DELETE operations | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | | `operations.query-method`: `query` method operation (searchShipments), 3.2 only: 3.1/3.0 keep it as x-query | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | · | | `operations.additional-operations`: `additionalOperations` COPY (copyShippingPreset); a POST action in 3.1/3.0 | ✓ | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ | ✓ | ✓ | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ | ✓ (3.1: ?, 3.0: ?, 2.0: ?) | ✓ | ✓ | · | | `operations.two-params-one-segment`: Two path parameters in one segment: /labels/{labelId}.{extension} | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | | `operations.deprecated`: Deprecated operation (quoteRateLegacy) marked as deprecated in the output | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | | `operations.operation-servers`: Operation-level and path-level servers (importShipments uploads host, /health) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | ✓ (2.0: ·) | ✓ (2.0: ·) | · | ✓ (2.0: ·) | · | | `operations.response-ranges`: Status code ranges (2XX, 5XX) and `default` responses | ✓ (2.0: ·) | ✓ (2.0: ·) | ? (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ? (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | | `operations.callbacks`: Callbacks with runtime expressions (createShipment, createWebhookSubscription) | · | · | · | · | · | · | · | · | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✗ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | | `operations.links`: Response links (operationId, operationRef, server) | · | · | · | · | · | · | · | · | · | ✓ (2.0: ·) | · | · | · | · | · | · | · | · | · | · | | `operations.webhooks`: Top-level webhooks, inline and $ref to components/pathItems (x-webhooks in 3.0) | · | · | · | · | · | · | · | · | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✗ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | | `operations.x-internal`: `x-internal` operation (submitCarrierManifest) left out of public output | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | ✓ | ✓ | ✓ | ✓ | · | ✓ | ✓ | ✓ | ? | ✓ | · | | `parameters.header`: Reusable header parameters (Idempotency-Key, If-Match, Accept-Language) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | | `parameters.cookie`: Cookie parameter (getPublicTracking) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | | `parameters.deep-object`: deepObject query parameter (listShipments createdAt) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | | `parameters.delimited`: pipeDelimited and spaceDelimited array parameters | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | | `parameters.content`: Parameter described with `content` instead of `schema` (JSON-encoded `near`) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | | `bodies.multipart`: multipart/form-data with encoding, per-part headers and file arrays | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | | `bodies.form-urlencoded`: application/x-www-form-urlencoded body (validateAddress) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | | `bodies.patch-media-types`: application/merge-patch+json and application/json-patch+json on one operation | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | | `bodies.streaming`: text/event-stream and application/jsonl responses, JSONL upload | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | | `bodies.streaming-item-schema`: Typed stream items from `itemSchema` (3.2; x-itemSchema in 3.1/3.0) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | | `bodies.binary`: Binary responses (label as PDF/PNG/ZPL, CSV export) and uploads | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | | `bodies.components-media-types`: Reusable media types in components/mediaTypes (3.2; inlined in 3.1/3.0) | ✓ (2.0: ·) | ✓ (2.0: ·) | ? (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ? (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | | `schemas.discriminator`: oneOf + discriminator with mapping (Shipment), implicit and bare-name mappings | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.discriminator-default-mapping`: discriminator.defaultMapping (3.2; x-defaultMapping in 3.1/3.0) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | ✓ (2.0: ·) | · | | `schemas.all-of`: allOf composition (ShipmentCommon + ParcelShipment, PartyBase + Person) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.nullable`: Nullable values (type arrays, oneOf with null; nullable in 3.0) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.enum`: String enums (ShipmentStatus, with x-enum-varnames and x-enum-descriptions) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.recursion`: Recursive schemas (HandlingUnit.contents, StorageLocation.children, SearchFilter) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.tuple`: prefixItems tuple (GeoPoint coordinates), 3.1/3.2 | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | | `schemas.map`: additionalProperties maps (Metadata) and patternProperties | ✓ | ✓ (3.0: ?, 2.0: ?) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ (3.0: ?, 2.0: ?) | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.read-write-only`: readOnly and writeOnly properties (ids, timestamps, secret, callbackUrl) | ✓ | ✓ | ? | ✓ | ✓ | ✓ | ✓ | ✓ | ? | ✓ | ✓ | ✓ | ✗ | ✓ (2.0: ·) | ✓ | ✓ | ✓ | ✓ | ✓ | · | | `schemas.formats`: date-time, date, uuid, uri, email and other formats mapped to typed values | ✓ | ✓ | ? | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.number-constraints`: minimum/maximum, exclusiveMinimum and multipleOf validation | ✓ | ✓ | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.string-constraints`: pattern, minLength and maxLength validation | ✓ | ✓ | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.conditional`: if/then/else, dependentRequired, dependentSchemas, unevaluatedProperties (3.1/3.2) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | · | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | | `security.oauth2`: OAuth2 flows (authorizationCode, clientCredentials, deviceAuthorization) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | | `security.api-key`: API key in a header and in the query | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | | `security.http`: HTTP bearer and basic schemes | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | | `security.mutual-tls`: mutualTLS scheme (3.1/3.2; an x-mutualTLS note in 3.0) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ? | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | ✓ (3.0: ?, 2.0: ?) | · | | `overlay.spring-paginated`: x-spring-paginated turns page/size/sort into a Pageable argument | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | · | | `overlay.spring-provide-args`: x-spring-provide-args adds handler arguments | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | · | | `overlay.operation-annotations`: x-operation-extra-annotation on createShipment | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | · | | `overlay.model-annotations`: x-class-extra-annotation and x-field-extra-annotation on models | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | · | | `overlay.implements`: x-implements adds interfaces to models | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | · | | `overlay.validation-messages`: x-pattern-message and x-size-message customize validation messages | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | · | | `overlay.codegen-disabled`: x-apigenie.codegen.disabled leaves the internal manifest path out | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | · | | `overlay.controller-name`: x-apigenie.codegen controller-name and action-name rename POST /rates | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | · | ### AsyncAPI features | Feature | client ws | server ws | server kafkajs | server kafkajs (counterpart) | client kafkajs | client kafkajs (application) | server faststream | server spring | server go | server go (counterpart) | client go | client go (application) | server aspnet | server aspnet (counterpart) | client csharp | client csharp (application) | client java | client java (application) | client python | client python (application) | server phoenix | server phoenix (counterpart) | client elixir | client elixir (application) | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `document.info`: Info title, version and Markdown description reach the output | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `servers.hosts`: Servers with host and port, pathname, protocol and protocolVersion | ✓ | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `servers.variables`: Server variables in host and pathname with enum, default and examples, also via components/serverVariables | ✓ | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `servers.security`: Server security as OR alternatives (production-ws takes streamToken or oauth2) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `servers.bindings`: Server bindings inline (MQTT clientId, lastWill) and via components/serverBindings (Kafka schema registry) | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | · | · | · | | `protocols.kafka`: Kafka channels (shipmentEvents, carrierScans, label render requests and results) | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `protocols.websocket`: WebSocket channels (trackingStream, pickupDesk) | ✓ | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | ✓ | · | | `protocols.mqtt`: MQTT 5 channels (courierPositions, courierJobOffers and replies, sorterScans) | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `protocols.http`: HTTP channels (merchantEvents webhooks, carrierStatusPush) | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `protocols.amqp`: AMQP 0.9.1 channels (customsFilings, customsDecisions) | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `channels.one-parameter`: Address with one parameter: /tracking/{shipmentId} | ✓ | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | ✓ | · | | `channels.two-parameters`: Address with two parameters: hubs/{hubId}/sorters/{sorterId}/scans | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `channels.routing-key-parameter`: Parameterised AMQP routing key: customs.{countryCode}.filing | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `channels.null-address`: `address: null`, a dynamic channel (courierJobOfferReplies) | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `channels.parameters`: Parameters with enum, default, examples, description and location, also via components/parameters | ✓ | ✓ | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | ✓ | · | | `channels.servers-subset`: Channel `servers` subsets, title, summary and tags | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ? | | `channels.bindings-kafka`: Kafka channel bindings (topic, partitions, replicas, topicConfiguration) | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `channels.bindings-ws`: WebSocket channel binding with method, query and headers schemas (trackingStream) | ✓ | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | ✓ | · | | `channels.bindings-amqp`: AMQP channel bindings, routing key with exchange and a queue via components/channelBindings | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `operations.send-receive`: `send` and `receive` operations become the right direction for the target | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ? | | `operations.messages-subset`: Operation `messages` as a subset of the channel's (streamTracking sends 3 of 3, requestPickup receives 1 of 3) or omitted | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ? | | `operations.security-override`: Operation `security` overriding the server's (streamTracking takes streamToken only) | ✓ | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | ✓ | · | | `operations.traits`: Operation traits carrying bindings, tags and security (kafkaProducer, kafkaConsumer) | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `operations.bindings-kafka`: Kafka operation bindings (groupId and clientId schemas) | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `operations.bindings-mqtt`: MQTT operation bindings (qos, retain, messageExpiryInterval) | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `operations.bindings-http`: HTTP operation bindings (method, query schema) | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `operations.bindings-amqp`: AMQP operation bindings (expiration, priority, deliveryMode, mandatory, timestamp, ack) | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `request-reply.static-channel`: Reply on another channel via components/replies (requestLabelRender, Kafka) | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `request-reply.same-channel`: Reply on the request's channel (requestPickup on WebSocket, receiveCarrierStatus on HTTP) | ✓ | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | ✓ | · | | `request-reply.dynamic-address`: Reply address from a runtime expression via components/replyAddresses ($message.header#/replyTo, MQTT job offers) | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `request-reply.several-messages`: Replies with several messages (pickup confirmed or rejected; label rendered or failed) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ? | | `messages.metadata`: Message name, title, summary and contentType overrides | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `messages.const-discriminated`: Several messages per channel told apart by a `type` const (WebSocket) or a `decision` const (MQTT replies) | ✓ | ✓ | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | ✓ | · | | `messages.traits`: Message traits carrying headers, contentType, correlationId, bindings and externalDocs; message fields override them | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `messages.trait-merge-trap`: renderLabel applies `traced` then `correlated`; JSON Merge Patch replaces headers.required, so only correlationId is required | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `messages.headers`: Message headers (CloudEvents ce_* binary mode, W3C traceparent, replyTo, correlationId) | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `messages.correlation-id`: correlationId in a header ($message.header#/correlationId) and in the payload ($message.payload#/requestId) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `messages.bindings-kafka`: Kafka message bindings (key schema, schemaIdLocation, schemaIdPayloadEncoding, schemaLookupStrategy) | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `messages.bindings-mqtt`: MQTT message bindings (payloadFormatIndicator, correlationData, responseTopic, contentType) | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `messages.bindings-http`: HTTP message bindings (headers schema, statusCode) | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `messages.bindings-amqp`: AMQP message bindings (contentEncoding, messageType) | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `messages.examples`: Message examples with name, summary, headers and payload | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `messages.avro-payload`: Non-JSON payload, an Avro 1.9 record via schemaFormat (CarrierScanAvro) | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.all-of`: allOf composition (CloudEvent envelope plus typed data) | ✓ | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `schemas.one-of-discriminator`: oneOf with a string `discriminator` (ShipmentEvent by type) | ✓ | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `schemas.one-of-const-branches`: oneOf with const branches (CustomsDecision held vs cleared/rejected) | ✓ | ✓ | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `schemas.any-of`: anyOf requiring one of two properties (JobStop.contact phone or email) | ✓ | ✓ | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `schemas.not`: `not` (status changed events can't have status draft) | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.conditional`: if/then/else (ZPL labels need dpi, others must not; US/CA/... addresses need state; DDP filings need EORI) | · | · | ✓ | ✓ | ✓ | ✓ | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.dependencies`: draft-07 dependencies, property form (actionUrl needs actionRequired) and schema form (chute only when sorted) | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.const-enum-default`: const, enum with x-enum-varnames, default and examples | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.deprecated-property`: Deprecated property (EtaChanged.reason) marked as deprecated in the output | ✓ | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | ✓ | · | | `schemas.nullable`: Nullable values via type arrays and oneOf with type null | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.multi-type`: Multi-type map values: [string, number, boolean] (CarrierStatusUpdate.details) | ✓ | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `schemas.tuple`: draft-07 tuple: items array with additionalItems false (GeoPoint coordinates) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.recursion`: Recursive schema (HandlingUnit.contents) | ✓ | ✓ | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `schemas.array-constraints`: contains, uniqueItems, minItems and maxItems | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | ✓ | · | | `schemas.object-constraints`: propertyNames, patternProperties, additionalProperties (false, schema, true) and maxProperties | ✓ | ✓ | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `schemas.content-encoding`: contentEncoding base64 with contentMediaType (signature PNG, PDF documents) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.formats`: date, date-time, time, uuid, uri, uri-reference, email, double and decimal formats | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.number-constraints`: minimum/maximum, exclusiveMinimum/exclusiveMaximum and multipleOf validation | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `schemas.external-docs-ref`: Schema externalDocs as a $ref to components/externalDocs (CloudEvent) | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `security.sasl-x509`: scramSha512 and X509 schemes (Kafka, MQTT devices) | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | `security.api-key`: httpApiKey in the query (streamToken) and in a header (webhookSignature) | ✓ | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | ✓ | · | | `security.oauth2`: OAuth2 clientCredentials and authorizationCode flows with refreshUrl, availableScopes and required scopes | ✓ | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ✓ | · | ✓ | · | | `security.openid`: openIdConnect with scopes (courierOidc) | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `security.http`: HTTP basic and bearer (JWT) schemes (carrier ingest) | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | | `security.plain-encryption`: plain and asymmetricEncryption schemes (customs broker) | · | · | · | · | · | · | ✓ | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | · | ### GraphQL features | Feature | server absinthe | | --- | --- | | `schema.description`: The schema description reaches the output | ✓ | | `schema.root-types`: A schema definition naming the query, mutation and subscription root types | ✓ | | `root.queries`: Every Query field is resolvable (shipment, shipments, trackShipment, rates, legacyRates, pickups, warehouses, node, validateAddress, webhookSubscriptions, account, health) | ✓ | | `root.mutations`: Every Mutation field is resolvable (createShipment, updateShipment, cancelShipment, schedulePickup, cancelPickup, createWebhookSubscription, deleteWebhookSubscription) | ✓ | | `root.subscriptions`: The Subscription field shipmentStatusChanged is served over a subscription transport | ✓ | | `types.objects`: Object types with scalar, enum, object, list and non-null fields (Address, Money, Parcel, TrackingEvent...) | ✓ | | `types.nested-arguments`: Fields with arguments below the root (Shipment.trackingEvents(first:), Warehouse.locations(prefix:)) | ✓ | | `types.interfaces`: Interfaces with their implementations (Node; Shipment as ParcelShipment, PalletShipment, FreightShipment) | ✓ | | `types.interface-inheritance`: An interface implementing another interface (Shipment implements Node) | ✓ | | `types.unions`: A union resolved to its members (Party = Person \| Company) | ✓ | | `types.enums`: Enum types (ShipmentStatus, ShipmentMode, CarrierCode, LabelFormat...) | ✓ | | `types.input-objects`: Input object types, nested (CreateShipmentInput with PartyInput, AddressInput, ParcelInput) | ✓ | | `types.one-of`: A @oneOf input object (ShipmentLookupInput) whose values must set exactly one field | ✓ | | `types.custom-scalars`: Custom scalars with parsing and serialization (DateTime, Date, Decimal, CountryCode, CurrencyCode) | ✓ | | `types.specified-by`: A scalar with @specifiedBy (DateTime, RFC 3339) | · | | `types.list-nesting`: List and non-null wrappers in field, argument and input field types ([TrackingEvent!]!, [ID!]!, [ShipmentStatus!]) | ✓ | | `docs.descriptions`: Descriptions of types, fields, arguments, enum values and input fields | ✓ | | `docs.field-deprecation`: Deprecated fields with a reason (Shipment.trackingUrl, Query.legacyRates) | ✓ | | `docs.argument-deprecation`: A deprecated argument (Query.shipments(status:)) and input field (UpdateShipmentInput.version) | ✓ | | `docs.enum-value-deprecation`: A deprecated enum value (CarrierCode.ROYAL_MAIL) | ✓ | | `values.argument-defaults`: Default values of arguments (shipments(first: 20), trackingEvents(first: 10), cancelShipment(reason: CUSTOMER_REQUEST)) | ✓ | | `values.input-defaults`: Default values of input fields, enum, list and string defaults included (CreateShipmentInput.mode, parcels, SchedulePickupInput.readyFrom) | ✓ | | `directives.custom`: A custom type-system directive definition (@cost on FIELD_DEFINITION) applied to fields | ✓ | ### Protobuf features | Feature | client elixir | server elixir-grpc | | --- | --- | --- | | `files.imports`: Types of other files of the set (common.proto, shipments.proto) are referenced across files | ✓ | ✓ | | `files.import-public`: shipments.proto re-exports common.proto with import public; rates.proto uses Address through it | ✓ | ✓ | | `files.package`: Every declaration is in package carpetexpress.v1, which scopes the generated names | ✓ | ✓ | | `files.standard-imports`: google/protobuf and google/api imports resolve without the files being in the set | ✓ | ✓ | | `messages.top-level`: Top-level messages (Money, Shipment, TrackingEvent) | ✓ | ✓ | | `messages.nested`: Nested messages (Shipment.Parcel, Shipment.ParcelDetails), used outside their parent (rates.proto uses Shipment.Parcel) | ✓ | ✓ | | `messages.empty`: Messages without fields (ListWarehousesRequest) | ✓ | ✓ | | `messages.deprecated`: A deprecated message (LegacyRate) | ✓ | ✓ | | `messages.comments`: Leading comments of messages reach the output as documentation | ✓ | ✓ | | `messages.reserved`: Reserved numbers and names (Shipment reserves 16 to 19 and insurance) don't break generation | ✓ | ✓ | | `fields.scalars`: Every scalar type (LabelFile, Money, Weight) with its own wire type | ✓ | ✓ | | `fields.repeated`: Repeated scalars, enums and messages (Address.lines, ListShipmentsRequest.statuses, ParcelDetails.parcels) | ✓ | ✓ | | `fields.packed`: Repeated scalars packed by default (Parcel.item_counts) | ✓ | ✓ | | `fields.unpacked`: [packed = false] (FreightDetails.hazmat_classes) | ✓ | ✓ | | `fields.optional`: proto3 optional fields with presence (Shipment.reference, Address.state) | ✓ | ✓ | | `fields.json-name`: JSON names, the default lowerCamelCase one and an explicit json_name (Address.country_code is "country") | ✓ | ✓ | | `fields.deprecated`: A deprecated field (Shipment.legacy_tag) | ✓ | ✓ | | `fields.required`: (google.api.field_behavior) = REQUIRED fields (Money.currency_code, CreateShipmentRequest.shipment) | ✓ | ✓ | | `fields.reserved-word`: A field named like a keyword of target languages (TimeWindow.end) | ✓ | ✓ | | `fields.comments`: Comments of fields reach the output | ✓ | ✓ | | `maps.scalar`: Maps of scalars (Shipment.labels, Account.features, Warehouse.capacity_by_zone) | ✓ | ✓ | | `maps.message`: Maps with message values (Shipment.charges) | ✓ | ✓ | | `oneofs.messages`: A oneof of messages (Shipment.mode, Party.kind) | ✓ | ✓ | | `oneofs.scalars`: A oneof of scalars (PublicTrackingRequest.lookup) | ✓ | ✓ | | `enums.top-level`: Top-level enums (ShipmentStatus, CarrierCode, WebhookEventType) | ✓ | ✓ | | `enums.nested`: Nested enums (Weight.Unit, TrackingEvent.Kind), used outside their parent (CourierUpdate.kind) | ✓ | ✓ | | `enums.alias`: allow_alias with two names for one number (CARRIER_CODE_DHL, CARRIER_CODE_DHL_EXPRESS) | ✓ | ✓ | | `enums.deprecated-value`: A deprecated value (CARRIER_CODE_TNT) | ✓ | ✓ | | `enums.reserved`: Reserved numbers and names of an enum (ShipmentStatus) don't break generation | ✓ | ✓ | | `wkt.timestamp`: google.protobuf.Timestamp maps to the target's timestamp type | ✓ | ✓ | | `wkt.duration`: google.protobuf.Duration maps to the target's duration type | ✓ | ✓ | | `wkt.empty`: google.protobuf.Empty as a request (AccountService) and a response (CancelShipment) | ✓ | ✓ | | `wkt.field-mask`: google.protobuf.FieldMask (UpdateShipmentRequest.update_mask) | ✓ | ✓ | | `wkt.struct`: google.protobuf.Struct (Shipment.metadata) | ✓ | ✓ | | `wkt.wrappers`: Wrapper types (Shipment.notes is a StringValue) | ✓ | ✓ | | `services.unary`: Unary methods (ShipmentService.CreateShipment and 19 more) | ✓ | ✓ | | `services.server-streaming`: Server streaming methods (TrackingService.StreamTrackingEvents, WarehouseService.GetWarehouseLocations) | ✓ | ✓ | | `services.client-streaming`: A client streaming method (ShipmentService.ImportShipments) | ✓ | ✓ | | `services.bidi-streaming`: A bidirectional streaming method (TrackingService.LiveTracking) | ✓ | ✓ | | `services.several`: Seven services of one file, each generated on its own | ✓ | ✓ | | `services.deprecated-method`: A deprecated method (RateService.QuoteRateLegacy) | ✓ | ✓ | | `services.comments`: Comments of services and methods reach the output | ✓ | ✓ | ## Not supported yet The reasons the targets' manifests give, by target. A feature that starts working fails the suite until its entry is removed, so the list can't fall behind the code. ### OpenAPI: server mcp - `schemas.read-write-only`: readOnly and writeOnly are ignored; one schema serves arguments and results, so createWebhookSubscription's result declares the writeOnly `secret`. ### OpenAPI: server axum - `operations.callbacks` (3.2, 3.1, 3.0): The server doesn't generate typed senders of callbacks yet; an application sends them with a client of its own. - `operations.webhooks` (3.2, 3.1, 3.0): The server doesn't generate typed senders of webhooks yet; an application sends them with a client of its own. --- # apigenie-generator docs Source: https://apigenie.pl/docs/reference/generator/docs Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). Release 0.12.0: Level 1 ✓ · [Verification](#verification) Generate a documentation site from OpenAPI, Swagger 2.0, AsyncAPI, GraphQL and Protobuf files, several at once. ## Usage ```sh apigenie-generator docs [...OPTIONS] INPUT... ``` ## Description The site is built in two steps: 1. `apigenie-generator docs` reads the inputs and writes a *docs bundle*: a manifest (`apigenie-docs.json`) and, per document and locale, the resolved document (OpenAPI and Swagger 2.0, with the files it references bundled in) or the documentation model (AsyncAPI, GraphQL and Protobuf), with the Git changelog and the example files when asked for. Next to the bundle it writes `package.json` and a README: an npm project that depends on the API Genie web components, `@mykulyak/apigenie-docs`. 2. `npm install`, then `npm run build` renders the bundle into `dist/`: one HTML page per API, operation and schema, prerendered so that it reads without JavaScript and hydrates with it (Try it out, search, navigation), with a sitemap, a locale switcher, a changelog page and the examples. Serve `dist/` from any static host. `npm run build -- --base /docs/ --origin https://example.com` hosts the site under a path and writes absolute URLs into the sitemap. The CLI never runs Node: the bundle is plain JSON, and `--bundle-only` writes it alone for a site built by other means, such as a page of your own holding an `` element. Several inputs of mixed families make one site, each document under its own path. An input that can't be read is reported with its positions and left out; the others are still written. Files of the output directory that the bundle doesn't write are left alone. ## Options | Option | Description | | --- | --- | | `-o`, `--output OUTPUT` | The output directory (required). | | `-c`, `--config CONFIG` | The configuration file: its `commands.generate.docs` section configures the site (below), its `diff` section the severities of the changelog. | | `--i18n LOCALE=FILE` | A translation file, as [`i18n extract`](/docs/reference/cli/i18n) writes it, for a locale. Can be repeated. Every file applies to every input, with the keys of the input's kind (JSON pointers for OpenAPI, Swagger and AsyncAPI, names for GraphQL and Protobuf); a file that translates nothing in an input is a warning. | | `--changelog` | Adds the changelog of each input from its Git history, as [`apigenie changelog`](/docs/reference/cli/changelog) computes it. An input outside a repository gets a warning and no changelog. | | `--package-name NAME` | The name of the generated npm package (`api-docs` by default). | | `--package-version VERSION` | Its version (`1.0.0` by default). | | `--bundle-only` | Writes the docs bundle only, without `package.json` and README. | ## Configuration All keys are optional and sit under `commands.generate.docs`. Paths are relative to the configuration file. ```yaml version: '1.0' commands: generate: docs: title: Acme APIs default_locale: en prefix_default_locale: false changelog: revisions: tags tag_pattern: 'v*' unreleased: true documents: - file: api/openapi.yaml id: shop title: Shop API - file: proto/orders.proto proto_paths: [proto] examples: - file: examples/create-order.json title: Create an order ``` | Key | Type | Default | Description | | --- | --- | --- | --- | | `title` | string | the first document's title | The title of the site. | | `default_locale` | string | `en` | The locale of the documents as written. `--i18n` files add the other locales. | | `prefix_default_locale` | bool | `false` | Whether the default locale's pages get the locale prefix too (`/en/...`). | | `changelog` | bool or object | `false` | `true` adds the changelog of every document (as `--changelog`); an object also selects the revisions: `revisions` (`commits` or `tags`), `tag_pattern`, `tag_sort` (`version` or `date`), `unreleased`, `from`, `to`, as the options of `apigenie changelog`. | | `documents` | list | | The inputs, besides those given on the command line: `file`, and optionally `id` (the document's directory in the bundle, by default the file's stem), `title`, `proto_paths` (the directories a .proto file's imports are searched in, before its own) and `examples` (paths, or `{file, title}`). | ## The docs bundle ``` apigenie-docs.json the manifest documents//document..json the document per locale documents//changelog.json with --changelog documents//examples/ example files package.json, README.md unless --bundle-only ``` The manifest holds `apigenieDocs: 1` and `formatVersion: 1` (the version of the format, under the name all JSON outputs of API Genie use; see [Compatibility](/docs/reference/cli/compatibility)), `title`, `generator`, `locales` (the default one first), `prefixDefaultLocale` and `documents`, each with `id`, `family` (`openapi`, `swagger`, `asyncapi`, `graphql` or `protobuf`), `title`, `version`, `source` (the input's file name), `files` (per locale), and `changelog` and `examples` when present. Paths are relative to the bundle. Its JSON Schema is [`apigenie-docs-manifest.json`](https://apigenie.pl/schemas/apigenie-docs-manifest.json). ## Examples Next to a GraphQL schema, the `.json`, `.yaml` and `.yml` files of its `_examples` directory (the examples [`apigenie test`](/docs/reference/cli/test) runs) are copied into the bundle and shown with the schema. Any document can list more under `examples` in the configuration. ## See also - [i18n](/docs/reference/cli/i18n), which extracts the translation files `--i18n` takes - [changelog](/docs/reference/cli/changelog), whose changelog `--changelog` writes into the bundle - [configuration](/docs/reference/cli/configuration) ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this command on the Carpet Express OpenAPI fixture at Level 1 and checks what it writes. [All targets](/docs/reference/generator/conformance#openapi). | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ 4 files, 38 operations | doesn't apply | doesn't apply | | Development version | ✓ 4 files, 38 operations | doesn't apply | doesn't apply | --- # apigenie-generator data Source: https://apigenie.pl/docs/reference/generator/data Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). Release 0.12.0: Level 1 ✓ · [Verification](#verification) Generate example data for a schema of an OpenAPI document. The command is experimental. ## Usage ```sh apigenie-generator data --pointer POINTER --output OUTPUT [...OPTIONS] INPUT_FILE ``` ## Description The command reads an OpenAPI 3.0, 3.1 or 3.2 document, takes the schema that `--pointer` points to, and writes a value that conforms to it. With `--number N` greater than 1 it writes a JSON array of `N` values. The output is JSON or YAML, chosen by the extension of the output file (`.json`, `.yaml` or `.yml`). Swagger 2.0 documents are not read; convert them first with [`convert --to openapi32`](/docs/reference/cli/convert). ```sh apigenie-generator data -p /components/schemas/Money -o money.json -n 2 openapi.yaml ``` ```json [ { "amount": "-841701990.0826", "currency": "ITG" }, { "amount": "-70238.2", "currency": "NOO" } ] ``` The pointer can name any schema of the document: a component (`/components/schemas/Pet`), a property (`/components/schemas/Pet/properties/tags`) or the schema of a parameter or a body. References inside the schema are followed when they are local (`#/...`). How values are made: - `enum` and `const` values are taken from the schema. Schema `example`, `examples` and `default` values are not used. - Numbers and integers stay within the schema's `minimum`, `maximum` and exclusive bounds. A bound the schema doesn't give comes from the configuration: -10 to 10 by default. - Strings with a `format` get a value of that format: `uuid`, `date`, `date-time`, `time`, `duration`, `email`, `idn-email`, `hostname`, `idn-hostname`, `ipv4`, `ipv6`, `uri`, `url`, `iri`, `uri-reference`, `iri-reference`, `uri-template`, `byte` and `password`. Strings with a `pattern` match the regular expression. Other strings are words of placeholder text, of a length within `minLength` and `maxLength`, or within the configured range (0 to 10) when the schema gives neither. - Arrays have between `minItems` and `maxItems` items, or a number within the configured range (0 to 10) when the schema gives neither. - Objects have all their required properties and a random selection of the optional ones, within `minProperties` and `maxProperties`. - `allOf` members are merged; `oneOf` and `anyOf` produce a value of one of the alternatives; a schema with several types (`type: [string, "null"]`) produces a value of one of them. - A schema with an `x-faker` extension gets its value from a faker provider (see "Extensions"), as in [`apigenie-server`](/docs/reference/server/scenarios). - Recursive schemas end: below a nesting depth of 16, objects only get their required properties and arrays their minimum number of items. Values are random: each run writes different data. A schema that can't produce a value (a `false` schema, an unresolved reference, a `minimum` greater than its `maximum`) stops the command with an error. ## Extensions | Extension | Effect | | --------- | ------ | | `x-faker` | the [faker provider](/docs/reference/cli/faker) that makes the value of a schema: a function name, `{name: [arguments]}`, or `{provider, args, options}` | | `x-apigenie-mock-faker` | the same as `x-faker`, which it takes precedence over | The extensions can live in an overlay for this target instead of in the document, e.g. `data.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Data fakers version: 1.0.0 actions: - target: $.components.schemas.User.properties.email update: x-faker: internet.email ``` ```sh apigenie-generator data -p /components/schemas/User openapi.yaml --overlay data.overlay.yaml -o user.json ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.data.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### -p, --pointer Required. JSON pointer to the schema in the input document, e.g. `/components/schemas/User`. A pointer that doesn't point to a schema is an error (`Schema not found at '...'`). ### -o, --output Required. Path to the output file. Its extension, `.json`, `.yaml` or `.yml`, sets the format. ### -n, --number Number of values to generate, a positive integer; 1 by default. With a number greater than 1 the output is an array. ## Configuration The `commands.generate.data` section of the configuration file sets the ranges used where a schema doesn't give its own bounds. ```yaml version: '1.0' commands: generate: data: minimum: 0 maximum: 1000 minLength: 1 maxLength: 20 minItems: 1 maxItems: 3 ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `minimum` | number | `0` | Lower bound of numbers and integers whose schema has no lower bound. | | `maximum` | number | `10` | Upper bound of numbers and integers whose schema has no upper bound. | | `minLength` | integer | `0` | Minimum length of strings whose schema has neither `minLength` nor `maxLength`. | | `maxLength` | integer | `10` | Maximum length of strings whose schema has no `maxLength`. | | `minItems` | integer | `0` | Minimum number of items of arrays whose schema has neither `minItems` nor `maxItems`. | | `maxItems` | integer | `10` | Maximum number of items of arrays whose schema has no `maxItems`. | | `minProperties` | integer | `0` | Read and checked, but objects are only limited by their schema. | | `maxProperties` | integer | `10` | Read and checked, but objects are only limited by their schema. | Without a configuration file the numeric range is -10 to 10. When the `data` section is present, a key it leaves out takes the default of the table, so `minimum` becomes 0 unless it is given. A minimum greater than its maximum, or a negative count, is an error. ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this command on the Carpet Express OpenAPI fixture at Level 1 and checks what it writes. [All targets](/docs/reference/generator/conformance#openapi). | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ 3 values each of Shipment, Address, HandlingUnit, StorageLocation, Pickup, TrackingEvent | doesn't apply | doesn't apply | | Development version | ✓ 3 values each of Shipment, Address, HandlingUnit, StorageLocation, Pickup, TrackingEvent | doesn't apply | doesn't apply | --- # apigenie-generator schema zod Source: https://apigenie.pl/docs/reference/generator/schema-zod Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Experimental](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 not run yet · [Verification](#verification) Generate [Zod](https://zod.dev) (v4) schemas, with their TypeScript types, from JSON Schemas. > **(experimental, outside the 1.0 compatibility promise)** The generated schemas aren't yet > checked against a live API (conformance Level 3), and the options and the output can still > change. `schema zod` says so in its `--help` and on the first line it prints, on the standard > error. See the [experimental commands](/docs/reference/cli#experimental-commands). ## Usage ```sh apigenie-generator schema zod [...OPTIONS] INPUT_FILE ``` ## Description The input is a JSON or YAML file: - a JSON Schema document (drafts 4, 6, 7, 2019-09 and 2020-12, 2020-12 when it has no `$schema`): its root schema, named after its `title` or the file, and its `$defs` (or `definitions`) are generated. A root that only holds definitions is left out; - an OpenAPI 3.x document: its `components.schemas`, with the OpenAPI 3.0 `nullable` keyword and boolean `exclusiveMinimum`/`exclusiveMaximum`; - a Swagger 2.0 document: its `definitions`, with the `x-nullable` extension; - an AsyncAPI document: its `components.schemas`. Schemas in other formats (Avro, ...) are skipped. Other schemas that a `$ref` points to, e.g. `#/$defs/User/properties/address` or a schema of another file, are named after their path (`UserAddressSchema`), so that each is written once. Every schema becomes a constant and a type: ```ts import * as z from "zod"; export const UserSchema = z.looseObject({ id: z.uuid(), email: z.email(), /** Display name */ name: z.string().min(1).max(80), age: z.int().gte(0).lt(150).optional(), }); export type User = z.infer; ``` Schemas are declared after the schemas they use. A schema using itself, or a schema declared later, from an object property gets a getter: ```ts export const CommentSchema = z.strictObject({ text: z.string(), get replies() { return z.array(CommentSchema).optional(); }, }); ``` Elsewhere, e.g. `items` of an array schema using the array itself, the reference is wrapped in `z.lazy()` and the constant is typed `z.ZodType`, so its inferred type is `unknown`. This is reported as a warning. ### How keywords are mapped | JSON Schema | Zod | | ----------- | --- | | `type` | `z.string()`, `z.number()`, `z.int()` (`z.int32()` for the `int32` format), `z.boolean()`, `z.null()`, `z.array()`, objects; several types make a `z.union()`, `null` with other types `.nullable()` | | no `type` | the type implied by the keywords, e.g. `minLength` makes a string; `z.unknown()` otherwise | | `enum`, `const` | `z.enum()` for strings, `z.literal()` otherwise | | `format` | `z.email()`, `z.url()` (`uri`, `iri`), `z.uuid()`, `z.iso.datetime({ offset: true })`, `z.iso.date()`, `z.iso.duration()`, `z.ipv4()`, `z.ipv6()`, `z.hostname()`, `z.base64()` (`byte`), `z.base64url()`; other formats are not validated | | `minLength`, `maxLength`, `pattern` | `.min()`, `.max()`, `.length()`, `.regex()` | | `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf` | `.gte()`, `.lte()`, `.gt()`, `.lt()`, `.multipleOf()` | | `items`, `minItems`, `maxItems` | `z.array()`, `.min()`, `.max()` | | `prefixItems` (or an array of `items`) | `z.tuple()`, with optional items beyond `minItems` and a rest of `items` (`additionalItems`) | | `uniqueItems`, `contains` | refinements | | `properties`, `required` | the shape, with `.optional()` for properties that aren't required, or `.default()` with their `default` | | `additionalProperties` | none or `true`: `z.looseObject()` (unknown properties are kept); `false`: `z.strictObject()`; a schema: `.catchall()`, or `z.record()` without properties | | `patternProperties` | a refinement validating the matching properties | | `minProperties`, `maxProperties`, `propertyNames`, `dependentRequired`, `dependentSchemas` (`dependencies`) | refinements | | `allOf` | `z.intersection()` | | `anyOf`, `oneOf` | `z.union()`, or `z.discriminatedUnion()` when a required property with constant values tells the objects apart (e.g. the OpenAPI `discriminator`) | | `not`, `if`/`then`/`else` | refinements | | `$ref` | the referenced schema's constant | | `description` (or `title`), `deprecated` | JSDoc comments; `.describe()` with the `describe` option | Not supported, and reported as warnings: `unevaluatedProperties` and `unevaluatedItems`. `$dynamicRef` and `$recursiveRef` are resolved to their initial targets. In very large graphs of recursive schemas, TypeScript may give up inferring a type (`TS2589: Type instantiation is excessively deep` at `z.infer`); the schemas still validate. Approximations: `oneOf` is not exclusive, `uniqueItems` compares items by their JSON text, string lengths count UTF-16 code units, and `uuid` accepts the versions known to Zod. The types of properties are implied by their keywords also where JSON Schema accepts other types, e.g. `{ "minLength": 1 }` rejects numbers. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | base of the names of the constant and the type of a schema (`AnimalSchema`, `Animal`) | | `x-nullable` | `true` makes a schema accept `null`, as in Swagger 2.0 documents | The extensions can live in an overlay for this target instead of in the document, e.g. `zod.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Zod names version: 1.0.0 actions: - target: $.components.schemas.Pet update: x-apigenie: codegen: name: Animal ``` ```sh apigenie-generator schema zod openapi.yaml --overlay zod.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.schema_zod.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the schemas are generated. ### --package-name Name of the generated package. Defaults to the title of the document or the name of the file. ### --package-version Version of the generated package. Defaults to the version of the API, or `0.0.0`. ## Configuration ```yaml version: '1.0' commands: generate: schema_zod: layout: package import_extension: .js schema_suffix: Schema type_suffix: '' types: true additional_properties: loose describe: false ``` | Option | Description | | ------ | ----------- | | `layout` | `package` (default): an npm package with `src/schemas.ts` and `src/index.ts`; `sources`: `schemas.ts` only | | `import_extension` | Extension of relative imports: `.js` (default, Node.js) or an empty string (bundlers) | | `schema_suffix` | Appended to the names of the schema constants (default `Schema`) | | `type_suffix` | Appended to the names of the types (default none) | | `types` | Whether `export type X = z.infer` is generated (default `true`) | | `additional_properties` | Objects without `additionalProperties`: `loose` (default) keeps unknown properties, `strip` removes them (`z.object()`) | | `describe` | Whether descriptions are attached with `.describe()` (default `false`) | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, and Level 2 runs the language's type checker and linter; Level 3 isn't wired for this target. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Experimental](/docs/reference/generator/conformance#tiers). It isn't run at every level yet. It is outside the [1.0 compatibility promise](/docs/reference/cli/compatibility): its options and the shape of its output can change, or it can go away, in a minor release. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 11 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, zod 4) | not run yet | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 11 supported, 0 not yet | runs before a release | not run yet | --- # apigenie-generator client csharp Source: https://apigenie.pl/docs/reference/generator/client-csharp Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 1](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a C# client of an OpenAPI document, built on `HttpClient` and `System.Text.Json`, for .NET 8 (or 9 and 10). From an AsyncAPI document, the command generates a C# Kafka client library instead; see [`apigenie-generator client csharp` (AsyncAPI)](/docs/reference/generator/client-csharp-asyncapi). ## Usage ```sh apigenie-generator client csharp [...OPTIONS] INPUT_FILE ``` ## Description The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)). The output is a class library: a `.csproj` targeting `net8.0` with nullable reference types, which references only `Microsoft.Extensions.Http` (for the registration with dependency injection). ```csharp services.AddPetStoreClient(options => { options.BaseUrl = new Uri("https://api.example.com/v1"); options.ApiKey = ApiCredential.Static(configuration["PetStore:ApiKey"]!); }); // inject PetStoreClient, or the client of a group, e.g. IPetsClient var pets = await client.Pets.ListPetsAsync(limit: 10, cancellationToken: token); try { var pet = await client.Pets.GetPetAsync(42); } catch (ApiException error) when (error.StatusCode == 404) { Console.WriteLine(error.Problem?.Detail); } ``` Without dependency injection, `PetStoreClient.CreateHttpClient(options)` makes an `HttpClient` that sends the credentials: `new PetStoreClient(PetStoreClient.CreateHttpClient(options), options)`. The generated code has: - **Clients.** One interface and one client per group of operations (`IPetsClient`, `PetsClient`), grouped by their first tag (see `grouping`), and `PetStoreClient` with a property per group. The clients take the `HttpClient` in their constructor, so `IHttpClientFactory` manages them; `AddPetStoreClient()` registers them as typed clients, with the options and the handlers sending the credentials. Operations marked `x-internal` are left out. - **Methods.** An `async` method per operation, named after its operation ID (`ListPetsAsync`, see `action_naming`): path parameters, the other required parameters and the body first, optional parameters (`null` leaves them out) and a `CancellationToken` last. Parameters are sent in their style (form, spaceDelimited, pipeDelimited, deepObject, simple, label, matrix), objects included; parameters described by `content` are sent as JSON. Deprecated operations are `[Obsolete]`. - **Bodies.** JSON (with the media type of the document, e.g. `application/merge-patch+json`), text, binary (`Stream`), JSON Lines uploads (`IAsyncEnumerable`), and forms and multipart bodies as `*Form` classes, whose files are `FilePart`s (`format: binary` or `contentMediaType`) sent with the content type of their `encoding`. - **Responses.** The method returns the body of the success response (`Task`), nothing (`Task`), or, when statuses have different bodies, a `*Result` with the status, the headers and a property per status. Responses with a status of 400 or more throw an `ApiException` with the status, the headers, the body as text and its RFC 9457 problem details (`Problem`). `text/event-stream` responses are `IAsyncEnumerable>`, typed by the `contentSchema` of the events' data (OpenAPI 3.2 `itemSchema`, or `x-itemSchema`), JSON Lines responses `IAsyncEnumerable`, both read as they arrive; binary responses are `BinaryResponse`s to dispose. Each other media type of a body or a response is a method of its own, named after it: `UpdatePetJsonPatchAsync`, `GetLabelPdfAsync`, `GetEventsEventStreamAsync`. - **Servers.** Requests go to `BaseUrl`, else to the base address of the `HttpClient`, else to the first server of the operation, of its path or of the API, with `ServerVariables` for their variables. - **Security.** A credential per security scheme in the options (`ApiCredential.Static`, `ApiCredential.FromProvider` for tokens that change, `ApiCredential.Basic`). A request carries the credentials of the first alternative of its operation's security requirements whose credentials are set; the `AuthorizationHandler` (HTTP schemes such as bearer and basic, OAuth 2.0, OpenID Connect) and `ApiKeyHandler` (headers, query parameters, cookies) delegating handlers add them. - **OAuth 2.0** (since 0.12.0). When a scheme has client credentials, authorization code or device authorization flows, `Infrastructure/OAuth.cs` has an `OAuthClient`. Create it with the flows of the scheme (`SecurityScheme.Flows`, in `PetStoreSecuritySchemes.All`), the client ID and, for a confidential client, the secret. `ClientCredentials()` returns an `ApiCredential`. The authorization code flow with PKCE (`CreateAuthorizationRequest()`, then `ExchangeCodeAsync()`) and the device authorization flow of OpenAPI 3.2 (`StartDeviceAuthorizationAsync()`, then `PollDeviceAuthorizationAsync()`) return `OAuthTokens`, which `FromTokens(tokens, flow)` makes an `ApiCredential`, with the flow that issued them, e.g. `scheme.Flows!.AuthorizationCode`. Credentials renew their access token 30 seconds before it expires, with the refresh token when there is one. Without one, or when the server refuses it, `ClientCredentials()` credentials ask for new tokens, and `FromTokens()` credentials keep the access token until the server refuses it. Errors of the authorization server, a refused refresh token among them, throw an `OAuthException`. The password and implicit flows are left to tokens from elsewhere. ```csharp var scheme = PetStoreSecuritySchemes.All.First(s => s.Name == "oauth2"); var oauth = new OAuthClient(scheme.Flows!, "my-client-id", "my-secret"); services.AddPetStoreClient(options => options.Oauth2 = oauth.ClientCredentials()); ``` - **Models.** Records and enums, as `apigenie-generator server aspnet` writes them: `required`/`init` properties, DataAnnotations for constraints (exclusive bounds of OpenAPI 3.0 and 3.1 alike), nullable types for `nullable`, `null` types and `oneOf` with `null`. `allOf` is merged into one record, or is inheritance (`[JsonPolymorphic]`/`[JsonDerivedType]`) when the base has a discriminator. `oneOf` and `anyOf` with a discriminator are abstract records whose variants are told apart by the discriminator value (explicit mapping, or the `const` of the discriminator property, or the schema name), read and written by generated converters wherever the discriminator is in the object; values with an unknown discriminator are read as the default mapping (`defaultMapping`, or `x-defaultMapping`). Unions whose members have one C# type (e.g. strings of different formats) have that type. - **Tuples, patterns and conditions** (since 0.12.0). Tuples (`prefixItems`) are lists of the type their positions share, or of `object` when they differ, with a `MaxLength` when `items: false` closes them. A `patternProperties` schema without `properties` is a dictionary of the type of its one pattern. With several patterns, it is a record whose `Entries` hold the values as `JsonElement`s. `multipleOf` is a `[MultipleOf]` attribute. Some records implement `IValidatableObject` and check in `Validate()`: - records with `if`/`then`/`else`, `dependentRequired` or `dependentSchemas` conditions on which properties are present and their constant values; - records with `additionalProperties: false`, for keys that match no pattern. The server's endpoint filter checks these attributes and `Validate()`; the client doesn't call them. - **JSON.** A `System.Text.Json` source-generated `JsonSerializerContext` (`PetStoreJsonContext`) with every model and body type, so the clients read and write JSON without reflection. Use it to read error bodies: `JsonSerializer.Deserialize(error.Content!, PetStoreJsonContext.Default.Error)`. The project also has `README.md`, `Infrastructure/` (the runtime of the clients) and `Serialization/` (the JSON context and converters). The code builds with `-warnaserror` and the .NET analyzers. Not supported: - receiving callbacks and webhooks (the client has no server for them); - mutual TLS (configure the client certificate on the HTTP handler); - XML bodies (sent and read as text); - the type of each position of a tuple; - `patternProperties` beside `properties`, the keys of a one-pattern dictionary and the values of `Entries` (not checked); - conditions on anything other than the presence and constant values of properties, and `unevaluatedProperties`; - retries (add a resilience handler with `configureHttpClient`) and pagination. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.controller-name` | on an operation or its path item: the group (client) of the operation, whatever `grouping` says | | `x-apigenie.codegen.action-name` | name of the method of an operation, when `action_naming` lists `extension` | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out, unless `skip_disabled` is `false` | | `x-internal` | `true` on an operation leaves it out | | `x-enum-varnames`, `x-enum-names` | names of the members of an enum, in PascalCase | | `x-enum-descriptions`, `x-enumDescriptions` | documentation comments of the members of an enum | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn't mapped | | `x-itemSchema` | `itemSchema` of a media type in OpenAPI 3.0 and 3.1 documents: the type of the items of a streamed response | The extensions can live in an overlay for this target instead of in the document, e.g. `csharp.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: C# names version: 1.0.0 actions: - target: $.components.schemas.PetStatus update: x-enum-varnames: [Available, OnHold, Sold] - target: $.paths['/pets'] update: x-apigenie: codegen: controller-name: Animals ``` ```sh apigenie-generator client csharp openapi.yaml --overlay csharp.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.client_csharp.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the project is generated. ### --package-name Root namespace of the generated code, e.g. `Acme.PetStore.Client`; also the name of the project. The API-wide types are named after its last segment (or the one before when it is `Client`, `Clients` or `Sdk`): `PetStoreClient`, `PetStoreClientOptions`. Defaults to the title of the API followed by `.Client`. ### --package-version Version of the project. Defaults to the version of the API when it's a valid .NET version, or `1.0.0`. ### -p, --property NAME=VALUE Sets an option (see below), e.g. `-p layout=sources`; can be repeated. Options given on the command line take precedence over the configuration file. OpenAPI documents only: using it with an AsyncAPI document is an error. ## Configuration The options are read from `commands.generate.client_csharp`. Its `asyncapi` section configures the generation from AsyncAPI documents (see [`apigenie-generator client csharp` (AsyncAPI)](/docs/reference/generator/client-csharp-asyncapi#configuration)). ```yaml version: '1.0' commands: generate: client_csharp: namespace: Acme.PetStore.Client target_framework: net9.0 grouping: tag dependency_injection: true ``` | Option | Values | Description | | ------ | ------ | ----------- | | `layout` | `project`, `sources` | `project` (default): a class library (.csproj, README.md and the sources); `sources`: only the generated sources, for an existing project | | `namespace` | namespace | Root namespace of the generated code (also `--package-name`); derived from the API title by default, e.g. `PetStore.Client` | | `target_framework` | `net8.0`, `net9.0`, `net10.0` | Target framework of the project (default: `net8.0`) | | `grouping` | `tag`, `url` | Grouping of operations into clients: by their first tag (default), or by the first segment of their paths | | `action_naming` | `id`, `extension`, `url` | Sources of method names, in order of preference (default: `id`, `url`) | | `dependency_injection` | `true`, `false` | Generate the registration of the clients with `IServiceCollection` and `IHttpClientFactory` (default: `true`; it references Microsoft.Extensions.Http) | | `skip_deprecated` | `true`, `false` | Don't generate deprecated operations (default: `false`) | | `skip_disabled` | `true`, `false` | Don't generate operations disabled with the `x-apigenie` extension (default: `true`) | | `model_suffix` | text | Suffix of model names, e.g. `Dto` | | `version` | version | Version of the project (also `--package-version`); defaults to the version of the API | Unknown options are errors. ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Tier 1](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, with the goal of supporting every feature of the fixture. Its unsupported features are worked on first. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (.NET SDK 8.0.204) | ✓ 37 of 37 operations pass (dotnet) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator client elixir Source: https://apigenie.pl/docs/reference/generator/client-elixir Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate an Elixir client on [Req](https://hexdocs.pm/req) from an OpenAPI document. From an AsyncAPI document, the command generates a WebSocket and Kafka client library instead; see [`apigenie-generator client elixir` (AsyncAPI)](/docs/reference/generator/client-elixir-asyncapi). ## Usage ```sh apigenie-generator client elixir [...OPTIONS] INPUT_FILE ``` ## Description The generator writes a Mix project (Elixir 1.18 or later) depending on Req 0.5 or later and Jason. Its code passes `mix format --check-formatted`, `mix compile --warnings-as-errors`, `mix credo --strict` and `mix dialyzer`. The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)). | File | Contents | | ---- | -------- | | `lib/.ex` | the root module, with `new/1` creating a client | | `lib//api/.ex` | a module per tag (`Default` for operations without tags), with a function per operation | | `lib//models/*.ex` | a module per schema: structs, enums, unions and aliases, with `new/1`, `new!/1` and `to_map/1` | | `lib//client.ex`, `api_error.ex` | the client struct and the error of operations | | `lib//metadata.ex` | the servers and the security schemes of the document | | `lib//runtime/*.ex`, `models/decode.ex`, `models/encode.ex` | the encoding of parameters and bodies, and the decoding of responses | | `mix.exs`, `.formatter.exs`, `.gitignore`, `README.md` | the project | ```elixir client = CarpetExpress.new( base_url: "https://api.example.com/v2", auth: [bearer_jwt: System.fetch_env!("API_TOKEN")], req_options: [receive_timeout: 10_000, retry: :transient] ) {:ok, shipment} = CarpetExpress.Api.Shipments.get_shipment(client, shipment_id: "shp_123") shipment = CarpetExpress.Api.Shipments.get_shipment!(client, shipment_id: "shp_123") ``` ### Functions Every operation is a function named after its `operationId` in snake_case, in the module of its first tag: - `op(client, params \\ [], opts \\ [])`, or `op(client, body, params \\ [], opts \\ [])` when the operation has a request body; - `params` is a keyword list of the path, query, header and cookie parameters, keyed by their names in snake_case (`shipment_id: "..."`, `if_match: ...`); missing required parameters and unknown ones give an error before anything is sent; - `opts` are the options of the call: `:content_type` (the media type of the body when the operation accepts several), `:headers` and `:req_options` (options of `Req.request/2`, e.g. `retry: false` or `into: File.stream!("label.pdf")`). A `!` variant of each function returns the body itself and raises the error. ### Responses and errors A response with a 2XX status gives `{:ok, body}`: the body decoded into its model (`new/1` of its module), a list of them, a string for `text/*` media types, the bytes for other media types, or `nil` without content. Any other status gives `{:error, %ApiError{reason: :status}}`, with the `status`, the `headers` and the decoded `body` (a problem document, the error's model). The other reasons are `:transport` (the request failed), `:decode` (the body doesn't match its schema), `:params` and `:auth`. Since 0.12.0, a `text/event-stream`, JSON Lines (`application/jsonl`, `application/x-jsonlines`, `application/x-ndjson`, `application/ndjson`) or `application/json-seq` response gives `{:ok, stream}`, a lazy stream of its items. Each item is decoded as it arrives. A JSON Lines or JSON text sequence item is a JSON value, decoded with the `itemSchema` of the media type (OpenAPI 3.2) when there is one. An event is the map of its fields, with the string keys `"data"` (its lines joined), `"event"`, `"id"` and `"retry"` (an integer); an event without a `data` field isn't an item. An `itemSchema` decodes that map, into its model when the schema is an object. Without an `itemSchema`, the item is the map. Such operations are sent with `into: :self` and `compressed: false` unless `:req_options` sets `:into`. Enumerating the stream raises `.Models.Decode.Error` for an item that doesn't match the `itemSchema`, and `JSON.DecodeError` for a line that isn't JSON. Enumerate it in the process that made the call. ### Parameters and bodies Parameters are encoded in their styles: `simple`, `label` and `matrix` path parameters, `form`, `spaceDelimited`, `pipeDelimited` and `deepObject` query parameters, headers, cookies, and parameters described with `content` as JSON. Models, enums (atoms), dates and times are encoded with their schemas. | Media type | Body | | ---------- | ---- | | JSON (`application/json`, `*+json`) | a model struct or a plain map | | `application/x-www-form-urlencoded` | a model struct or a map, its fields in the styles of their `encoding` | | `multipart/form-data` | a map or a keyword list of the parts: files as `{content, filename: ..., content_type: ...}` or the content alone, lists of files, values and JSON parts | | `text/event-stream`, JSON Lines, `application/json-seq` | since 0.12.0, an enumerable of items, each encoded with the `itemSchema` and sent as it is enumerated | | `text/*` | a string | | anything else | iodata, or an enumerable of chunks | ### Servers The base URL is the first server of the document, or the `:base_url` option of `new/1`. Operations with servers of their own are sent there, unless `operation_servers: false`. ### Security `new/1` takes the credentials by security scheme in `:auth`, keyed by the scheme names in snake_case (`CarpetExpress.Metadata.security_schemes/0` lists them). A credential is the value (an API key, a token, `{user, password}` for HTTP basic) or a supplier called before each request (`fn -> {:ok, token} end`, or `{module, function, args}`), e.g. to fetch and refresh OAuth2 tokens. Each request uses the first security requirement of its operation whose schemes all have a credential: API keys in headers, the query or cookies, HTTP bearer and basic, OAuth2 and OpenID Connect tokens as bearer tokens. Mutual TLS is set up with `req_options: [connect_options: [transport_opts: [certfile: ..., keyfile: ...]]]`. ### Types The models are the modules of [the Elixir models](/docs/reference/generator/client-elixir#types): a struct per object (with `allOf` flattened), atoms for string enums, a module dispatching on the discriminator for `oneOf` and `anyOf`, `Date`, `DateTime`, `NaiveDateTime` and `Time` for dates and times, binaries for `format: byte` (decoded from base64) and `format: binary`, `additional_properties` maps, and `| nil` for nullable values. Since 0.12.0, the models check the constraints of the schemas: `minLength`, `maxLength` and `pattern`, `minimum`, `maximum`, their exclusive forms and `multipleOf`, `minItems`, `maxItems` and `uniqueItems`, `minProperties` and `maxProperties`. `new/1` and the decoding of responses check them; a response that breaks one gives `{:error, %ApiError{reason: :decode}}`. A struct built as a literal is sent unchecked. `prefixItems` are Elixir tuples when the array is closed (`items: false`), `minItems` requires every position, and each position is a scalar, an enum or a model, not nullable, with types short enough for the tuple's type to fit on one line (60 characters). Otherwise they are lists whose first items are checked against the positions. The entries whose keys match `patternProperties` are in the `additional_properties` map, each checked with the schema of its pattern. `if`/`then`/`else`, `dependentRequired` and `dependentSchemas` are checked between the properties of a struct when they only test the presence and the values of properties. Since 0.12.0, `readOnly` properties are left out of request bodies and `writeOnly` properties ignored in responses. Neither is a required field of the struct. ### Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | name of the module of a component schema, unless `module_overrides` names it | | `x-apigenie.codegen.action-name` | name of the function of an operation without an `operationId` (with the default `action_naming`, which lists `id` first) | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out | | `x-internal` | `true` on an operation or its path item leaves the operation out, unless `internal_operations` is set | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn't mapped | The extensions can live in an overlay for this target instead of in the document, e.g. `elixir.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Elixir names version: 1.0.0 actions: - target: $.components.schemas.Pet update: x-apigenie: codegen: name: Animal - target: $.paths['/admin'] update: x-internal: true ``` ```sh apigenie-generator client elixir openapi.yaml --overlay elixir.overlay.yaml -o out ``` ### Limitations - Links aren't generated, and neither are receivers of callbacks and webhooks (`server phoenix` generates their senders). - Conditions between properties that test more than their presence and values (a `pattern` in an `if` schema, for example) aren't checked. - A `pattern` that Elixir's `Regex` doesn't compile matches every string. The value isn't checked, and in `patternProperties` that pattern's schema checks every key no earlier pattern matches. - A property matching several `patternProperties` is checked against the first pattern only. ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.client_elixir.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. Not for a `.proto` input. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the project is generated. ### --package-name Name of the Mix application, converted to snake_case (`carpet-express` gives `carpet_express` and the root module `CarpetExpress`). Defaults to the name of the output directory. ### --package-version Version of the Mix project; `0.1.0` by default. ### -p, --property NAME=VALUE Sets a generator option (see below), e.g. `-p dev_deps=false`. Options given on the command line take precedence over the configuration file. Lists are comma-separated (`-p include_tags=pets,store`) and mappings too (`-p module_overrides=pet-owner=Owner`). ## Configuration ```yaml version: '1.0' commands: generate: client_elixir: app: carpet_express namespace: CarpetExpress exclude_tags: [internal] ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `app` | string | name of the output directory | Name of the Mix application (snake_case, the directory under `lib/`); also set by `--package-name`. | | `namespace` | string | the application in PascalCase | Root module of the generated modules, e.g. `CarpetExpress`. | | `include_tags` | list of strings | | Generates only the operations with one of these tags. | | `exclude_tags` | list of strings | | Skips the operations with one of these tags. | | `skip_prune` | boolean | `false` | Keeps the component schemas that no generated operation uses. | | `internal_operations` | boolean | `false` | Also generates the operations marked `x-internal: true`. | | `dev_deps` | boolean | `true` | Lists credo and dialyxir as dependencies of `mix.exs` (`only: :dev`). | | `action_naming` | list of `id`, `extension`, `url` | `id, extension, url` | Where function names come from, in order of preference. | | `field_prefix` | string | `field_` | Prefix of struct fields whose property names give no valid name. | | `module_overrides` | map of strings | | Module names of component schemas, e.g. `pet-owner: Owner`. | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 37 of 37 operations pass (elixir) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator client fetch Source: https://apigenie.pl/docs/reference/generator/client-fetch Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 1](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a TypeScript client for the Fetch API from an OpenAPI document. ## Usage ```sh apigenie-generator client fetch [...OPTIONS] INPUT_FILE ``` ## Description The generator writes TypeScript sources with no runtime dependencies: requests go through the global `fetch()` (or one you pass), so the client runs in browsers and in Node.js 18 or later. The input is an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)). | File | Contents | | ---- | -------- | | `src/types.ts` | a type per component schema, the `...Params` interface of each operation, and the named types of inline bodies | | `src/operations.ts` | an `async` function per operation, and a function per streamed response format | | `src/metadata.ts` | `DEFAULT_BASE_URL`, the `AuthCredentials` interface and `SECURITY_SCHEMES` | | `src/runtime.ts` | `configure()`, `ApiError`, parameter serialization, authentication, body encoding | | `src/index.ts` | exports the types, the operations and the public part of the runtime | | `package.json`, `tsconfig.json` | an ES module package built with `tsc` into `dist/` (`layout: package` only) | With `layout: sources`, the five files are written directly to the output directory, to be compiled as part of your own project. A client of a shipping API, generated with `layout: sources` into `api/`: ```ts import { configure, ApiError, listShipments, getShipment, downloadLabelFile } from "./api/index.js"; configure({ baseUrl: "https://eu.api.carpetexpress.example/v2", auth: { apiKey: "ce_live_123", // sent in the X-Api-Key header oauth2: () => fetchAccessToken(), // called before every request that needs it }, }); try { const page = await listShipments({ status: ["in_transit", "delivered"], limit: 20 }); const shipment = await getShipment( { shipmentId: "shp_01J9Z", expand: ["labels"] }, { signal: AbortSignal.timeout(5000), headers: { "X-Request-Id": "req-1" } }, ); const label: Blob = await downloadLabelFile({ labelId: "lbl_1", extension: "pdf" }); } catch (error) { if (error instanceof ApiError) { console.error(error.status, error.body); // status 0: no response was received } } ``` ### Configuration at run time `configure(settings)` sets the client-wide settings; settings it doesn't give keep their values. Every operation function also takes an optional last argument, `RequestOptions`, with the same settings for that call only, and an `AbortSignal`. | Setting | Meaning | | ------- | ------- | | `baseUrl` | Base URL of the API. Defaults to `DEFAULT_BASE_URL`: the URL of the document's first server when it is absolute and has no variables, otherwise empty. A call without a base URL throws an `ApiError`, unless the operation has an absolute server of its own (see Servers). | | `fetch` | The `fetch()` implementation; the global one by default. | | `headers` | Headers sent with every request. | | `auth` | Credentials, by security scheme name (`AuthCredentials`). | | `operationServers` | Since 0.12.0. Whether an operation with servers of its own is sent to the first of them; `true` by default. With `false`, every request goes to `baseUrl`, for example to a mock server. | | `signal` | `RequestOptions` only: aborts the request. | ### Operations Every operation is an exported `async` function named after its `operationId` in camel case (`list_shipments` becomes `listShipments`), or after its method and path when it has none (`GET /pets/{id}` becomes `getPetsId`); see `action_naming`. The summary and the description become its JSDoc comment, and deprecated operations are marked `@deprecated`. ```ts export async function getShipment(params: GetShipmentParams, options?: RequestOptions): Promise export async function listShipments(params: ListShipmentsParams = {}, options?: RequestOptions): Promise export async function getAccount(options?: RequestOptions): Promise ``` - **Parameters** of all locations (path, query, header, cookie) are properties of one `...Params` object, under their names in the document (`params["If-Match"]`). A name used in two locations gets the location as a prefix for the second one (`queryId`). `Accept`, `Content-Type` and `Authorization` header parameters are left out. When no parameter is required, the object defaults to `{}`. - **Serialization** follows each parameter's `style` and `explode`: `simple`, `label` and `matrix` path parameters; `form`, `spaceDelimited`, `pipeDelimited` and `deepObject` query parameters. Values that are `undefined` or `null` are not sent; `Date` values are sent in ISO 8601 form. Since 0.12.0, a parameter described by `content` in a JSON media type instead of a `schema` is sent as its JSON text, URL-encoded in a query (`near=%7B%22type%22%3A%22Point%22...`) or a path. - **The request body** is the `body` property of the params (`requestBody` when a parameter is already named `body`). An operation with several request media types gets one: JSON first, then `application/x-www-form-urlencoded`, `multipart/form-data`, `text/*`, and other types. JSON bodies are typed by their schema and sent with `JSON.stringify`; form bodies are objects (or `URLSearchParams`), multipart bodies `FormData`, text bodies `string`, and other media types `Blob`. Since 0.12.0, an operation with several request media types of the preferred one's kind (two JSON types, for example) can send any of them. The params get a `contentType` property (`bodyContentType` when a parameter has that name): a union of those media types that defaults to the preferred one. A JSON or form body is typed as the union of their schemas' types, and the type check doesn't tie the body to the media type. Media ranges such as `image/*` are not offered. Multipart bodies are always sent as `multipart/form-data`, the type `fetch` gives a `FormData` body. ```ts await updateShipment({ shipmentId, "If-Match": etag, body: [{ op: "remove", path: "/metadata" }], contentType: "application/json-patch+json", }); ``` - **Servers.** Since 0.12.0, an operation with `servers` of its own, or whose path item has them, is sent to the first of them, unless it is the document's first server. Each server variable takes its default value. An absolute server URL is used in place of `baseUrl`, even when `baseUrl` is configured. A relative one is resolved against `baseUrl` as a URL reference, so one starting with `/` replaces the path of `baseUrl`. In a browser, a relative `baseUrl` is itself resolved against the page's address. Without a `baseUrl`, or with a relative `baseUrl` outside a browser, the call fails with an `ApiError`. `operationServers: false` sends every request to `baseUrl`. - **Left-out operations.** Since 0.12.0, an operation marked `x-internal: true`, or whose path item is, is left out unless `internal_operations` is `true`. One marked `x-apigenie.codegen.disabled: true` is always left out. - **The result** is the body of the success response (`2XX`, or `default` when no success response is documented): its schema's type for JSON, `string` for `text/*`, `Blob` for other media types. Several success responses give a union (`Promise`), and a response without content adds `undefined`; an operation whose responses have no content returns `Promise`. The `Accept` header is set from the media type of the response. - **Streams.** Since 0.12.0, an operation with a success response in `text/event-stream` or JSON Lines (`application/jsonl`, `application/x-ndjson`, `application/x-jsonlines`) also gets a function per format. It is named after the operation with `EventStream` or `Jsonl` appended, with a number when that name is taken. It takes the same arguments and returns an `AsyncIterable` of the items typed by `itemSchema` (`x-itemSchema` in OpenAPI 3.0 and 3.1 documents). JSON Lines yield one parsed value per non-blank line; a line that isn't JSON throws an `ApiError` whose `body` is the line. Server-sent events yield an object with the event's `data`, `event`, `id` and `retry` fields, a `ServerSentEvent` when no `itemSchema` describes them. `data` is the text of its `data:` lines joined by line feeds, not parsed, and events without data are skipped. The request is sent when the iteration starts, and leaving the loop early closes the connection. The operation's own function keeps reading its preferred media type as a whole. ```ts for await (const event of getTrackingEventsJsonl({ shipmentId: "shp_01J9Z" })) { console.log(event.status); // a TrackingEvent } ``` - **Security** is the operation's requirements, or the document's when the operation declares none. Before the request is sent, the first alternative whose credentials are all configured is applied; when none is, the request goes out without credentials. ### Types Component schemas become exported interfaces (plain objects) or type aliases, named in Pascal case (`user_profile` becomes `UserProfile`, `x-apigenie.codegen.name` overrides the name): | Schema | TypeScript | | ------ | ---------- | | object with properties | `interface`; optional properties are marked `?`, deprecated ones `@deprecated` | | `additionalProperties` | `Record`, or an index signature next to properties; `false` without `patternProperties`: no index signature, or `Record` without properties | | `patternProperties` | with `additionalProperties: false` or a schema object: the union of the pattern schemas' types (and `T`) in the `Record` or the index signature, since 0.12.0; ignored without `additionalProperties` or with `true` | | `enum`, `const` | union of literals (`"available" \| "sold"`, `1 \| 2 \| 3`) | | `oneOf`, `anyOf` | union (`Circle \| Square`) | | `allOf` | intersection (`Shape & { name?: string }`) | | `prefixItems` | tuple (`[number, number]`) | | `type: [T, "null"]`, OpenAPI 3.0 `nullable: true` | `T \| null` | | `format: binary` string | `Blob` | | other strings, `date-time` included | `string` | | `integer`, `number` | `number` | | `{}` | `unknown` | Recursive schemas refer to themselves (`children?: Tree[]`). The client doesn't validate values against their schemas: constraints such as `minimum`, `pattern` or `if`/`then`/`else` generate no code. ### Authentication `AuthCredentials` has an optional property per security scheme of the document. A credential is a string, or a function returning a string or a promise of one, called before every request that needs it (to refresh tokens). | Scheme | Sent as | | ------ | ------- | | `apiKey` | the header, query parameter or cookie the scheme names | | `http` with `scheme: basic` | `Authorization: Basic ...`, the credential being `user:password` | | `http` with `scheme: bearer` | `Authorization: Bearer ` | | other `http` schemes | `Authorization: ` | | `oauth2`, `openIdConnect` | `Authorization: Bearer ` | The client implements no OAuth 2.0 flow: it sends the access token you supply. ### Errors Every failure is an `ApiError` (a subclass of `Error`) with: | Property | Value | | -------- | ----- | | `status` | the HTTP status, or `0` when no response was received | | `body` | the response body: parsed JSON for JSON media types, otherwise text, `undefined` when empty | | `response` | the `Response`, when there was one | | `cause` | the underlying error, e.g. a network error or a `SyntaxError` of invalid JSON | A response with a status outside 200-299 throws, as does a success response whose JSON can't be parsed. So do a network failure, a missing path parameter, and a missing base URL for an operation without an absolute server of its own. A stream function throws them from the first iteration. ### Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | name of the type of a component schema | | `x-apigenie.codegen.action-name` | name of the function of an operation, when `action_naming` lists `extension` | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn't mapped | | `x-itemSchema` | `itemSchema` of a media type in OpenAPI 3.0 and 3.1 documents: the type of the items of a streamed response | | `x-apigenie.codegen.disabled` | since 0.12.0, `true` on an operation or its path item leaves the operation out | | `x-internal` | since 0.12.0, `true` on an operation or its path item leaves the operation out, unless `internal_operations` is `true` | The extensions can live in an overlay for this target instead of in the document, e.g. `fetch.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: TypeScript names version: 1.0.0 actions: - target: $.components.schemas.Pet update: x-apigenie: codegen: name: Animal ``` ```sh apigenie-generator client fetch openapi.yaml --overlay fetch.overlay.yaml -o out ``` ### Limitations The features of the conformance fixture the client doesn't support yet are listed under [Verification](#verification). Beyond them: - Form-encoded bodies don't apply the `encoding` styles of their properties: an object property is sent as `[object Object]`. - Callbacks, webhooks and links aren't generated: they describe requests the server makes, or documentation. - Documents referencing other files must be bundled first with [`apigenie bundle`](/docs/reference/cli/bundle). ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.client_fetch.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Required. Directory where the client is generated. ### --package-name Name of the npm package in `package.json`. Defaults to the document's `info.title` in lower case with hyphens between words (`Carpet Express Shipping API` becomes `carpet-express-shipping-api`), or `api-client` when the title has no letters or digits. ### --package-version Version of the npm package in `package.json`. Defaults to the document's `info.version`, or `0.0.0` when it is empty. ## Configuration ```yaml version: '1.0' commands: generate: client_fetch: layout: sources import_extension: '' action_naming: [id, extension, url] internal_operations: true ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `layout` | `package` or `sources` | `package` | `package` writes an npm package (`package.json`, `tsconfig.json`, sources in `src/`); `sources` writes only the sources, directly in the output directory. | | `import_extension` | `.js` or `''` | `.js` | Extension of relative imports between the generated files: `.js` for Node.js ES modules (`NodeNext` resolution), `''` for bundlers. | | `action_naming` | `id`, `extension`, `url`, or a list of them | `[id, url]` | Where function names come from, in order of preference: the `operationId`, the `x-apigenie.codegen.action-name` extension, or the method and path. | | `internal_operations` | boolean | `false` | Since 0.12.0. Also generates the operations marked `x-internal: true` on the operation or its path item. | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Tier 1](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, with the goal of supporting every feature of the fixture. Its unsupported features are worked on first. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 29 supported, 0 not yet, 5 not checked | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8) | ✓ 40 of 40 operations pass (node) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 29 supported, 0 not yet, 5 not checked | runs before a release | runs before a release | --- # apigenie-generator client go Source: https://apigenie.pl/docs/reference/generator/client-go Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 1](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Go client for the `net/http` package of Go 1.22 from an OpenAPI document. From an AsyncAPI document, the command generates a Go Kafka client package instead; see [`apigenie-generator client go` (AsyncAPI)](/docs/reference/generator/client-go-asyncapi). ## Usage ```sh apigenie-generator client go [...OPTIONS] INPUT_FILE ``` ## Description The generator writes a Go package whose code uses the standard library only: its `go.mod` has no requirements. It shares the types, validation and parameter codecs with [`apigenie-generator server go`](/docs/reference/generator/server-go), so a client and a server generated from the same document read and write values the same way. | File | Contents | | ---- | -------- | | `types.gen.go` | the types of the component schemas the operations use, and of their inline schemas, with `Validate()` methods | | `client.gen.go` | `DefaultBaseURL`, `Servers`, `SecuritySchemes`, `Operations`, `NewClient`, an option per security scheme, and per operation its parameters, bodies, response type and methods | | `runtime_*.gen.go` | the `Client`, requests and errors, parameter encoding, streams, multipart bodies, validation, `Nullable[T]`, `Date` | | `go.mod` | with `layout: module` | ```go client, err := api.NewClient( api.WithBaseURL("https://api.example.com/v1"), // DefaultBaseURL otherwise api.WithAPIKey(os.Getenv("API_KEY")), api.WithHTTPClient(&http.Client{Timeout: 30 * time.Second}), ) if err != nil { return err } res, err := client.GetPet(ctx, 42, nil) var apiErr *api.APIError switch { case errors.As(err, &apiErr): log.Printf("status %d: %v", apiErr.StatusCode, apiErr.Problem) // RFC 9457 problem details case err != nil: return err // transport, encoding or decoding error default: fmt.Println(res.JSON200.Name) } ``` ### Methods Every operation is a method of `Client`, named after its `operationId`, whose first argument is a `context.Context`, followed by the path parameters, a pointer to a struct with the query, header and cookie parameters (`nil` when none is set), the body, and request editors changing the request before it is sent: ```go func (c *Client) CreatePet(ctx context.Context, params *CreatePetParams, body NewPet, reqEditors ...RequestEditorFn) (*CreatePetResponse, error) func (c *Client) CreatePetWithBody(ctx context.Context, params *CreatePetParams, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreatePetResponse, error) ``` - An operation with several request media types gets a method per media type (`UpdatePetWithApplicationMergePatchJSONBody`; the bare name sends `application/json`), and always a `...WithBody` method taking the media type and an `io.Reader`. - JSON bodies are values of their types, validated with `Validate()` before they are sent (`validate_requests: false` turns that off); `text/*` bodies are strings, other media types `io.Reader` values, and `application/jsonl` bodies slices of the items of their `itemSchema`. - `application/x-www-form-urlencoded` bodies are encoded field by field with the styles of their `encoding` (`deepObject`, delimited arrays, JSON fields). - Parameters are serialized in their style and `explode` mode: `simple`, `label` and `matrix` path parameters, `form`, `spaceDelimited`, `pipeDelimited` and `deepObject` query parameters, `allowReserved`, headers and cookies. Parameters described with `content` are sent as JSON. - Methods set the `Accept` header to the media types of the documented responses. - Operations marked `x-internal: true` (on the operation or its path) are left out, unless `internal_operations` is set. ### Responses A method returns a response struct with one field per documented status and media type, set for the response received, next to the raw `*http.Response`: ```go type GetPetResponse struct { HTTPResponse *http.Response Body []byte // the body, when it was read Headers200 *GetPet200Headers // typed response headers JSON200 *Pet // 200, application/json ApplicationPdf200 io.ReadCloser // 200, application/pdf: left open ApplicationProblemJSON404 *ProblemDetails // 404, application/problem+json ApplicationProblemJSONDefault *ProblemDetails } ``` - The field names join the media type (`JSON` for `application/json`, `Text` for `text/plain`, `EventStream`, `JSONL`, the media type otherwise) and the status (`200`, `2XX`, `Default`). - `application/problem+json` contents are `*ProblemDetails` (type, title, status, detail, instance and the other members in `Extensions`), whatever their schema. - Binary contents and streams are left open: close the field, or the response with `Close()`. Other bodies are read, kept in `Body`, and closed. - For a status of 400 or more, the method returns the response and an `*APIError` with the status, the problem details of an `application/problem+json` body, the body and the response. `errors.As(err, &problem)` also finds the `*ProblemDetails`. - An undocumented status or media type sets no field: `Body` holds the body. - Response headers that can't be parsed are left unset; their text stays in `HTTPResponse.Header`. ### Streams `text/event-stream` and `application/jsonl` contents are iterators over their items, typed by the `itemSchema` of the media type (OpenAPI 3.2; `x-itemSchema` in 3.0 and 3.1 documents): ```go res, err := client.GetTrackingEvents(ctx, id, nil) if err != nil { return err } defer res.Close() if events := res.EventStream200; events != nil { for events.Next() { event := events.Item() // the itemSchema type, filled from id, event, data and retry fmt.Println(event.Event, event.Data) } if err := events.Err(); err != nil { return err } } ``` - `JSONLStream[T]` reads one JSON value per line. `EventStream[T]` follows the server-sent events parsing rules of the HTML standard (`data` lines joined, comments, `id`, `retry`); `Event()` returns the event as received and `LastEventID()` the ID to resume from with `Last-Event-ID`. - Without `itemSchema`, server-sent events are `ServerSentEvent` values and JSON Lines items `json.RawMessage` values. - Go 1.22 has no range-over-func iterators, hence `Next()`, `Item()` and `Err()`. ### Multipart bodies `multipart/form-data` bodies of object schemas are structs with a field per part: - Binary parts (`format: binary`, or `contentMediaType` in 3.1 and 3.2) are `File` values (a name, a media type, a reader and extra part headers), arrays of them `[]File`. A file part is sent with the `contentType` of its encoding, or its `contentMediaType`, unless `File.ContentType` is set. Headers the encoding declares are set through `File.Header`. - Object parts, and parts whose encoding has a JSON `contentType`, are sent as JSON; other parts as text, a part per item of arrays. The body is built in memory and sent with its boundary. ### Servers `DefaultBaseURL` is the first server of the document with an absolute URL, the default values of its variables applied; `WithBaseURL` sets another one, and is required when there is none. Operations with servers of their own (on the operation or its path) are sent there, a relative server URL being resolved against the base URL; `WithOperationServers(false)` sends every request to the base URL instead, e.g. to a test server or a proxy. ### Security Every security scheme of the document gets an option setting its credentials, named `With` followed by the name of the scheme: | Scheme (name in the document) | Option | | ----------------------------- | ------ | | `apiKey` in a header, the query or a cookie (`apiKey`) | `WithAPIKey(key string)` | | `http` `bearer`, `oauth2`, `openIdConnect` (`oauth2`) | `WithOauth2(token string)`, sent as a bearer token | | `http` `basic` (`basicAuth`) | `WithBasicAuth(username, password string)` | A request gets the credentials of the first alternative of its operation's security requirements whose schemes all have credentials, so an API key in the query is only sent to the operations that accept it; an operation with `security: []` gets none. `WithSecurity(scheme, editor)` sets the credentials of any scheme with a `RequestEditorFn`; obtaining and refreshing OAuth2 tokens is up to the caller. `mutualTLS` needs a client certificate in the transport of the `http.Client` (`WithHTTPClient`). ### Types - Optional properties are pointers with `omitempty`; slices, maps and `any` stay values. `optional_fields: omitzero` uses values with `omitzero` (Go 1.24). - Optional properties that can be null are `Nullable[T]`, which tells absent, null and set values apart; required ones are pointers. `nullable_type: pointer` uses pointers for both. - Enums are defined types with constants named after the type and the value (`PetStatusAvailable`). - `oneOf` and `anyOf` schemas are structs with one pointer per variant. With a discriminator, the value goes to the variant its property selects: through the `mapping`, the name of the schema or the value the schema gives the property (`const`); other values go to the `defaultMapping` variant (`x-defaultMapping` in 3.0 and 3.1 documents), or are kept in `Raw`. Without a discriminator, the value goes to the first variant it decodes into. - `allOf` schemas are merged into one struct; an `anyOf` or `oneOf` whose members only list required properties (`anyOf: [{required: [email]}, {required: [phone]}]`) is checked by `Validate()`. - since 0.12.0, `prefixItems` tuples and `patternProperties` maps are typed and checked as by [`server go`](/docs/reference/generator/server-go#types). `Validate()` checks `dependentRequired`, and `if`/`then`/`else`, `dependentSchemas`, `not` and draft-07 `dependencies` within the limits below. - `date-time` strings are `time.Time`, `date` strings `Date`, `byte` and `binary` strings `[]byte`, and so are `contentEncoding: base64` strings. ### Extensions | Extension | Effect | | --------- | ------ | | `x-go-name` | name of the type of a schema, or of the field of a property | | `x-go-type` | Go type of a schema, e.g. `decimal.Decimal`; with `x-go-type-import: {path: ...}` for its package | | `x-go-type-skip-optional-pointer` | the optional property isn't a pointer | | `x-go-json-ignore` | the field gets the tag `json:"-"` | | `x-omitempty` | `true` or `false` overrides the `omitempty` of the field | | `x-enum-varnames`, `x-enumNames` | names of the enum constants | | `x-enum-descriptions` | comments of the enum constants | | `x-apigenie.codegen.name` | name of the type of a component schema, when it has no `x-go-name` | | `x-apigenie.codegen.action-name` | name of the method of an operation without an `operationId` (with the default `action_naming`, which lists `id` first) | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out | | `x-internal` | `true` on an operation or its path item leaves the operation out, unless `internal_operations` is set | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn't mapped | | `x-itemSchema` | `itemSchema` of a media type in OpenAPI 3.0 and 3.1 documents: the type of the items of a streamed response | The extensions can live in an overlay for this target instead of in the document, e.g. `go.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Go types version: 1.0.0 actions: - target: $.components.schemas.Pet update: x-go-name: Animal - target: $.components.schemas.Pet.properties.price update: x-go-type: decimal.Decimal x-go-type-import: path: github.com/shopspring/decimal ``` ```sh apigenie-generator client go openapi.yaml --overlay go.overlay.yaml -o out ``` ### Limitations - Callbacks, webhooks and links aren't generated: they describe requests the server makes or documentation ([`server go`](/docs/reference/generator/server-go#webhooks-and-callbacks) writes the senders of webhooks and callbacks). - `Validate()` doesn't check `unevaluatedProperties`, nor patterns using lookaround or backreferences. It checks `if`/`then`/`else`, `not`, `dependentSchemas` and the schemas of draft-07 `dependencies` only when their schemas use `required` and the `const` and `enum` of properties, and skips the others. - Multipart bodies are built in memory; there are no retries or rate limiting beyond what the `http.Client` does. - Exported names of the runtime (`Client`, `File`, `Server`, `Operation`, `ProblemDetails`, `Date`, `Nullable`, ...) are reserved: schemas with these names get numbered types, e.g. `File2`. - The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle documents referencing other files with `apigenie bundle`. ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.client_go.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the package is generated. ### --package-name Name of the Go package. Defaults to the name of the output directory (`api` when it isn't a valid package name). ### --package-version Ignored: Go packages have no version. ### -p, --property NAME=VALUE Sets a generator option (see below), e.g. `-p layout=module`. Options given on the command line take precedence over the configuration file. Lists are comma-separated (`-p include_tags=pets,store`) and mappings too (`-p type_mappings=uuid=github.com/google/uuid.UUID`). ## Configuration ```yaml version: '1.0' commands: generate: client_go: package: petstore layout: module module: github.com/acme/petstore type_mappings: uuid: github.com/google/uuid.UUID ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `package` | string | name of the output directory | Name of the Go package; also set by `--package-name`. | | `layout` | `package` or `module` | `package` | `module` also writes `go.mod`, making the output a module of its own. | | `module` | string | `example.com/` | Module path written to `go.mod`. | | `optional_fields` | `pointer` or `omitzero` | `pointer` | Optional properties as pointers with `omitempty`, or as values with `omitzero` (Go 1.24). | | `nullable_type` | `tristate` or `pointer` | `tristate` | Optional nullable properties as `Nullable[T]`, or as pointers. | | `include_tags` | list of strings | | Generates only the operations with one of these tags. | | `exclude_tags` | list of strings | | Skips the operations with one of these tags. | | `skip_prune` | boolean | `false` | Keeps the component schemas that no generated operation uses. | | `internal_operations` | boolean | `false` | Also generates the operations marked `x-internal: true`. | | `validate_requests` | boolean | `true` | Validates request bodies against their schemas before sending them. | | `initialisms` | list of strings | | Words written in upper case in identifiers, besides `ID`, `URL`, `HTTP`, `JSON` and the other initialisms of golint. | | `type_mappings` | map of strings | | Go types of string formats or `x-go-type` names, e.g. `uuid: github.com/google/uuid.UUID`. | | `action_naming` | list of `id`, `extension`, `url` | `id, extension, url` | Where method names come from, in order of preference. | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Tier 1](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, with the goal of supporting every feature of the fixture. Its unsupported features are worked on first. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (go version go1.22.5 linux/amd64) | ✓ 37 of 37 operations pass (go) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator client java Source: https://apigenie.pl/docs/reference/generator/client-java Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 1](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Java client of an OpenAPI document: a Maven project using Spring's `RestClient` (the default) or `RestTemplate`, Spring Cloud OpenFeign interfaces, or Spring HTTP interfaces. From an AsyncAPI document, the command generates a Java Kafka client library instead; see [`apigenie-generator client java` (AsyncAPI)](/docs/reference/generator/client-java-asyncapi). ## Usage ```sh apigenie-generator client java [...OPTIONS] INPUT_FILE ``` ## Description The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)). The generated project needs Java 17 and Maven; its dependencies come from Maven Central. ```java ApiClient client = new ApiClient(); client.setBearerToken("token"); PetsApi pets = new PetsApi(client); List page = pets.listPets(10, null); ResponseEntity response = pets.getPetWithHttpInfo(42L); try (Stream events = pets.watchPetsStream()) { events.limit(5).forEach(System.out::println); } ``` `--library` selects how the client calls the API: | Library | Output | | ------- | ------ | | `restclient` (default) | `ApiClient` on Spring's `RestClient`, one class per API | | `resttemplate` | the same classes, with `ApiClient` on Spring's `RestTemplate` | | `feign` | Spring Cloud OpenFeign: `@FeignClient` interfaces extending Spring MVC interfaces, request interceptors of the security schemes | | `http-interface` | Spring HTTP interfaces (`@HttpExchange`) and a configurator creating their proxies with a `RestClient` (or a `WebClient` with `reactive`) | The `feign` and `http-interface` libraries are the clients the `spring-cloud` and `spring-http-interface` libraries of `apigenie-generator server spring` generate, with the options of the client. The rest of this section describes the `restclient` and `resttemplate` libraries. Their API classes are grouped by the first tag of operations (`Api`); each operation has: - `op(...)`, returning the body of the response (`void` without content); - `opWithHttpInfo(...)`, returning the `ResponseEntity`, with the status and the headers; - `opStream(...)` when the response can be streamed as `text/event-stream`, `application/jsonl`, `application/x-ndjson` or `application/json-seq`: a `Stream` of the items, typed by the `itemSchema` of the media type (`x-itemSchema` before 3.2) or the `contentSchema` of the `data` of events, read as they arrive. Closing the stream (try-with-resources) closes the connection. - `opWith(...)` for each further request media type taking another Java type, e.g. `updateShipmentWithJsonPatch(...)` for `application/json-patch+json`. Required parameters come first. Parameters are serialized with their style (form, spaceDelimited, pipeDelimited, deepObject, simple); parameters described with `content` are sent as JSON. Bodies are JSON, JSON Lines (a `List` of items), form fields, multipart parts (Spring `Resource`s for files, JSON parts for objects, the content type of the `encoding`), text or binary (`Resource`). Binary responses are `Resource`s. Methods other than the eight classic ones (QUERY, `additionalOperations`) are sent as they are; the JDK `HttpClient` the client uses allows them. `ApiClient` holds: - the servers of the document (`setServerIndex`, `setServerVariables`) or a base path (`setBasePath`); operations with servers of their own are sent to them, unless `setOperationBasePath(operationId, url)` says otherwise; - one `Authentication` per security scheme, added to the operations requiring it: `setBearerToken` (HTTP bearer and OpenID Connect schemes, and OAuth 2 schemes whose tokens are obtained elsewhere), `setOAuthClientCredentials` (OAuth 2, since 0.12.0), `setApiKey` (headers, query parameters and cookies), `setUsername` and `setPassword` (HTTP basic); - the `ObjectMapper` (`createObjectMapper()`: Java time, `JsonNullable`, absent properties left out, unknown properties ignored), default headers and cookies. Since 0.12.0, an OAuth 2 scheme gets an `OAuth` authentication (with the `RestClient` and `RestTemplate` libraries). It holds the endpoints and scopes of the client credentials, authorization code and device authorization flows of the scheme, and each flow uses its own token URL: ```java OAuth oauth = (OAuth) client.getAuthentication("oauth2"); // the name of the security scheme oauth.setClientCredentials("client-id", "secret"); // a null secret for a public client oauth.setScopes(List.of("shipments:read")); // none by default: the server's default String url = oauth.authorizationUrl("https://app.example.com/callback", state); oauth.exchangeAuthorizationCode(code, "https://app.example.com/callback"); OAuth.DeviceAuthorization device = oauth.requestDeviceAuthorization(); oauth.pollDeviceToken(device); // waits until the user enters device.userCode() ``` - With a client credentials flow and client credentials, the client requests a token before the first request, and again once it expires. - A token that comes with a refresh token is renewed with it at the refresh URL of its flow (its token URL without one). - `authorizationUrl` and `requestDeviceAuthorization` send the client id, so call `setClientCredentials` first. `authorizationUrl` adds a PKCE challenge, whose verifier `exchangeAuthorizationCode` sends. A second `authorizationUrl` replaces the verifier of the first, so one authorization runs at a time. - The methods of the authorization code and device authorization flows throw an `IllegalStateException` when the scheme has no such flow. - Token requests use a JDK `HttpClient` of their own, which `setHttpClient` replaces: a client certificate of `withClientCertificate` isn't sent to the token endpoint. - A token set with `setBearerToken` takes precedence, and `setRefreshToken` sets a refresh token obtained elsewhere. A token request that fails raises an `OAuth.OAuthException`, from the API call or from the method that sent it. Its `getError()` tells what happened: | `getError()` | When | The refresh token | | --- | --- | --- | | `invalid_grant` | the server refused the grant | dropped | | another `error` code of the answer | the server refused the request | kept | | `http_` | an error status without an `error` code | kept | | `request_failed` | the server could not be reached, or its answer isn't JSON | kept | | `interrupted` | the thread was interrupted | kept | When a refresh fails and the scheme has a client credentials flow with client credentials set, the client requests a new token with them instead of raising the exception. Since 0.12.0, with a `mutualTLS` scheme (OpenAPI 3.1 and 3.2), `ApiClient.withClientCertificate` creates a client that presents the certificate of a key store. It checks the certificate of the server against a trust store, or against the CAs of the JDK when the trust store is null. `loadKeyStore` reads a PKCS #12 or JKS file, and `sslContext` gives the `SSLContext` for a request factory of your own. Responses with an error status raise an `ApiException` with the status, the headers and the body; `application/problem+json` responses raise a `ProblemDetailsException` with the RFC 9457 problem details, typed as the problem schema of the document. Models are the Jackson classes of `apigenie-generator server spring`, without Swagger annotations: - classes for objects, with the properties of `allOf` members (the properties of `anyOf` and `oneOf` alternatives are optional) - interfaces for `oneOf`: with a discriminator, `@JsonTypeInfo` and `@JsonSubTypes`, its `defaultMapping` (`x-defaultMapping` before 3.2) as `defaultImpl` and the `const` values of the members as the names of implicit mappings; without one, the members are told apart by a property with constant values (`useImplicitOneOfDiscriminator`) or by their properties (`useDeductionForOneOfInterfaces`) - enums, `JsonNullable` for nullable properties, Bean Validation annotations, `java.time` types - `readOnly` properties only read from responses and `writeOnly` ones only sent (`jsonAccessForReadWriteOnly`) - since 0.12.0, tuples (`prefixItems` without an `items` schema): a list of the type their items share (`Object` when they differ), with `@Size(max = …)` when `items: false` closes them - since 0.12.0, `patternProperties` (when `additionalProperties` is absent or `false`). An object without properties or `additionalProperties` whose keys match one pattern is a `Map`. Other objects hold the entries like additional properties (`getAdditionalProperties()`), and read each value as the type of the pattern its key matches. Keys that match no pattern are kept there too. With `additionalProperties: false`, `putAdditionalProperty` throws an `IllegalArgumentException` for them instead, so the object fails to deserialize. - since 0.12.0, with `useBeanValidation` (the default, except with the `http-interface` library): `multipleOf`, checked by `MultipleOf`, a constraint generated in the configuration package. Numbers with a `multipleOf` are annotated with it. - since 0.12.0, with `useBeanValidation`: conditions of a schema (`if`/`then`/`else`, `dependentRequired`, `dependentSchemas`) as `@AssertTrue` methods, such as `isConditionSatisfied()`, `isDependentRequiredSatisfied()` and `isDependentSchemaSatisfied()`. They test which properties are present and the `const` or `enum` values of string, enum and boolean properties; other conditions are left out. Unknown properties of other models are ignored, `unevaluatedProperties: false` included. `x-internal` operations and paths are left out. The project contains `pom.xml` (Spring Framework, Jackson and Jakarta versions from the Spring Boot BOM, without Spring Boot), `README.md`, `.openapi-generator-ignore` (written only when it doesn't exist) and, in the base package, `ApiClient`, `ApiException`, `ProblemDetailsException` (with a problem schema), `ServerConfiguration`, `ServerVariable`, `StreamDecoder` (with streaming responses), `RFC3339DateFormat`, `auth/` (`Authentication`, `HttpBearerAuth`, `HttpBasicAuth`, `ApiKeyAuth`, and `OAuth` with an OAuth 2 scheme), `configuration/` (`MultipleOf`, with a `multipleOf` and `useBeanValidation`), `api/` and `model/`. Not supported: callbacks and webhooks, and the password and implicit flows of OAuth 2 (set their tokens with `setBearerToken`). With the `feign` and `http-interface` libraries, OAuth 2 flows and mutual TLS are not supported: set tokens by hand, and the `SSLContext` on the HTTP client. The `feign` library leaves out operations of methods other than the classic ones. ## Extensions | Extension | Effect | | --------- | ------ | | `x-class-extra-annotation` | annotations of the class of a schema, e.g. `['@Entity']` | | `x-implements` | interfaces the class of a schema implements | | `x-field-extra-annotation` | annotations of the field of a property, or of the method parameter of a parameter (`feign`, `http-interface`) | | `x-extra-annotation` | annotations of the getter of a property | | `x-setter-extra-annotation` | annotations of the setter of a property | | `x-pattern-message`, `x-size-message`, `x-minimum-message`, `x-maximum-message` | `message` of the `@Pattern`, `@Size`, `@Min`/`@DecimalMin` and `@Max`/`@DecimalMax` annotations of a property or a parameter, on its schema, and since 0.12.0 on the parameter itself, as in Swagger 2.0 documents | | `x-jackson-json-include-policy` | `@JsonInclude` policy of a property, e.g. `non_empty` (`none` for no annotation) | | `x-jackson-json-setter-nulls` | `@JsonSetter(nulls = ...)` of a property, e.g. `skip` (`none` for no annotation) | | `x-enum-varnames` | names of the constants of an enum | | `x-enum-descriptions` | Javadoc of the constants of an enum | | `x-parent` | `true` makes a schema the superclass of the schemas extending it with `allOf`, without a discriminator | | `x-discriminator-value` | the discriminator value of a subclass in `@JsonSubTypes` (default: the name of its schema) | | `x-jackson-default-impl` | `defaultImpl` of the `@JsonTypeInfo` of a class with a discriminator | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the `defaultImpl` of `@JsonTypeInfo`, without `x-jackson-default-impl` | | `x-itemSchema` | `itemSchema` of a media type in OpenAPI 3.0 and 3.1 documents: the type of the items of a streamed response | | `x-codegen-request-body-name` | on an operation or its request body: the name of the body parameter | | `x-apigenie.codegen.controller-name` | on an operation: the API class of the operation, instead of its tag or path | | `x-apigenie.codegen.action-name` | name of the method of an operation, instead of its `operationId` | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out, with `skipDisabled` | | `x-internal` | `true` on an operation or its path item leaves the operation out | | `x-operation-extra-annotation` | annotations of the method of an operation (`feign`) | | `x-version-param` | `true` on a header or query parameter adds it to the `headers` or `params` of the `@RequestMapping` (`feign`) | The extensions can live in an overlay for this target instead of in the document, e.g. `java.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Java annotations version: 1.0.0 actions: - target: $.components.schemas.Pet update: x-class-extra-annotation: ['@com.acme.Audited'] x-implements: [java.io.Serializable] - target: $.components.schemas.Pet.properties.name update: x-pattern-message: Lower-case letters only ``` ```sh apigenie-generator client java openapi.yaml --overlay java.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.client_java.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the project is generated. ### --package-name Base package of the generated code, e.g. `com.acme.pets`; the `api`, `model` and `configuration` packages are derived from it unless set explicitly. Defaults to `org.openapitools.client`. ### --package-version Version of the Maven artifact. Defaults to the version of the API. ### --library `restclient` (default), `resttemplate`, `feign` or `http-interface`. Overrides the `library` of the configuration file. ### -p, --property An option of the "Configuration" section as `name=value`, e.g. `-p useBeanValidation=false`. Can be repeated; overrides the configuration file. ## Configuration ```yaml version: '1.0' commands: generate: client_java: library: restclient basePackage: com.acme.pets groupId: com.acme artifactId: pets-client useBeanValidation: true openApiNullable: true typeMappings: DateTime: java.time.Instant ``` The main options: | Option | Description | | ------ | ----------- | | `library` | `restclient` (default), `resttemplate`, `feign` or `http-interface` | | `basePackage`, `apiPackage`, `modelPackage` | Packages of the code (`org.openapitools.client`, `.api`, `.model` by default) | | `groupId`, `artifactId`, `artifactVersion` | Coordinates of the Maven artifact (`org.openapitools`, `openapi-java-client`, the version of the API) | | `useSpringBoot4` | The versions of Spring Boot 4 (Spring Framework 7) instead of Spring Boot 3.5 | | `useBeanValidation` | Bean Validation annotations on models (`true` by default) | | `openApiNullable` | `JsonNullable` for nullable properties (`true` by default) | | `useTags` | Group operations by tag (`true` by default) or by the first segment of their path | | `generateStreamMethods` | `Stream` methods for streaming responses (`true` by default) | | `allHttpMethods` | Operations of every HTTP method (`true` by default; `false` with `feign`) | | `contentMediaTypeAsBinary` | Strings with a non-JSON `contentMediaType` are binary `Resource`s (`true` by default) | | `useImplicitOneOfDiscriminator` | Dispatch `oneOf` schemas on a property with constant values (`true` by default) | | `jsonAccessForReadWriteOnly` | `@JsonProperty(access)` for `readOnly` and `writeOnly` properties (`true` by default) | | `typeMappings`, `importMappings`, `schemaMappings` | Java types of OpenAPI types and schemas | All options: | Option | Description | | ------ | ----------- | | `basePackage` | Base package for generated code | | `invokerPackage` | Alias of basePackage | | `apiPackage` | Package for generated API classes | | `modelPackage` | Package for generated models | | `configPackage` | Package for generated configuration classes | | `groupId` | groupId in the generated pom.xml | | `artifactId` | artifactId in the generated pom.xml | | `artifactVersion` | Artifact version in the generated pom.xml | | `artifactDescription` | Artifact description in the generated pom.xml | | `artifactUrl` | Artifact URL in the generated pom.xml | | `licenseName` | License name in the generated pom.xml | | `licenseUrl` | License URL in the generated pom.xml | | `developerName` | Developer name in the generated pom.xml | | `developerEmail` | Developer email in the generated pom.xml | | `developerOrganization` | Developer organization in the generated pom.xml | | `developerOrganizationUrl` | Developer organization URL in the generated pom.xml | | `scmConnection` | SCM connection in the generated pom.xml | | `scmDeveloperConnection` | SCM developer connection in the generated pom.xml | | `scmUrl` | SCM URL in the generated pom.xml | | `parentGroupId` | groupId of the parent pom | | `parentArtifactId` | artifactId of the parent pom | | `parentVersion` | Version of the parent pom | | `snapshotVersion` | Append -SNAPSHOT to the artifact version | | `title` | Server title, used in property names (defaults to info.title) | | `useSpringBoot3` | Generate code for Spring Boot 3 (jakarta); false means Spring Boot 2 | | `useSpringBoot4` | Generate code for Spring Boot 4 | | `useJackson3` | Use Jackson 3 (tools.jackson) instead of Jackson 2; requires useSpringBoot4 | | `optionalAcceptNullable` | Use Optional.ofNullable in fluent setters of Optional properties | | `useJspecify` | Use JSpecify (org.jspecify.annotations.Nullable) for null checks | | `hideGenerationTimestamp` | Omit the generation date from @Generated annotations (default: `true` since 0.12.0, `false` before) | | `generationTimestamp` | Timestamp used in @Generated annotations when hideGenerationTimestamp is false | | `generatorVersion` | Generator version written into generated files | | `dateLibrary` | Date library: java8, java8-localdatetime, joda or legacy | | `documentationProvider` | springdoc, source or none | | `annotationLibrary` | swagger2 or none | | `interfaceOnly` | Generate only API interfaces, without controllers | | `skipDefaultInterface` | Don't generate default implementations of API methods | | `useTags` | Group operations by tag instead of the first path segment | | `requestMappingMode` | Where to put the class-level @RequestMapping: controller, api_interface or none | | `useResponseEntity` | Wrap return types in ResponseEntity | | `useOptional` | Use Optional for optional parameters | | `returnSuccessCode` | Return the success code instead of 501 Not Implemented | | `unhandledException` | Declare 'throws Exception' on API methods | | `async` | Return CompletableFuture from API methods | | `reactive` | Generate reactive (WebFlux) code | | `responseWrapper` | Wrapper of return types: CompletableFuture, Callable, Future, ListenableFuture, DeferredResult or a fully qualified class name | | `includeHttpRequestContext` | Add the HTTP request (ServerWebExchange / HttpServletRequest) to API methods | | `singleContentTypes` | Use a single content type per operation | | `sortParamsByRequiredFlag` | Put required parameters before optional ones | | `apiNameSuffix` | Suffix of API class names | | `skipDeprecated` | Don't generate code for deprecated operations | | `skipDisabled` | Don't generate code for operations disabled with x-apigenie | | `implicitHeaders` | Describe header parameters with @Parameters instead of method parameters | | `implicitHeadersRegex` | Regular expression of header parameters described with @Parameters | | `useHttpServiceProxyFactoryInterfacesConfigurator` | Use a HttpServiceProxyFactory in HttpInterfacesAbstractConfigurator (spring-http-interface) | | `clientRegistrationId` | @ClientRegistrationId of API interfaces (spring-http-interface, Spring Boot 4) | | `useFeignClientUrl` | Use the url attribute of @FeignClient (spring-cloud) | | `useFeignClientContextId` | Use the contextId attribute of @FeignClient (spring-cloud) | | `useBeanValidation` | Use Bean Validation annotations | | `performBeanValidation` | Use Hibernate Validator annotations | | `useSpringBuiltInValidation` | Rely on Spring's built-in validation (no @Validated) | | `additionalNotNullAnnotations` | Add @NotNull to required path and body parameters | | `openApiNullable` | Use JsonNullable for nullable properties | | `serializableModel` | Make models implement Serializable | | `useOneOfInterfaces` | Represent oneOf schemas as interfaces | | `useDeductionForOneOfInterfaces` | Deduce oneOf subtypes from their properties | | `generatedConstructorWithRequiredArgs` | Generate constructors with required arguments | | `generateConstructorWithAllArgs` | Generate constructors with all arguments | | `generateBuilders` | Generate builders for models | | `sortModelPropertiesByRequiredFlag` | Put required properties first in constructors | | `enumPropertyNaming` | Naming of enum constants: MACRO_CASE, original, legacy, camelCase, PascalCase, snake_case or UPPERCASE | | `useEnumCaseInsensitive` | Match enum values ignoring case | | `withXml` | Add XML annotations to models | | `useSealed` | Use sealed classes and interfaces (Java 17+) | | `containerDefaultToNull` | Initialize containers with null instead of empty ones | | `legacyDiscriminatorBehavior` | Use the legacy discriminator behavior | | `disableDiscriminatorJsonIgnoreProperties` | Don't ignore discriminator properties during serialization | | `modelNamePrefix` | Prefix of model names | | `camelCaseDollarSign` | Keep the case of the first letter after a leading $ in names | | `useEnumValueInterface` | Make enums implement the ValuedEnum interface | | `generateJsonIncludeAnnotations` | Add @JsonInclude annotations to model properties | | `optionalNonNullPropertyJsonInclude` | @JsonInclude policy of optional, non-nullable properties: NON_NULL, NON_EMPTY, NON_DEFAULT or NONE | | `generateJsonSetterNullsAnnotations` | Add @JsonSetter(nulls = ...) annotations to optional, non-nullable properties | | `optionalNonNullPropertyJsonSetterNulls` | @JsonSetter(nulls = ...) mode of optional, non-nullable properties: SKIP or FAIL | | `modelNameSuffix` | Suffix of model names | | `additionalModelTypeAnnotations` | Annotations added to model classes, separated by semicolons | | `additionalEnumTypeAnnotations` | Annotations added to enum classes, separated by semicolons | | `additionalOneOfTypeAnnotations` | Annotations added to oneOf interfaces, separated by semicolons | | `typeInfoDefaultImpls` | Classes used as defaultImpl of @JsonTypeInfo, by schema name (Schema=Class,...) | | `typeMappings` | Mappings of OpenAPI types to Java types (type=JavaType,...) | | `importMappings` | Mappings of Java types to imports (Type=package.Type,...) | | `schemaMappings` | Mappings of schemas to existing classes (Schema=package.Class,...) | | `modelNameMappings` | Mappings of schema names to model names (Schema=Model,...) | | `nameMappings` | Mappings of property names to Java names (name=javaName,...) | | `parameterNameMappings` | Mappings of parameter names to Java names (name=javaName,...) | | `enumNameMappings` | Mappings of enum values to constant names (value=NAME,...) | | `contentMediaTypeAsBinary` | Map strings with a non-JSON contentMediaType to binary types, like format: binary (on by default) | | `useImplicitOneOfDiscriminator` | Dispatch oneOf schemas without a discriminator on a property whose value is constant in every member | | `jsonAccessForReadWriteOnly` | Read readOnly properties from JSON only and write writeOnly ones only (@JsonProperty access) | | `library` | Client library: restclient (Spring RestClient, the default), resttemplate, feign (Spring Cloud OpenFeign) or http-interface (Spring HTTP interfaces) | | `allHttpMethods` | Generate operations of every HTTP method (QUERY, COPY, ...), not only the eight classic ones | | `generateStreamMethods` | Generate `Stream` methods for text/event-stream and application/jsonl responses | Unknown options are errors. ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Tier 1](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, with the goal of supporting every feature of the fixture. Its unsupported features are worked on first. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | ✓ 39 of 39 operations pass (java) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator client python Source: https://apigenie.pl/docs/reference/generator/client-python Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 1](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Python client of an OpenAPI document, built on [httpx](https://www.python-httpx.org) and [Pydantic](https://docs.pydantic.dev) 2. From an AsyncAPI document, the command generates an asyncio Kafka client package instead; see [`apigenie-generator client python` (AsyncAPI)](/docs/reference/generator/client-python-asyncapi). ## Usage ```sh apigenie-generator client python [...OPTIONS] INPUT_FILE ``` ## Description The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)). The generated package needs Python 3.10 or later, `pydantic>=2.11` and `httpx` (or `httpx2`, see `http_library`). ```python from pet_store_client import Client, NotFoundError, models with Client(api_key="...") as client: pets = client.pets.list_pets(limit=10) pet = client.pets.create_pet(models.PetInput(name="Rex")) try: client.pets.get_pet(42) except NotFoundError as error: print(error.body) ``` `AsyncClient` has the same methods, as coroutines: ```python async with AsyncClient(api_key="...") as client: pets = await client.pets.list_pets() ``` The clients have: - one resource per group of operations, e.g. `client.pets`, with one method per operation. Operations are grouped by their first tag (see `group_by`); the methods of operations without a group belong to the client. Method names come from operation IDs, or from the method and the path (see `action_naming`). - arguments for the server (`base_url`, or `server` and `server_variables`), one argument per security scheme (API keys, HTTP schemes, bearer tokens, OAuth 2.0 tokens or an `OAuth2ClientCredentials`, which requests and refreshes tokens), `auth` (any `httpx.Auth`), `timeout`, `max_retries`, `headers`, `http_client` and `follow_redirects`. Since 0.12.0, a `mutualTLS` scheme takes a client certificate: a PEM file holding the certificate and its key, or a pair of files. It applies only to the HTTP client the constructor creates; configure it on an `http_client` you pass. Each method takes the operation's required parameters as positional arguments, optional ones as keyword arguments (left out unless given; `UNSET` by default), the request body, and `request_options`, which override the timeout and retries and add headers and query parameters. Parameters are serialized with their style (form, spaceDelimited, pipeDelimited, deepObject, simple, label, matrix). Since 0.12.0, a parameter described with `content` is sent whole, as JSON when its media type is JSON. Bodies are JSON, form, multipart (with `File` objects or bytes), text or binary. Since 0.12.0: - strings with a `contentMediaType` other than text or JSON are files - a body with several media types takes a `content_type` argument choosing one; by default (`None`), JSON, else form, multipart, text, binary, JSON Lines or JSON text sequence, in that order - JSON Lines (`application/jsonl`, `application/x-ndjson` and the like) and JSON text sequence (`application/json-seq`) bodies are iterables of the items of their `itemSchema` Requests use the credentials of the first alternative of the operation's security requirements for which the client has credentials. Methods return the parsed body of a successful response, chosen by status code (`200`, `2XX`, `default`): a model, a list, text, bytes, or `None`. Error statuses raise an `ApiStatusError` subclass (`BadRequestError`, `AuthenticationError`, `NotFoundError`, `RateLimitError`, `InternalServerError`, ...) whose `body` is parsed with the documented schema. Connection errors, timeouts, and 408, 409, 429 and 5xx responses are retried with exponential backoff, honoring `Retry-After`; timeouts and server errors only for idempotent methods. `client.pets.with_raw_response` returns responses with their status and headers, `client.pets.with_streaming_response` returns them before reading their bodies (e.g. to download a file in chunks). Operations answering with server-sent events (`text/event-stream`) return a `Stream` of events. Since 0.12.0, so do operations answering with JSON Lines or JSON text sequences, with their items, when the response has no JSON media type; text or binary media types beside them are not read. Since 0.12.0, when the response also has JSON, the method returns the JSON and a `_stream` method beside it returns the `Stream`, which reads the items by the media type of the response. Models are Pydantic classes in the `models` module. Fields have Python names (`pet_id` for `petId`) and are serialized with the names of the API. Requests send the fields that were set: a field left out is omitted, one set to `None` is sent as `null`. Unknown properties of responses are kept in `model_extra`. Schemas become: - classes for objects, with `allOf` flattened into one class, and since 0.12.0 `if`/`then`/`else`, `dependentRequired`, `dependentSchemas`, `not` and draft-07 `dependencies` checked by a `model_validator` when they only test the presence and the values of properties (other conditions aren't checked) - `Enum` classes for string and integer enums of component schemas, `Literal` types otherwise - tagged unions for `oneOf` and `anyOf` with a discriminator, unions otherwise - `PetInput` variants for requests when a schema has `readOnly` or `writeOnly` properties - `datetime.date`, `datetime.datetime`, `uuid.UUID`, `Decimal` and `Base64Bytes` for formats, `Annotated` constraints for `minimum`, `maxLength` and the like, and `pattern` checked with Python's `re` by `matching()` of `_models.py` (a pattern `re` can't compile, such as one using `\p{L}`, isn't checked) The generated package contains `pyproject.toml`, `README.md` and the package: `client.py`, `models.py`, `resources/` (one module per group), `_metadata.py` (servers and security schemes), the runtime (`_base_client.py`, `_types.py`, `_auth.py`, `_exceptions.py`, `_serialization.py`, `_response.py`, `_sse.py`, `_models.py`), `_http.py` and `py.typed`. The code passes `mypy --strict`. Since 0.12.0, operations marked `x-internal: true` (on the operation or its path item) are left out, unless `internal_operations` is set. Not supported: callbacks and webhooks, XML bodies, and pagination. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | name of the model class of a component schema | | `x-enum-varnames`, `x-enumNames` | names of the members of an enum | | `x-apigenie.codegen.controller-name` | on an operation or its path item: the resource of the operation, when `group_by` lists `extension` | | `x-apigenie.codegen.action-name` | name of the method of an operation, when `action_naming` lists `extension` | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out | | `x-internal` | since 0.12.0, `true` on an operation or its path item leaves the operation out, unless `internal_operations` is set | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn't mapped | The extensions can live in an overlay for this target instead of in the document, e.g. `python.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Python names version: 1.0.0 actions: - target: $.components.schemas.Pet update: x-apigenie: codegen: name: Animal - target: $.components.schemas.PetStatus update: x-enum-varnames: [AVAILABLE, ON_HOLD, SOLD] ``` ```sh apigenie-generator client python openapi.yaml --overlay python.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.client_python.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the package is generated. ### --package-name Name of the distribution, e.g. `pet-store-client`; the package is named after it (`pet_store_client`). Defaults to the title of the API followed by `-client`. ### --package-version Version of the package. Defaults to the version of the API. ## Configuration ```yaml version: '1.0' commands: generate: client_python: layout: package http_library: httpx internal_operations: false group_by: tag action_naming: [id, url] raise_on_error: true enum_style: enum field_prefix: field_ class_overrides: pet-v2: Pet ``` | Option | Description | | ------ | ----------- | | `layout` | `package` (default): `pyproject.toml`, `README.md` and the package directory; `sources`: the modules only, directly in the output directory | | `http_library` | `httpx` (default) or `httpx2`, Pydantic's continuation of httpx with the same API | | `internal_operations` | Since 0.12.0. `true`: also generates the operations marked `x-internal: true`; `false` by default | | `group_by` | How operations are grouped into resources: `tag` (default), `url`, `extension` (`x-apigenie` `codegen/controller-name`), or an array of them, tried in order | | `action_naming` | Sources of method names: `id`, `extension` (`x-apigenie` `codegen/action-name`), `url`, or an array of them, tried in order; `[id, url]` by default | | `raise_on_error` | `true` (default): documented error responses raise errors; `false`: methods return their parsed bodies | | `enum_style` | `enum` (default): `Enum` classes for enums of component schemas; `literal`: `Literal` types everywhere | | `field_prefix` | Prefix of field names that would be invalid or clash with Pydantic, e.g. `json` becomes `field_json`; `field_` by default | | `class_overrides` | Class names of component schemas, by schema name | Unknown options are errors. ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Tier 1](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, with the goal of supporting every feature of the fixture. Its unsupported features are worked on first. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (python 3.12.11 httpx 0.28.1 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | ✓ 38 of 38 operations pass (python) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator client rust Source: https://apigenie.pl/docs/reference/generator/client-rust Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Experimental](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 not run yet · [Verification](#verification) Generate a Rust client crate on reqwest 0.12 and serde from an OpenAPI document: an async method per operation, returning an enum of the documented responses. > **(experimental, outside the 1.0 compatibility promise)** `client rust` is new in 0.12.0, and > the generated crate isn't yet checked against a live API (conformance Level 3): the options and > the output can still change. `client rust` says so in its `--help` and on the first line it > prints, on the standard error. See the > [experimental commands](/docs/reference/cli#experimental-commands). ## Usage ```sh apigenie-generator client rust [...OPTIONS] INPUT_FILE ``` ## Description The generator writes a library crate for Rust 1.85 (edition 2024). It shares `src/models.rs` and the types of its runtime with [`apigenie-generator server axum`](/docs/reference/generator/server-axum), so a client and a server generated from the same document read and write values the same way. | File | Contents | | ---- | -------- | | `Cargo.toml` | the package, its dependencies, and the feature `internal` when the document has operations marked `x-internal: true` | | `src/lib.rs` | the modules, with `Client`, `ClientBuilder` and `Error` re-exported | | `src/client.rs` | `DEFAULT_BASE_URL`, `Client::builder()`, a `ClientBuilder` method per security scheme, and per operation its parameters struct, its response enum and its method | | `src/models.rs` | the types of the component schemas the operations use, and of their inline schemas, with their `Validate` implementations | | `src/internal.rs` | the operations marked `x-internal: true`, behind the cargo feature `internal` | | `src/runtime/*.rs` | the client, its builder and credentials, `Error`, parameter encoding, streams, `FilePart`, `ProblemDetails`, `Nullable`, `DateTime`, `Date`, `Base64` and validation | `Cargo.toml` depends on reqwest 0.12 (without its default features, with `rustls-tls`), serde 1, serde_json 1, futures 0.3, bytes 1, thiserror 2, time 0.3 and regex 1, and on uuid 1, url 2 and rust_decimal 1 when the document uses their formats. reqwest runs on tokio: call the client from a tokio runtime. The examples on this page use the crate generated with `-o carpet-express` from the Carpet Express fixture ([OpenAPI 3.1 definition](/samples/carpet-express.openapi-31.yaml)). This application, which also depends on tokio (with `macros` and `rt-multi-thread`), reqwest and, for the streams, futures, gets a shipment and downloads its label: ```rust use std::time::Duration; use carpet_express::client::{ GetShipmentLabelParams, GetShipmentLabelResponse, GetShipmentParams, GetShipmentResponse, }; use carpet_express::models::{LabelFormat, Shipment}; use carpet_express::{Client, Error}; #[tokio::main] async fn main() -> Result<(), Error> { let client = Client::builder() // DEFAULT_BASE_URL; Client::with_base_url(url) for another one .api_key(std::env::var("CARPET_EXPRESS_API_KEY").unwrap_or_default()) .http_client(reqwest::Client::builder().timeout(Duration::from_secs(30)).build()?) .build()?; let id = "shp_8Yb2Kk1qP0wZcT3uXr5sN7aD"; match client.get_shipment(id, &GetShipmentParams::default()).await { Ok(GetShipmentResponse::Ok(Shipment::ParcelShipment(parcel))) => println!("{:?}", parcel.status), Ok(GetShipmentResponse::Ok(other)) => println!("{other:?}"), // a pallet or freight shipment Ok(GetShipmentResponse::NotModified) => {} Ok(GetShipmentResponse::NotFound(problem)) => println!("{:?}", problem.detail), // RFC 9457 Err(Error::UnexpectedStatus { status, .. }) => println!("status {status}"), Err(error) => return Err(error), // transport, encoding, decoding or credentials } let params = GetShipmentLabelParams { format: Some(LabelFormat::Pdf), ..Default::default() }; if let GetShipmentLabelResponse::OkPdf(pdf) = client.get_shipment_label(id, ¶ms).await? { std::fs::write("label.pdf", &pdf).expect("label.pdf written"); } Ok(()) } ``` ### Methods Every operation is an async method of `Client`, named after its `operationId` in snake case. It takes the path parameters, a reference to a struct with the query, header and cookie parameters when the operation has any, and the body, and returns the response enum of the operation: ```rust pub async fn get_shipment(&self, shipment_id: &str, params: &GetShipmentParams) -> Result pub async fn get_pickup(&self, pickup_id: &Uuid) -> Result pub async fn quote_rates(&self, body: &RateRequest) -> Result ``` - Path parameters are `&str` for strings, values for integers, numbers and booleans, and references for the other types (`&Uuid`, an enum). - The parameters struct, e.g. `GetShipmentParams`, has a field per parameter, an `Option` unless the parameter is required. It implements `Default` when none is required. - An operation with several request media types gets a method per media type, named with the media type: `update_shipment_merge_patch` and `update_shipment_json_patch`, `import_shipments_csv` and `import_shipments_jsonl`. The one for `application/json` keeps the bare name (`put_customs_declaration`, next to `put_customs_declaration_xml`). - JSON bodies are `&T`, checked with `Validate` before they are sent; an optional body is an `Option<&T>`. JSON Lines bodies (`application/jsonl`, `application/x-ndjson`, ...) are `&[T]` of the items of their `itemSchema`, each checked. `text/*` bodies are `&str`, other media types `impl Into`. - `application/x-www-form-urlencoded` bodies are structs, checked and encoded field by field with the styles of their `encoding` (`deepObject`, delimited arrays, JSON fields). - Parameters are written in their style and `explode` mode: `simple`, `label` and `matrix` path parameters, `form`, `spaceDelimited`, `pipeDelimited` and `deepObject` query parameters, headers and cookies. Parameters described with `content` are sent as JSON. The header parameters `Accept`, `Content-Type` and `Authorization` are ignored, as OpenAPI requires. - Methods set the `Accept` header to the media types of the documented responses. - The `query` operations and the `additionalOperations` of OpenAPI 3.2 are sent with their method, e.g. `QUERY` or `COPY`. - Deprecated operations get `#[deprecated(note = "the operation is deprecated")]`. - Operations marked `x-internal: true` (on the operation or its path item) are methods in `src/internal.rs`, compiled with the cargo feature `internal`; `internal_operations` includes them in `src/client.rs` or leaves them out. ### Responses A method returns an enum with a variant per documented status, holding the decoded body: ```rust pub enum GetShipmentLabelResponse { OkPdf(Bytes), // 200, application/pdf OkPng(Bytes), // 200, image/png OkZpl(Bytes), // 200, application/x-zpl OkJson(LabelEnvelope), // 200, application/json NotFound(ProblemDetails), // 404, application/problem+json // ... } pub enum CreateShipmentResponse { Created(Shipment), // 201 Accepted(Job), // 202 // ... Status5xx(u16, ProblemDetails), // 5XX, with the status code } ``` - Variants are named after the reason phrase of the status (`Ok`, `Created`, `NotModified`, `NotFound`), or `Status` for a status without one. A range is `Status5xx`, the `default` response `Default`; both hold the status code first. - A status with several media types gets a variant per media type (`OkJson`, `OkPdf`, `OkEventStream`, `OkJsonl`), chosen by the `Content-Type` of the response. A media type the document doesn't list is read as the last one. - A response without content is a variant without a value (`NotModified`). - JSON bodies are decoded and checked with `Validate`. `application/problem+json` bodies are `ProblemDetails` (`type`, `title`, `status`, `detail`, `instance`, and the other members in `extensions`), whatever their schema. `text/*` bodies are `String`, other media types `Bytes`. - Error statuses the document describes are variants, not errors. The `Error` of a method is one of: | Variant | When | | ------- | ---- | | `InvalidRequest(String)` | A parameter can't be written in its style, or the body doesn't meet the constraints of its schema. Nothing is sent. | | `MissingCredentials(&'static str)` | The client has no credentials for any alternative of the operation's security requirements, named by the `operationId`. Nothing is sent. | | `Transport(reqwest::Error)` | The request couldn't be sent or the response read. | | `UnexpectedStatus { status, body }` | The response has a status the operation doesn't describe, and it has no `default` response. | | `InvalidResponse(String)` | The body isn't JSON of its type, or doesn't meet the constraints of its schema. | ### Streams `text/event-stream` and JSON Lines contents (`application/jsonl`, `application/x-ndjson`, ...) are `EventStream` and `JsonLinesStream`, which implement `futures::Stream` and decode the items as they arrive. `T` comes from the `itemSchema` of the media type (OpenAPI 3.2; `x-itemSchema` in 3.0 and 3.1 documents). `getTrackingEvents` answers with JSON, server-sent events or JSON Lines: ```rust use futures::StreamExt; let params = GetTrackingEventsParams::default(); match client.get_tracking_events(id, ¶ms).await? { GetTrackingEventsResponse::OkEventStream(mut events) => { while let Some(event) = events.next().await { let event = event?; // Event: event, id, retry, and data decoded and checked println!("{:?} {:?}", event.event, event.data.status); } } GetTrackingEventsResponse::OkJsonl(mut events) => { while let Some(event) = events.next().await { println!("{:?}", event?.status); // TrackingEvent } } other => println!("{other:?}"), // the history as JSON, or 404 } ``` - For server-sent events, `T` is the `contentSchema` of the `data` property of the `itemSchema`, or the `itemSchema` itself without one. Each `Event` has the `event` (`None` for the default type), the `id` last received, the `retry` in milliseconds, and the `data` lines joined and decoded as JSON. Comments and events without data are skipped. - JSON Lines streams yield one `T` per line; blank lines are skipped. - Without `itemSchema`, the items are `serde_json::Value` values. - An item that isn't valid JSON of `T`, or doesn't meet its schema, is an `Err(Error::InvalidResponse)`; the stream goes on with the next one. ### Multipart bodies `multipart/form-data` bodies of object schemas are structs with a field per part, e.g. `UploadShipmentDocumentMultipartBody`: ```rust let body = UploadShipmentDocumentMultipartBody { file: FilePart::new(std::fs::read("invoice.pdf").expect("invoice.pdf read")) .with_file_name("invoice.pdf") .with_content_type("application/pdf"), kind: DocumentKind::CommercialInvoice, metadata: None, thumbnails: Vec::new(), }; let response = client.upload_shipment_document(id, &body).await?; ``` - Binary parts (`format: binary`, or `contentMediaType` in 3.1 and 3.2) are `FilePart` values, arrays of them `Vec`. A `FilePart` holds the bytes, a file name and a media type. Without a media type, the part is sent with the first `contentType` of its encoding, or its `contentMediaType`, or `application/octet-stream`. - Object and array parts, and parts whose encoding has a JSON `contentType`, are sent as JSON; other parts as text. Optional parts that are `None` are left out. The body is built in memory. ### Servers `DEFAULT_BASE_URL` is the URL of the first server of the document, with the default values of its variables (`http://localhost` without servers): `https://eu.api.carpetexpress.example/v2` for Carpet Express. `Client::builder()` sends requests there. `Client::with_base_url(url)` and `ClientBuilder::new(url)` send them to another URL. Operations with servers of their own (on the operation or its path item) are sent to the first of them; `.operation_servers(false)` sends every request to the base URL instead, e.g. to a test server or a proxy. ### Security Every security scheme of the document gets a `ClientBuilder` method setting its credentials, named after the scheme in snake case: | Scheme (name in the document) | Method | | ----------------------------- | ------ | | `apiKey` in a header, the query or a cookie (`apiKey`) | `api_key(key)` | | `http` `basic` (`basicAuth`) | `basic_auth(username, password)` | | `http` `bearer` (`bearerJwt`) | `bearer_jwt(token)`, sent as a bearer token | | `oauth2`, `openIdConnect` (`oauth2`) | `oauth2(token)`, sent as a bearer token, and `oauth2_tokens(provider)` | | `mutualTLS` (`mutualTLS`) | `mutual_tls(identity)`, a `reqwest::Identity` | A request gets the credentials of the first alternative of its operation's security requirements whose schemes all have credentials. An operation with `security: []`, or with an empty alternative (`{}`), gets none. Without such an alternative, the method returns `Error::MissingCredentials`. - `oauth2_tokens` takes a `TokenProvider`, an `Arc Result + Send + Sync>` called for every request: a token cache of the application. Obtaining and refreshing tokens is up to the caller. - `mutual_tls` sets the identity of the reqwest client the builder creates. With `http_client`, configure the identity on that client instead. - `credential(scheme, Credential)` sets the credentials of a scheme by its name, and `default_header(name, value)` a header sent with every request. Clones of `Client` share the connection pool and the credentials. Its `Debug` output doesn't show credentials. ### Types | Schema | Rust type | | ------ | --------- | | `string` | `String` | | `string`, `format: date-time` | `runtime::DateTime`, a `time::OffsetDateTime` | | `string`, `format: date` | `runtime::Date`, a `time::Date` | | `string`, `format: byte` or `contentEncoding: base64` | `runtime::Base64`, a `Vec` | | `string`, `format: binary` | `bytes::Bytes` in a response, `impl Into` as a request body, `runtime::FilePart` as a multipart part, `runtime::Base64` inside a JSON value | | `string`, `format: uuid` | `uuid::Uuid` | | `string`, `format: uri` or `url` | `url::Url` | | `string`, `format: decimal` | `rust_decimal::Decimal`, written as a JSON string and read from a string or a number | | `integer` | `i64`; `i32`, `i16`, `i8`, `u8`, `u16`, `u32`, `u64` for the formats `int32`, `int16`, `int8`, `uint8`, `uint16`, `uint32`, `uint64` and `uint` | | `number` | `f64`, `format: decimal` included (a JSON number); `f32` for `format: float` | | `boolean` | `bool` | | `array` | `Vec`; a tuple, e.g. `(f64, f64)`, for `prefixItems` without `items` | | `object` with properties | a struct | | `object` with only `additionalProperties` or `patternProperties` | `BTreeMap` | | a schema without a type | `serde_json::Value` | - Optional properties are `Option`, left out when `None`. Properties that can be null are `Nullable` (`Null` or `Value(T)`), optional ones `Option>`, which tells absent, null and set values apart. Required properties that are `readOnly` or `writeOnly` are `Option`, as they are absent from requests or responses. - Structs are `Debug`, `Clone`, `PartialEq`, `Serialize` and `Deserialize`, with the JSON names kept by `#[serde(rename)]`. `additionalProperties: false` adds `#[serde(deny_unknown_fields)]`; a schema of `additionalProperties` adds an `additional_properties` map. Types that contain themselves hold a `Box`. - String enums are Rust enums with a variant per value (`OutForDelivery` for `out_for_delivery`), `as_str()` and `Display`. With `unknown_enum_values: true`, an `Other(String)` variant takes the values the document doesn't list. Other enums are newtypes (`pub struct Dpi(pub i64)`) whose values are checked. - `oneOf` and `anyOf` schemas are enums with a variant per member. With a discriminator, the value goes to the variant its property selects: through the `mapping` or the name of the schema; other values go to the `defaultMapping` variant (`x-defaultMapping` in 3.0 and 3.1 documents), or fail to decode. Without a discriminator, a `oneOf` value goes to the only variant it decodes into and meets the constraints of, an `anyOf` value to the first one. - `allOf` schemas are merged into one struct; an `anyOf` or `oneOf` whose members only list required properties (`anyOf: [{required: [email]}, {required: [phone]}]`) is checked by `Validate`. ### Validation The types of `src/models.rs` implement `Validate`: `validate()` returns the `ValidationErrors` of the constraints of its schema, each with the JSON pointer of the value. The checks cover the lengths and patterns of strings, the bounds and `multipleOf` of numbers, items, unique items, properties, pattern properties, `enum`, `if`/`then`/`else`, `dependentRequired` and `dependentSchemas`, and the `email`, `idn-email`, `hostname`, `ipv4`, `ipv6`, `time`, `iri`, `uri-reference` and `iri-reference` formats. Values of the `date-time`, `date`, `uuid`, `uri`, `url` and `decimal` formats are checked as they are decoded into their types. The lengths and patterns of `decimal`, `uuid`, `uri` and `url` strings are checked on the text the crate writes for the value, e.g. the `pattern` of `Money.amount` on `"12.90"`. In a response, that is the text of the decoded value, not the text the server sent. The client checks request bodies before it sends them, and response bodies and stream items after it decodes them. ### Extensions | Extension | Effect | | --------- | ------ | | `x-rust-name` | name of the type of a schema | | `x-rust-type` | Rust type of a schema, a path such as `my_crate::Money`, or a name `type_mappings` maps | | `x-enum-varnames`, `x-enumNames` | names of the enum variants | | `x-enum-descriptions` | doc comments of the enum variants | | `x-apigenie.codegen.name` | name of the type of a component schema, when it has no `x-rust-name` | | `x-apigenie.codegen.action-name` | name of the method of an operation without an `operationId` (with the default `action_naming`, which lists `id` first) | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out | | `x-internal` | `true` on an operation or its path item puts the operation behind the cargo feature `internal` (see `internal_operations`) | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn't mapped | | `x-itemSchema` | `itemSchema` of a media type in OpenAPI 3.0 and 3.1 documents: the type of the items of a stream | The extensions can live in an overlay for this target instead of in the document, e.g. `rust.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Rust types version: 1.0.0 actions: - target: $.components.schemas.Rate update: x-rust-name: Quote - target: $.components.schemas.Money.properties.amount update: x-rust-type: my_crate::Amount ``` ```sh apigenie-generator client rust carpet-express.openapi-31.yaml --overlay rust.overlay.yaml -o carpet-express ``` ### Limitations The features of the conformance fixture the client doesn't support yet are listed under [Verification](#verification). Beyond them: - Callbacks, webhooks and links aren't generated. - Response headers aren't returned: a variant holds the body only. - The `Accept` header lists every documented media type of the operation; a method can't ask for one of them. - `allowReserved` is ignored: reserved characters in query values are percent-encoded. - Parameters and multipart bodies aren't checked against their schemas before they are sent. - `Validate` doesn't check `unevaluatedProperties`, nor patterns using lookaround or backreferences, which the regex crate doesn't support (a warning says so). It checks `if`/`then`/`else` and `dependentSchemas` only when their schemas use `required` and the `const` and `enum` of properties, and skips the others. - Values of an `x-rust-type` aren't checked, and the generated `Cargo.toml` doesn't list the crate of the type: add the dependency after generating. - Server URLs are used as written: a relative URL isn't resolved, so give an absolute base URL with `Client::with_base_url`, and `.operation_servers(false)` when the operations have relative servers. - Bodies are read in memory, except streams; there are no retries or rate limiting beyond what the reqwest client does. - Schemas named like the prelude, serde or the runtime (`Result`, `Option`, `String`, `Vec`, `Validate`, ...) get numbered types, e.g. `Result2`, with a message saying so. - The input must be an OpenAPI 3.0, 3.1 or 3.2 document or a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle documents referencing other files with `apigenie bundle`. An AsyncAPI document is refused with exit status 2. ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --no-config Doesn't look for `apigenie.yaml` (or `.apigenie.yaml`) in the current directory and its parents up to the root of the repository. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.client_rust.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### -o, --output Directory where the crate is generated. ### --package-name Name of the crate in `Cargo.toml`. Defaults to the name of the output directory in lower case, with `_`, `.` and spaces written as `-`, other characters dropped and at most 64 characters (`api` when that isn't a valid crate name). ### --package-version Version of the crate in `Cargo.toml`. Defaults to the `info.version` of the document. ### -p, --property NAME=VALUE Sets a generator option (see below), e.g. `-p internal_operations=exclude`. Options given on the command line take precedence over the configuration file. Lists are comma-separated (`-p include_tags=Shipments,Rates`) and mappings too (`-p type_mappings=money=my_crate::Money`). ### --json Prints the status of the run as one JSON document on the standard output, and nothing else there; see [JSON output](/docs/reference/cli#json-output). ## Exit status | Status | When | | ------ | ---- | | 0 | The crate was generated. | | 2 | The options, the configuration, an overlay or the input can't be used, the output directory can't be created, or the input is an AsyncAPI document. With `--strict`, also when an overlay action selects nothing. Nothing is generated. | See the [exit statuses of `apigenie-generator`](/docs/reference/generator#exit-status). ## Configuration ```yaml version: '1.0' commands: generate: client_rust: crate: carpet-express-client internal_operations: exclude type_mappings: money: my_crate::Money ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `crate` | string | name of the output directory | Name of the crate in `Cargo.toml`: a letter, then letters, digits, `-` and `_`, at most 64 characters; also set by `--package-name`. | | `version` | string | the document's `info.version` | Version of the crate in `Cargo.toml`, written as `MAJOR.MINOR.PATCH` from its leading numbers (`v2.4` gives `2.4.0`, a version without numbers `0.1.0`); also set by `--package-version`. | | `include_tags` | list of strings | | Generates only the operations with one of these tags. | | `exclude_tags` | list of strings | | Skips the operations with one of these tags. | | `skip_prune` | boolean | `false` | Keeps the component schemas that no generated operation uses. | | `internal_operations` | `feature`, `include` or `exclude` | `feature` | The operations marked `x-internal: true` (on the operation or its path): behind the cargo feature `internal`, generated like the others, or left out. | | `unknown_enum_values` | boolean | `false` | String enums get an `Other(String)` variant for the values the document doesn't list, so that new server values don't fail decoding. | | `type_mappings` | map of strings | | Rust types of string, integer and number formats or of `x-rust-type` names, by their paths, e.g. `money: my_crate::Money`. A component schema they apply to becomes an alias of the type. | | `action_naming` | list of `id`, `extension`, `url` | `id, extension, url` | Where method names come from, in order of preference: the `operationId`, the `x-apigenie` action name, or the method and path. | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, and Level 2 runs the language's type checker and linter; Level 3 isn't wired for this target. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Experimental](/docs/reference/generator/conformance#tiers). It isn't run at every level yet. It is outside the [1.0 compatibility promise](/docs/reference/cli/compatibility): its options and the shape of its output can change, or it can go away, in a minor release. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (rustc 1.99.1 (58cf8f9c3 2026-10-13)) | not run yet | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | not run yet | --- # apigenie-generator client swift Source: https://apigenie.pl/docs/reference/generator/client-swift Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Experimental](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Swift package calling the operations of an OpenAPI document, for iOS, macOS, tvOS, watchOS and Linux apps. > **(experimental, outside the 1.0 compatibility promise)** The generated code isn't yet built and > run against a live API by the conformance suite, so its types and methods can still change. > `client swift` says so in its `--help` and on the first line it prints, on the standard error. > See the [experimental commands](/docs/reference/cli#experimental-commands). ## Usage ```sh apigenie-generator client swift [...OPTIONS] INPUT_FILE ``` ## Description The generator writes a Swift package with one library target. Its code uses Foundation only: the package has no dependencies. | File | Contents | | ---- | -------- | | `Package.swift` | tools version 6.0, the platforms (iOS 16, macOS 13, tvOS 16, watchOS 9) and a library product of the module | | `.swift-format` | the swift-format settings the generated code follows (`swift format lint`) | | `Sources//Client.swift` | `Server`, `Credentials` and `Client`, with an async method per operation | | `Sources//Operations.swift` | per operation, the enum of its responses, the structs of their headers and the enums of bodies of several media types | | `Sources//Models.swift` | the types of the component schemas the operations use, and of their inline schemas | | `Sources//Runtime/*.swift` | the transport, requests and errors, JSON coding, parameter styles, streams, multipart bodies, validation, `Nullable`, `CalendarDate`, `Indirect`, `JSONValue` | The module is named after the document's title followed by `Client` (`Carpet Express Shipping API` gives `CarpetExpressShippingAPIClient`; `APIClient` when the title gives no name), unless `--package-name` or `package` names it. ```swift let client = Client(server: .production, credentials: .apiKey(apiKey)) switch try await client.getShipment(shipmentID: "shp_123") { case .ok(let body, let headers): print(body, headers.eTag) case .notFound(let problem): print(problem.title) case .notModified: break } ``` ### Methods Every operation is a method of `Client`, named after its `operationId`. Its arguments are the path parameters, the body (`body:`, `nil` by default when optional), the required query, header and cookie parameters, then the optional ones defaulting to `nil`, in document order. It returns the operation's response enum, with a case per documented status: ```swift public func createShipment( body: ShipmentCreate, idempotencyKey: UUID? = nil, prefer: CreateShipmentPrefer? = nil, xRequestID: String? = nil ) async throws -> CreateShipmentResponse public enum CreateShipmentResponse: Sendable { /// `201`: Shipment booked. case created(body: Shipment, headers: CreateShipmentCreatedHeaders) /// `400`: The request could not be parsed. case badRequest(Problem) // ... 202, 401, 403, 409, 422, 429 /// `5XX`: A carrier or Carpet Express itself is unavailable. case serverError(statusCode: Int, body: Problem, headers: CreateShipmentServerErrorHeaders) } ``` - A case holds the body of its status and, when the response declares headers, a struct of them; ranges (`5XX`) and `default` also hold the status code. A status with several media types holds an enum of them (`.pdf(Data)`, `.json(LabelEnvelope)`), chosen by the response's `Content-Type`. - A status the document doesn't list throws `ClientError.undocumentedStatus` with the status, the headers and the body; a body or header that can't be read throws `ClientError.invalidResponse`, and a request that can't be written (a null required path parameter, an invalid URL) throws `ClientError.invalidParameter`. - A request body of several media types is an enum with a case per media type (`UpdateShipmentRequestBody.mergePatchJSON(ShipmentPatch)`). - JSON bodies are checked against their schemas before they are sent while `client.validatesRequests` is `true` (the default, `validate_requests`): a body that breaks one throws `ClientError.invalidRequest` with the constraints it breaks. `validatesResponses` (`validate_responses`) checks response bodies the same way. - Parameters are written in their style and `explode` mode: `simple`, `label` and `matrix` path parameters, `form`, `spaceDelimited`, `pipeDelimited` and `deepObject` query parameters, `allowReserved`, headers and cookies. Parameters described with `content` are sent as JSON. - Methods set `Accept` to the media types of the documented responses. - Operations marked `x-internal: true` (on the operation or its path) are left out, unless `internal_operations` is set. Deprecated operations are marked `@available(*, deprecated)`. ### Streams `text/event-stream`, `application/jsonl` and `application/json-seq` responses are `AsyncThrowingStream`s of their items, typed by the media type's `itemSchema` (OpenAPI 3.2; `x-itemSchema` in 3.0 and 3.1 documents): ```swift if case .ok(.eventStream(let events)) = try await client.getTrackingEvents(shipmentID: id) { for try await event in events { print(event.id ?? "", event.data) } } ``` - Server-sent events are `ServerSentEvent` values whose `data` is decoded as the `contentSchema` of the `itemSchema`'s `data` property, or kept as a `String`. - On Apple platforms the items arrive as the server sends them (`URLSession.bytes(for:)`). On Linux, whose Foundation has no `bytes(for:)`, `URLSessionTransport` reads the whole body first. - JSON Lines and JSON text sequence request bodies are arrays of their items. ### Multipart bodies `multipart/form-data` bodies of object schemas are structs with a property per part. Binary parts (`format: binary`, or `contentMediaType` in 3.1 and 3.2) are `MultipartFile` values (data, file name and media type), arrays of them `[MultipartFile]`. Object parts, and parts whose encoding has a JSON `contentType`, are sent as JSON; other parts as text, a part per item of arrays. ### Servers `Server` has a static property per server of the document, named after its `name` or `description` (`.production`, `.sandbox`; `server1` when neither gives a name), with the default values of its variables. `Client` sends to the first one unless `server:` says otherwise; without servers in the document, `server:` is required. `Server(url:)` makes any other. Operations with servers of their own (on the operation or its path) are sent there unless `usesOperationServers` is `false`, e.g. for a test server or a proxy. ### Security `Credentials` has a property per security scheme of the document, and a function making credentials of that scheme alone: | Scheme | Property | Sent as | | ------ | -------- | ------- | | `apiKey` in a header, the query or a cookie | `String?` | the header, query parameter or cookie | | `http` `basic` | `BasicCredentials?` | `Authorization: Basic ...` | | `http` `bearer` | `String?` | `Authorization: Bearer ...` | | `oauth2`, `openIdConnect` | `TokenProvider?`, an async closure returning the access token | `Authorization: Bearer ...` | | `mutualTLS` | `Bool`, set when the transport presents the certificate | `URLSessionTransport(clientCertificate:)` (Apple platforms) | A request gets the credentials of the first alternative of its operation's security requirements whose schemes all have credentials; without one, the method throws `ClientError.missingCredentials`. An operation with `security: []` gets none. ### Transport `Client` sends requests through an `HTTPTransport` (one `async throws` method, `send(_:)`), `URLSessionTransport` by default. A transport of your own can add retries, logging or a test double. ## Stability Experimental, since 0.12.0. ## What you depend on - Swift 6.0 or later, in the Swift 6 language mode (strict concurrency). - Swift Package Manager (`swift build`), which reads `Package.swift` (tools version 6.0). - Foundation, and FoundationNetworking on Linux. No package dependencies. - iOS 16, macOS 13, tvOS 16 or watchOS 9 on Apple platforms. ## Features | Feature | Support | | ------- | ------- | | Authentication schemes | yes: API keys, HTTP basic and bearer, OAuth 2 and OpenID Connect tokens, mutual TLS | | Streaming | partial: server-sent events, JSON Lines and JSON text sequences arrive as sent on Apple platforms; on Linux the body is read whole first | | Pagination | no | | File upload | yes: multipart bodies and binary bodies | | Enums | yes, with `unknown(String)` for values the document doesn't list | | Discriminators | yes, with `mapping` and `defaultMapping` | | Nullable | yes: `Nullable?` tells missing, null and set values apart | | Errors | yes: a case per documented status, typed `ClientError`s | | Retries | no: an `HTTPTransport` of your own can retry | ## Type mapping | Schema | Swift | | ------ | ----- | | object | `public struct` that is `Codable`, `Hashable`, `Sendable` and `Validatable`, with a memberwise initializer | | optional property | `T?`, left out when encoding `nil` | | optional nullable property | `Nullable?`: `nil` when missing, `.null` when null | | required nullable property | `T?`, written as `null` | | string or integer enum | an enum with a case per value and `unknown(String)` (`unknown(Int)`), or without it with `unknown_enum_cases: false` | | `oneOf`, `anyOf` | an `indirect enum` with a case per variant; with a discriminator, the variant its property selects, else the first variant the value decodes as | | `allOf` | the properties merged into one struct | | `prefixItems` | a struct with a property per position (`item0`, `item1`), coded as an array | | `additionalProperties`, `patternProperties` | `[String: V]`, or `additionalProperties` of the struct | | `integer` | `Int`; `Int8` … `Int64`, `UInt` … `UInt64` by `format`; `Int64` for `double-int`, `unixtime` | | `number` | `Double`, `Float`, `Decimal` (`format: decimal`, `decimal128`) | | `date-time`, `date`, `uuid`, `uri` and `url` | `Date`, `CalendarDate`, `UUID`, `URL` | | `byte`, `binary` | `Data` | | any value | `JSONValue` | | recursive struct | the property held through `@Indirect` | Every struct, union and tuple has `validate()`, which checks lengths, patterns, numeric limits, item counts, unique items, `const`, `enum`, formats, `if`/`then`/`else`, `dependentRequired`, `dependentSchemas` and the `oneOf`/`anyOf` groups of required properties, and throws a `ValidationError` listing the constraints a value breaks with JSON pointers to them. ## Extensions | Extension | Effect | | --------- | ------ | | `x-swift-name` | name of the type of a schema, or of the property of a property | | `x-enum-varnames`, `x-enumNames` | names of the enum cases | | `x-enum-descriptions` | documentation of the enum cases | | `x-apigenie.codegen.name` | name of the type of a component schema, when it has no `x-swift-name` | | `x-apigenie.codegen.action-name` | name of the method of an operation without an `operationId` (with the default `action_naming`) | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out | | `x-internal` | `true` on an operation or its path item leaves the operation out, unless `internal_operations` is set | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents | | `x-itemSchema` | `itemSchema` of a media type in OpenAPI 3.0 and 3.1 documents | ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.client_swift.overlay` in the configuration file. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning. ### --no-config Doesn't look for `apigenie.yaml` (or `.apigenie.yaml`) in the current directory and its parents up to the root of the repository. ### --json Prints one JSON document on the standard output (`formatVersion`, `command`, `exitStatus`, `messages`) instead of the messages. ### -o, --output Directory where the package is generated. ### --package-name Name of the Swift module, its library product and the package. Defaults to the document's title followed by `Client`. ### --package-version Ignored: Swift packages take their versions from Git tags. ### -p, --property NAME=VALUE Sets a generator option (see below), e.g. `-p validate_responses=true`. Options given on the command line take precedence over the configuration file. Lists are comma-separated (`-p include_tags=shipments,rates`). ## Configuration ```yaml version: '1.0' commands: generate: client_swift: package: CarpetExpress validate_responses: true exclude_tags: [internal] ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `package` | string | the document's title followed by `Client` | Name of the module, its library product and the package; also set by `--package-name`. | | `include_tags` | list of strings | | Generates only the operations with one of these tags. | | `exclude_tags` | list of strings | | Skips the operations with one of these tags. | | `skip_prune` | boolean | `false` | Keeps the component schemas that no generated operation uses. | | `internal_operations` | boolean | `false` | Also generates the operations marked `x-internal: true`. | | `validate_requests` | boolean | `true` | The default of `Client.validatesRequests`: request bodies are checked before they are sent. | | `validate_responses` | boolean | `false` | The default of `Client.validatesResponses`: response bodies are checked. | | `unknown_enum_cases` | boolean | `true` | Enums get an `unknown` case for values the document doesn't list. | | `initialisms` | list of strings | | Words written in one case in identifiers, besides `ID`, `URL`, `HTTP`, `JSON` and the other common initialisms. | | `action_naming` | list of `id`, `extension`, `url` | `id, extension, url` | Where method names come from, in order of preference. | ## Exit status 0 when the package was generated; 2 when the options, the configuration, an overlay or the input document can't be used (with `--strict`, also when an overlay action selects nothing). See [`apigenie-generator`](/docs/reference/generator). ## Limitations - What the conformance fixture doesn't cover is listed under [Verification](#verification); callbacks, webhooks and links are out of scope there. - `validate()` skips patterns Swift's `Regex` can't compile and `unevaluatedProperties` other than `false`. It checks `if`/`then`/`else` and `dependentSchemas` only when their schemas use `required` and the `const` and `enum` of properties. - `format: decimal` numbers are decoded by `JSONDecoder`, which reads them through `Double` on Apple platforms before macOS 15 and iOS 18. - A `oneOf` without a discriminator decodes as its first variant that decodes, even when another one matches too. - Types of the standard library, Foundation, the runtime and the client (`Data`, `Error`, `ValidationError`, `Client`, `Credentials`, `Server`, ...) are reserved: schemas with these names get types with `Model` after their names, e.g. `ErrorModel`. - The input must be an OpenAPI 3.0, 3.1 or 3.2 document or a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle documents referencing other files with `apigenie bundle`. ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Experimental](/docs/reference/generator/conformance#tiers). It isn't run at every level yet. It is outside the [1.0 compatibility promise](/docs/reference/cli/compatibility): its options and the shape of its output can change, or it can go away, in a minor release. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (Swift version 6.0.3 (swift-6.0.3-RELEASE)) | ✓ 37 of 37 operations pass (swift) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator server aspnet Source: https://apigenie.pl/docs/reference/generator/server-aspnet Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 1](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate an ASP.NET Core server in C#, built on Minimal APIs. From an AsyncAPI document, the command generates an ASP.NET Core Kafka application instead; see [`apigenie-generator server aspnet` (AsyncAPI)](/docs/reference/generator/server-aspnet-asyncapi). ## Usage ```sh apigenie-generator server aspnet [...OPTIONS] INPUT_FILE ``` ## Description The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle documents referencing other files with [`apigenie bundle`](/docs/reference/cli/bundle). The generated project targets .NET 8 (or 9 and 10, see `target_framework`) and uses only the shared framework, without NuGet packages: ``` PetStore.csproj Program.cs the host, written only when missing README.md ApiRegistration.cs MapPetStoreApi(): maps the endpoints of all operations Apis/IPetsApi.cs one interface per group of operations Apis/PetsApi.cs its implementation, written only when missing Endpoints/PetsEndpoints.cs routes, parameter binding, validation and metadata Models/Pet.cs records and enums of the schemas Senders/*.cs typed HTTP clients sending the webhooks and callbacks Infrastructure/*.cs helpers used by the generated code ``` Operations are grouped by their first tag (or by the first segment of their paths). Each group gets an interface whose methods return the responses of the operation as a union of typed results, so the compiler accepts only declared responses: ```csharp public interface IPetsApi { /// Find a pet /// GET /pets/{petId} Task, NotFound, GoneResult>> GetPet(long petId, CancellationToken cancellationToken); } ``` Implementations return `TypedResults.Ok(pet)`, `TypedResults.NotFound()` and the like. Statuses without a `TypedResults` method (403, 410, 429, 500, ...) have result types of their own, created with `ApiResults.Gone(error)`. All results describe their responses in the endpoint metadata, so OpenAPI documents produced by ASP.NET Core match the input. Since 0.12.0, a response with several media types has a result for each kind, and the implementation picks one, e.g. by the `Accept` header of the request. Files (PDF, PNG, ...) are `FileStreamHttpResult`, text is `ContentHttpResult`. `text/event-stream` is `ServerSentEventsHttpResult`, and JSON Lines (`application/jsonl` and the like) is `JsonLinesHttpResult`. The streams are typed by the item schema: OpenAPI 3.2 `itemSchema`, or `x-itemSchema`, and for events the `contentSchema` of their `data`. Create them with `StreamingResults.ServerSentEvents(events)` from an `IAsyncEnumerable>`, and with `StreamingResults.JsonLines(items)` from an `IAsyncEnumerable`. Both write and flush each item as it comes. Pass `statusCode` when the response the document declares the stream for isn't 200, and `contentType` for another JSON Lines media type. The endpoints bind parameters from the path, the query, headers and cookies, in the styles of the document, e.g. exploded or delimited arrays. They read JSON, text, binary, form and multipart bodies, and resolve the implementation from the services of the request. Since 0.12.0, they also read: - objects in the query, as `deepObject`, exploded form, or comma-separated keys and values; - parameters described by JSON or text `content`; - form fields with the `deepObject` encoding; - file arrays whose items have `format: binary` or a `contentMediaType`. ```csharp var app = builder.Build(); app.MapPetStoreApi(); ``` Models are records with `required` properties, System.Text.Json attributes and DataAnnotations attributes for the constraints of the schemas (`minimum`, `maxLength`, `pattern`, `format: email`, `maxItems`, ...). An endpoint filter checks them, and the values of enums, before the implementation is called, and answers invalid requests with 400 validation problem details. - `oneOf` and `anyOf` with a discriminator become abstract records with `[JsonPolymorphic]` attributes, and their variants derive from them. On .NET 8, System.Text.Json reads the discriminator only as the first property of an object. - `allOf` referencing a schema with a discriminator becomes inheritance; other `allOf` schemas are merged into one record. - String enums become C# enums whose converters read and write the values of the document, e.g. `in-progress`. Integer enums keep their values. The `x-enum-varnames` extension names members. - Inline object and enum schemas get types named after their location, e.g. `PetOwner` for the `owner` property of `Pet`. Identical inline schemas share a type. - Schemas whose names would clash with types of .NET (`Task`, `File`, `Environment`, ...) get a `Model` suffix. - Since 0.12.0, tuples (`prefixItems`), `patternProperties`, `multipleOf`, and `if`/`then`/`else`, `dependentRequired` and `dependentSchemas` conditions are written as for [`apigenie-generator client csharp`](/docs/reference/generator/client-csharp). They become lists, dictionaries or records with `Entries`, `[MultipleOf]` attributes, and `IValidatableObject` implementations, which the endpoint filter checks. Operations with security requirements call `RequireAuthorization()`; configure the authentication schemes in `Program.cs`, which lists the schemes of the document. Since 0.12.0, when each alternative of the requirements lists OAuth 2.0 or OpenID Connect scopes, the endpoint answers 403 unless the user has every scope of one alternative. The scopes are read from the `scope`, `scp` or Microsoft Entra ID scope claims (`ScopeAuthorization`). Since 0.12.0, operations or paths with servers of their own are mapped below the path of their first server, with the defaults of its variables, instead of below the first server of the document. For example, `GET /health` of a server `https://status.example.com` is mapped at `/health`. `MapPetStoreApi()` maps them outside the group it returns, so conventions added to that group, e.g. `RequireCors()`, don't apply to them. With `base_path: none` they have no prefix either. Since 0.12.0, webhooks and callbacks get senders in `Senders/`. They are typed HTTP clients: - `WebhookSender` has a method per webhook. - Each callback of an operation has a class, e.g. `CreateShipmentStatusChangedCallback`, with a method per request. Register them with `builder.Services.AddHttpClient()` and one call per callback class; a new `Program.cs` has these calls. The methods take the URL, which the caller resolves: the subscriber's, or the value the callback's expression names, e.g. `callbackUrl` of the request body. Then they take the parameters and the body. They send JSON bodies with the JSON options of the application, and return the `HttpResponseMessage`. Not supported: - `oneOf` and `anyOf` without a discriminator whose members have different types (typed `object`; members of one type, e.g. strings of different formats, give that type), and `not` other than on the presence and constant values of properties; - separate request and response variants of models with `readOnly` and `writeOnly` properties (such properties are optional); - conditions on anything other than the presence and constant values of properties, and `unevaluatedProperties`; - in parameters, arrays of objects, objects in the label or matrix style, maps in the exploded form style, and `content` other than JSON or text (left out with a warning); - the constraints of form fields, and response headers; - request bodies of more than one kind, e.g. CSV or JSON Lines: the preferred one is accepted; - the host of an operation's own server: its routes answer on every host; - scopes, when an alternative of the requirements lists no OAuth 2.0 or OpenID Connect scopes (e.g. an API key), and the roles that OpenAPI 3.1 lists for other schemes: the endpoint only calls `RequireAuthorization()`; - in the senders of webhooks and callbacks, path, object and `content` parameters, the `Accept`, `Content-Type` and `Authorization` header parameters, and form bodies (left out with a warning). ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.controller-name` | on an operation or its path item: the group (API interface) of the operation, whatever `grouping` says | | `x-apigenie.codegen.action-name` | name of the method of an operation, when `action_naming` lists `extension` | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out, unless `skip_disabled` is `false` | | `x-internal` | `true` on an operation leaves it out | | `x-enum-varnames`, `x-enum-names` | names of the members of an enum, in PascalCase | | `x-enum-descriptions`, `x-enumDescriptions` | documentation comments of the members of an enum | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn't mapped | | `x-itemSchema` | `itemSchema` of a media type in OpenAPI 3.0 and 3.1 documents: the type of the items of a streamed response | The extensions can live in an overlay for this target instead of in the document, e.g. `aspnet.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: ASP.NET names version: 1.0.0 actions: - target: $.components.schemas.PetStatus update: x-enum-varnames: [Available, OnHold, Sold] - target: $.paths['/pets'] update: x-apigenie: codegen: controller-name: Animals ``` ```sh apigenie-generator server aspnet openapi.yaml --overlay aspnet.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_aspnet.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the project is generated. ### --package-name Root namespace of the generated code, e.g. `Acme.PetStore`; also the name of the project. Defaults to the title of the API. ### --package-version Version of the project. Defaults to the version of the API when it's a valid .NET version, or `1.0.0`. ### -p, --property NAME=VALUE Sets an option (see below), e.g. `-p layout=sources`; can be repeated. Options given on the command line take precedence over the configuration file. OpenAPI documents only: using it with an AsyncAPI document is an error. ## Configuration The options are read from `commands.generate.server_aspnet`. Its `asyncapi` section configures the generation from AsyncAPI documents (see [`apigenie-generator server aspnet` (AsyncAPI)](/docs/reference/generator/server-aspnet-asyncapi#configuration)). ```yaml version: '1.0' commands: generate: server_aspnet: namespace: Acme.PetStore target_framework: net10.0 grouping: url ``` | Option | Values | Description | | ------ | ------ | ----------- | | `layout` | `project`, `sources` | `project` (default): a complete project (.csproj, Program.cs, README.md); `sources`: only the generated sources, for an existing project | | `namespace` | namespace | Root namespace of the generated code (also `--package-name`); derived from the API title by default | | `target_framework` | `net8.0`, `net9.0`, `net10.0` | Target framework of the project (default: `net8.0`) | | `grouping` | `tag`, `url` | Grouping of operations into API interfaces: by their first tag (default), or by the first segment of their paths | | `action_naming` | `id`, `extension`, `url` | Sources of method names, in order of preference (default: `id`, `url`) | | `validation` | `filter`, `none` | `filter` (default): an endpoint filter validates parameters and bodies against their DataAnnotations; `none`: attributes only | | `authorization` | `require`, `none` | `require` (default): operations with security requirements call `RequireAuthorization()`; `none`: no authorization metadata | | `base_path` | `servers`, `none` | `servers` (default): routes are prefixed with the path of the first server URL, or of the first own server of the operation or its path; `none`: no prefix | | `program` | `true`, `false` | Generate Program.cs and stub implementations of the API interfaces (written only when missing; default: `true`) | | `skip_deprecated` | `true`, `false` | Don't generate deprecated operations (default: `false`) | | `skip_disabled` | `true`, `false` | Don't generate operations disabled with the `x-apigenie` extension (default: `true`) | | `model_suffix` | text | Suffix of model names, e.g. `Dto` | | `version` | version | Version of the project (also `--package-version`); defaults to the version of the API | Unknown options are errors. ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Tier 1](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, with the goal of supporting every feature of the fixture. Its unsupported features are worked on first. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | ✓ pass (.NET SDK 8.0.204) | ✓ 70 of 77 operations pass, 2 known failures (dotnet) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | runs before a release | runs before a release, 2 known failures | --- # apigenie-generator server axum Source: https://apigenie.pl/docs/reference/generator/server-axum Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Experimental](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 not run yet · 2 features of the fixture not supported yet · [Verification](#verification) Generate a Rust server crate on axum 0.8 from an OpenAPI document: a trait with an async method per operation, and a router that checks, decodes and validates requests before it calls them. > **(experimental, outside the 1.0 compatibility promise)** `server axum` is new in 0.12.0, and > the generated crate isn't yet checked against requests in contract tests (conformance Level 3): > the options and the output can still change. `server axum` says so in its `--help` and on the > first line it prints, on the standard error. See the > [experimental commands](/docs/reference/cli#experimental-commands). ## Usage ```sh apigenie-generator server axum [...OPTIONS] INPUT_FILE ``` ## Description The generator writes a library crate for Rust 1.85 (edition 2024). It shares `src/models.rs` and the types of its runtime with [`apigenie-generator client rust`](/docs/reference/generator/client-rust), so a client and a server generated from the same document read and write values the same way. | File | Contents | | ---- | -------- | | `Cargo.toml` | the package, its dependencies, and the feature `internal` when the document has operations marked `x-internal: true` | | `src/lib.rs` | the modules, with `Api`, `router`, `SecurityHandler`, `AcceptAnyCredentials`, `Credentials`, `Scheme`, `RequestContext` and `Problem` re-exported | | `src/server.rs` | the `Api` trait, a `SCHEME_*` constant per security scheme, and per operation its parameters struct, its body enum when it has several media types, its response enum and its handler; `router` | | `src/models.rs` | the types of the component schemas the operations use, and of their inline schemas, with their `Validate` implementations | | `src/internal.rs` | the response types and handlers of the operations marked `x-internal: true`, behind the cargo feature `internal` | | `src/runtime/*.rs` | the request context, reading parameters and bodies, security, problem details, writing responses and streams, `FilePart`, `Nullable`, `DateTime`, `Date`, `Base64` and validation | `Cargo.toml` depends on axum 0.8 (with `multipart`), serde 1, serde_json 1, futures 0.3, bytes 1, time 0.3 and regex 1, and on uuid 1, url 2 and rust_decimal 1 when the document uses their formats. Serve the router with `axum::serve` on a tokio runtime. The examples on this page use the crate generated with `-o carpet-express` from the Carpet Express fixture ([OpenAPI 3.1 definition](/samples/carpet-express.openapi-31.yaml)). Implement `Api`, which has one method per operation, and serve `router(api, security)`. This application also depends on axum, tokio (with `macros`, `net` and `rt-multi-thread`), rust_decimal for `Decimal`, and futures for the streams: ```rust use std::sync::Arc; use carpet_express::models::{Money, Rate, RateRequest, ShipmentId}; use carpet_express::runtime::ProblemDetails; use carpet_express::server::{GetShipmentParams, GetShipmentResponse, QuoteRatesResponse}; use carpet_express::{Api, Credentials, RequestContext, Scheme, SecurityHandler, router}; use rust_decimal::Decimal; struct Shipping; impl Api for Shipping { async fn quote_rates(&self, _ctx: RequestContext, body: RateRequest) -> QuoteRatesResponse { // the body is decoded and validated: two addresses, at least one parcel, weights above 0 // in the units of the request let weight: f64 = body.parcels.iter().map(|parcel| parcel.weight.value).sum(); QuoteRatesResponse::Ok(vec![Rate { service: "dhl.express_worldwide".into(), carrier: "dhl".into(), total: Money { amount: Decimal::new(1290, 2), currency: "EUR".into() }, // "12.90" transit_days: if weight > 30.0 { 3 } else { 1 }, service_name: None, breakdown: None, transit_time: None, guaranteed: None, valid_until: None, }]) } async fn get_shipment( &self, _ctx: RequestContext, shipment_id: ShipmentId, _params: GetShipmentParams, ) -> GetShipmentResponse { GetShipmentResponse::NotFound(ProblemDetails { r#type: Some("about:blank".into()), title: Some("Not Found".into()), status: Some(404), detail: Some(format!("no shipment {shipment_id}")), ..ProblemDetails::default() }) } // ... a method per operation } struct Keys; impl SecurityHandler for Keys { async fn check(&self, _ctx: &RequestContext, _scheme: &Scheme, credentials: &Credentials, _scopes: &[&str]) -> bool { matches!(credentials, Credentials::ApiKey(key) if key == "secret") } } #[tokio::main] async fn main() { let app = axum::Router::new().nest("/v2", router(Arc::new(Shipping), Arc::new(Keys))); let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await.unwrap(); axum::serve(listener, app).await.unwrap(); } ``` Once it runs, a valid request reaches `quote_rates`, and the `Decimal` amount is written as a JSON string: ```sh curl -s -H 'X-Api-Key: secret' -H 'Content-Type: application/json' -d '{"origin":{"line1":"Hauptstr. 1","postalCode":"10115","city":"Berlin","countryCode":"DE"},"destination":{"line1":"1 Rue de Rivoli","postalCode":"75001","city":"Paris","countryCode":"FR"},"parcels":[{"weight":{"value":1.2,"unit":"kg"}}]}' localhost:8080/v2/rates ``` ```json [{"service":"dhl.express_worldwide","carrier":"dhl","total":{"amount":"12.90","currency":"EUR"},"transitDays":1}] ``` ### The Api trait Every operation is a method of `Api`, named after its `operationId` in snake case. It takes a `RequestContext`, the path parameters, a struct with the query, header and cookie parameters when the operation has any, and the body, all owned, and returns the response enum of the operation: ```rust fn get_shipment(&self, ctx: RequestContext, shipment_id: ShipmentId, params: GetShipmentParams) -> impl Future + Send; fn quote_rates(&self, ctx: RequestContext, body: RateRequest) -> impl Future + Send; ``` The methods return `impl Future + Send`, so an implementation writes them as `async fn`, without `async-trait`. `Api` is `Send + Sync + 'static`; the router holds it in an `Arc`. - `RequestContext` has the `method`, `uri`, `headers` and `extensions` of the request (connection info, values of middleware), the decoded query pairs (`query()`) and the media type of the body (`media_type()`). - The parameters struct, e.g. `GetShipmentParams`, has a field per parameter, an `Option` unless the parameter is required. Parameters described with `content` are read as JSON. - A body with one media type is its type (`RateRequest`), an `Option` when the body is optional. A body with several media types is an enum with a variant per media type, e.g. `UpdateShipmentBody::MergePatch(ShipmentPatch)` and `UpdateShipmentBody::JsonPatch(JsonPatch)`. - JSON bodies are values of their types, JSON Lines bodies (`application/jsonl`, `application/x-ndjson`, ...) `Vec`s of the items of their `itemSchema`, `text/*` bodies `String`, `application/x-www-form-urlencoded` bodies structs read field by field with the styles of their `encoding`, other media types `Bytes`. - Deprecated operations say so in their doc comment. - Operations marked `x-internal: true` (on the operation or its path item) are methods and routes compiled with the cargo feature `internal`; `internal_operations` generates them like the others or leaves them out. ### Routing `router(api, security)` returns an `axum::Router` with a route per path of the document, in its order. Nest it to serve it below a path, e.g. the path of the server's URL (`/v2`). - Path parameters are read in their style (`simple`, `label`, `matrix`). A segment with several parameters or with text around one (`/labels/{labelId}.{extension}`) is split; a request whose segment doesn't match is answered with 404. - `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS` and `TRACE` are routed with axum's method filters, so axum answers a method the path doesn't have with 405 and `Allow`. A path with a `query` operation or `additionalOperations` (OpenAPI 3.2, e.g. `QUERY`, `COPY`) is served by one handler that dispatches on the method, and answers the methods it doesn't have with 405 and problem details. - Operations with servers of their own (on the operation or its path item) are routed at their path like the others. ### Requests A handler reads a request in this order, and answers the first failure with [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) problem details (`application/problem+json`), without calling the method: 1. The security requirements of the operation, through the `SecurityHandler` (401). 2. The path, query, header and cookie parameters, in their style and `explode` mode (`form`, `spaceDelimited`, `pipeDelimited` and `deepObject` query parameters), and their constraints (400; 404 for a path segment that doesn't match). 3. The media type of the body, against those of the document (415). 4. The body, decoded and checked with `Validate` (400; 413 for a body larger than `MAX_BODY_SIZE`, 16 MiB). For a body that doesn't meet its schema, the `errors` member lists the failed checks with their JSON pointers: ```sh curl -s -H 'X-Api-Key: secret' -H 'Content-Type: application/json' -d '{"origin":{"line1":"Hauptstr. 1","postalCode":"10115","city":"Berlin","countryCode":"DE"},"destination":{"line1":"","postalCode":"75001","city":"Paris","countryCode":"FR"},"parcels":[]}' localhost:8080/v2/rates ``` ```json {"type":"about:blank","title":"Bad Request","status":400,"detail":"Invalid body: /destination/line1: must be at least 1 characters long; /parcels: must have at least 1 items","errors":[{"detail":"must be at least 1 characters long","pointer":"/destination/line1"},{"detail":"must have at least 1 items","pointer":"/parcels"}]} ``` A parameter of the wrong type, a body of another media type and a request without credentials: ```sh curl -s -H 'X-Api-Key: secret' 'localhost:8080/v2/shipments?limit=abc' curl -s -H 'X-Api-Key: secret' -H 'Content-Type: text/csv' -d 'a,b' localhost:8080/v2/rates curl -s -H 'Content-Type: application/json' -d '{}' localhost:8080/v2/rates ``` ```json {"type":"about:blank","title":"Bad Request","status":400,"detail":"parameter 'limit': 'abc' isn't an integer"} {"type":"about:blank","title":"Unsupported Media Type","status":415,"detail":"the body must be application/json"} {"type":"about:blank","title":"Unauthorized","status":401,"detail":"the request has no valid credentials for the operation"} ``` ### Responses A method returns an enum with a variant per documented status, which implements `axum::response::IntoResponse` and writes the status, the `Content-Type` and the body: ```rust pub enum GetTrackingEventsResponse { OkJson(Vec), // 200, application/json OkEventStream(ItemStream>), // 200, text/event-stream OkJsonl(ItemStream), // 200, application/jsonl NotFound(ProblemDetails), // 404, application/problem+json } ``` - Variants are named after the reason phrase of the status (`Ok`, `Created`, `NotModified`, `NotFound`), or `Status` for a status without one. A range is `Status5xx`, the `default` response `Default`; both hold the status code first, written as 500 when it isn't a valid one. - A status with several media types gets a variant per media type (`OkJson`, `OkPdf`, `OkEventStream`, `OkJsonl`): the method picks one, e.g. from the `Accept` header in `ctx.headers`. - A response without content is a variant without a value (`NoContent`). - JSON bodies are written as JSON, `application/problem+json` bodies are `ProblemDetails` whatever their schema, `text/*` bodies `String`, other media types `Bytes`. ### Streams `text/event-stream` and JSON Lines responses (`application/jsonl`, `application/x-ndjson`, ...) hold an `ItemStream`, a `Pin + Send>>`. Each item is written as it arrives, until the stream ends. `getTrackingEvents` answers with JSON, server-sent events or JSON Lines; this implementation sends one event: ```rust use carpet_express::models::{ShipmentStatus, TrackingEvent}; use carpet_express::runtime::Event; use carpet_express::server::{GetTrackingEventsParams, GetTrackingEventsResponse}; use futures::StreamExt; impl Api for Shipping { async fn get_tracking_events( &self, _ctx: RequestContext, _shipment_id: ShipmentId, _params: GetTrackingEventsParams, ) -> GetTrackingEventsResponse { let event = TrackingEvent { id: "evt_1".into(), status: ShipmentStatus::InTransit, occurred_at: "2026-11-04T09:30:00Z".parse().expect("an RFC 3339 time"), description: Some("Departed the hub".into()), carrier_status_code: None, location: None, estimated_delivery: None, proof_of_delivery: None, }; let tracking = Event { event: Some("tracking".into()), id: Some(event.id.clone()), ..Event::new(event) }; let events = futures::stream::iter([tracking]); // or the stream of a channel GetTrackingEventsResponse::OkEventStream(events.boxed()) } // ... } ``` ```sh curl -s localhost:8080/v2/shipments/shp_8Yb2Kk1qP0wZcT3uXr5sN7aD/tracking-events ``` ```text event: tracking id: evt_1 data: {"id":"evt_1","status":"in_transit","description":"Departed the hub","occurredAt":"2026-11-04T09:30:00Z"} ``` - An `Event` has an `event`, an `id` and a `retry` (milliseconds), written when they are set, and the `data`, written as JSON. `T` is the `contentSchema` of the `data` property of the `itemSchema` (OpenAPI 3.2; `x-itemSchema` in 3.0 and 3.1 documents), or the `itemSchema` itself without one. - JSON Lines items are written as JSON, one per line. - Without `itemSchema`, the items are `serde_json::Value` values. ### Multipart bodies `multipart/form-data` bodies of object schemas are structs with a field per part, e.g. `UploadShipmentDocumentMultipartBody`. Binary parts (`format: binary`, or `contentMediaType` in 3.1 and 3.2) are `FilePart` values with the bytes, the file name and the media type of the part, arrays of them `Vec`. Object and array parts, and parts whose encoding has a JSON `contentType`, are read as JSON and checked; other parts as text. A missing required part is answered with 400. The parts are read in memory. ### Security The handler of an operation with security requirements finds the credentials of each scheme of an alternative in the request, and calls the `SecurityHandler` with them: ```rust pub trait SecurityHandler: Send + Sync + 'static { fn check(&self, ctx: &RequestContext, scheme: &Scheme, credentials: &Credentials, scopes: &[&str]) -> impl Future + Send; } ``` | Scheme | `Credentials` | | ------ | ------------- | | `apiKey` in a header, the query or a cookie | `ApiKey(String)` | | `http` `basic` | `Basic { username, password }`, decoded | | `http` `bearer`, `oauth2`, `openIdConnect` | `Bearer(String)`, from `Authorization: Bearer` | | `mutualTLS` | `MutualTls`: the application finds the client certificate in `ctx.extensions` | - A request is authorized when every scheme of one alternative has credentials and `check` returns `true` for them. Otherwise the handler answers 401; a scope check that fails is a 401 too. An operation with `security: []`, or an empty alternative, needs no credentials. - `scheme.name` is the name of the scheme in the document; `src/server.rs` has a constant per scheme, e.g. `SCHEME_API_KEY`. `scopes` are those of the requirement. - `AcceptAnyCredentials` accepts any credentials: for tests, and for applications that check them in a layer of their own. ### Types The types are those of [`client rust`](/docs/reference/generator/client-rust#types): structs with serde derives, `Option` for optional properties, `Nullable` for nullable ones, enums for string enums and for `oneOf` and `anyOf`, merged structs for `allOf`, and `runtime::DateTime`, `runtime::Date`, `uuid::Uuid`, `url::Url` and `rust_decimal::Decimal` for the formats. `unknown_enum_values` adds an `Other(String)` variant to string enums. - A `string` with `format: decimal` is a `rust_decimal::Decimal`, written as a JSON string and read from a string or a number. A `number` with `format: decimal` is an `f64`, a JSON number. - A `string` with `format: binary` is `bytes::Bytes` as a request or response body, `runtime::FilePart` as a multipart part, and `runtime::Base64` inside a JSON value. ### Validation The types of `src/models.rs` implement `Validate`, which checks the constraints of its schema as listed for [`client rust`](/docs/reference/generator/client-rust#validation). The lengths and patterns of `decimal`, `uuid`, `uri` and `url` values are checked on the text the crate writes for the decoded value, not on the text of the request: `"+12.90"` and the JSON number `12.9` both pass the `pattern` of `Money.amount`. The handlers check the parameters and the request bodies before they call the methods; responses aren't checked. ### Extensions | Extension | Effect | | --------- | ------ | | `x-rust-name` | name of the type of a schema | | `x-rust-type` | Rust type of a schema, a path such as `my_crate::Money`, or a name `type_mappings` maps | | `x-enum-varnames`, `x-enumNames` | names of the enum variants | | `x-enum-descriptions` | doc comments of the enum variants | | `x-apigenie.codegen.name` | name of the type of a component schema, when it has no `x-rust-name` | | `x-apigenie.codegen.action-name` | name of the method of an operation without an `operationId` (with the default `action_naming`, which lists `id` first) | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out | | `x-internal` | `true` on an operation or its path item puts the operation behind the cargo feature `internal` (see `internal_operations`) | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn't mapped | | `x-itemSchema` | `itemSchema` of a media type in OpenAPI 3.0 and 3.1 documents: the type of the items of a stream | The extensions can live in an overlay for this target instead of in the document, e.g. `rust.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Rust types version: 1.0.0 actions: - target: $.components.schemas.Rate update: x-rust-name: Quote - target: $.components.schemas.Money.properties.amount update: x-rust-type: my_crate::Amount ``` ```sh apigenie-generator server axum carpet-express.openapi-31.yaml --overlay rust.overlay.yaml -o carpet-express ``` ### Limitations The features of the conformance fixture the server doesn't support yet are listed under [Verification](#verification). Beyond them: - Links aren't generated. - A `decimal`, `uuid` or `url` value is validated after it is decoded: a JSON number is accepted for a `type: string, format: decimal` property, and the `pattern` and lengths apply to the text the crate writes (`12.90`, a lower-case UUID), not to the text received. - Response headers aren't written: a variant holds the body only. Add headers with a middleware layer. - A method returns one of the documented responses; there is no content negotiation, and responses aren't checked against their schemas. - Operations with servers of their own are served by the same router: the host and the path of their server aren't checked. - Request bodies and multipart parts are read in memory; only responses are streams. - `Validate` doesn't check `unevaluatedProperties`, nor patterns using lookaround or backreferences, which the regex crate doesn't support (a warning says so). It checks `if`/`then`/`else` and `dependentSchemas` only when their schemas use `required` and the `const` and `enum` of properties, and skips the others. - Values of an `x-rust-type` aren't checked, and the generated `Cargo.toml` doesn't list the crate of the type: add the dependency after generating. - Schemas named like the prelude, serde or the runtime (`Result`, `Option`, `String`, `Vec`, `Validate`, ...) get numbered types, e.g. `Result2`, with a message saying so. - The input must be an OpenAPI 3.0, 3.1 or 3.2 document or a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle documents referencing other files with `apigenie bundle`. An AsyncAPI document is refused with exit status 2. ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --no-config Doesn't look for `apigenie.yaml` (or `.apigenie.yaml`) in the current directory and its parents up to the root of the repository. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_axum.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### -o, --output Directory where the crate is generated. ### --package-name Name of the crate in `Cargo.toml`. Defaults to the name of the output directory in lower case, with `_`, `.` and spaces written as `-`, other characters dropped and at most 64 characters (`api` when that isn't a valid crate name). ### --package-version Version of the crate in `Cargo.toml`. Defaults to the `info.version` of the document. ### -p, --property NAME=VALUE Sets a generator option (see below), e.g. `-p internal_operations=exclude`. Options given on the command line take precedence over the configuration file. Lists are comma-separated (`-p include_tags=Shipments,Rates`) and mappings too (`-p type_mappings=money=my_crate::Money`). ### --json Prints the status of the run as one JSON document on the standard output, and nothing else there; see [JSON output](/docs/reference/cli#json-output). ## Exit status | Status | When | | ------ | ---- | | 0 | The crate was generated. | | 2 | The options, the configuration, an overlay or the input can't be used, the output directory can't be created, or the input is an AsyncAPI document. With `--strict`, also when an overlay action selects nothing. Nothing is generated. | See the [exit statuses of `apigenie-generator`](/docs/reference/generator#exit-status). ## Configuration ```yaml version: '1.0' commands: generate: server_axum: crate: carpet-express-server internal_operations: include unknown_enum_values: true ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `crate` | string | name of the output directory | Name of the crate in `Cargo.toml`: a letter, then letters, digits, `-` and `_`, at most 64 characters; also set by `--package-name`. | | `version` | string | the document's `info.version` | Version of the crate in `Cargo.toml`, written as `MAJOR.MINOR.PATCH` from its leading numbers (`v2.4` gives `2.4.0`, a version without numbers `0.1.0`); also set by `--package-version`. | | `include_tags` | list of strings | | Generates only the operations with one of these tags. | | `exclude_tags` | list of strings | | Skips the operations with one of these tags. | | `skip_prune` | boolean | `false` | Keeps the component schemas that no generated operation uses. | | `internal_operations` | `feature`, `include` or `exclude` | `feature` | The operations marked `x-internal: true` (on the operation or its path): behind the cargo feature `internal`, generated like the others, or left out. | | `unknown_enum_values` | boolean | `false` | String enums get an `Other(String)` variant for the values the document doesn't list. | | `type_mappings` | map of strings | | Rust types of string, integer and number formats or of `x-rust-type` names, by their paths, e.g. `money: my_crate::Money`. A component schema they apply to becomes an alias of the type. | | `action_naming` | list of `id`, `extension`, `url` | `id, extension, url` | Where method names come from, in order of preference: the `operationId`, the `x-apigenie` action name, or the method and path. | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, and Level 2 runs the language's type checker and linter; Level 3 isn't wired for this target. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Experimental](/docs/reference/generator/conformance#tiers). It isn't run at every level yet. It is outside the [1.0 compatibility promise](/docs/reference/cli/compatibility): its options and the shape of its output can change, or it can go away, in a minor release. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 2 not yet | ✓ pass (rustc 1.99.1 (58cf8f9c3 2026-10-13)) | not run yet | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 2 not yet | runs before a release | not run yet | Not supported yet, as the target's manifest says: - `operations.callbacks` (3.2, 3.1, 3.0): The server doesn't generate typed senders of callbacks yet; an application sends them with a client of its own. - `operations.webhooks` (3.2, 3.1, 3.0): The server doesn't generate typed senders of webhooks yet; an application sends them with a client of its own. --- # apigenie-generator server express Source: https://apigenie.pl/docs/reference/generator/server-express Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate an Express server stub in TypeScript from an OpenAPI document. ## Usage ```sh apigenie-generator server express [...OPTIONS] INPUT_FILE ``` ## Description The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle documents referencing other files with `apigenie bundle` first. The generated code runs on Node.js 20 or later with Express 5. The generator writes typed handler interfaces and a router serving them. Your code implements the handlers in files of its own, so regenerating the code never overwrites it: ```ts import express from "express"; import { BASE_PATH, createRouter, HttpError, type PetsHandlers } from "pet-store-server"; const pets: Partial = { async listPets(request) { const pets = await db.pets.list({ limit: request.query.limit }); return { status: 200, body: pets, headers: { "X-Total-Count": pets.length } }; }, async showPetById(request) { const pet = await db.pets.find(request.params.petId); if (pet === undefined) { throw new HttpError(404, "No such pet"); } return { status: 200, body: pet }; }, }; const app = express(); app.use( BASE_PATH, createRouter( { pets }, { handleNotFound: true, security: { api_key: ({ credential }) => users.byApiKey(credential) }, }, ), ); app.listen(8080); ``` Operations are grouped into handler interfaces by their first tag (`PetsHandlers`); operations without tags belong to the `default` group. A handler is named after the `operationId` of its operation, or after its method and path. It receives: - the request: the decoded and validated path, query, header and cookie parameters (`params`, `query`, `headers`, `cookies`, by name) and the body with its declared media type (`contentType`), all typed from the document - the context: the Express request and response (`req`, `res`), the description of the operation, the principal returned by the security handlers, and `signal`, aborted when the connection closes before the response is complete It returns the response: a status, a body, headers and optionally a content type, typed per status from the document. A handler which answers on its own through `context.res` returns nothing. Since 0.12.0, a response in `text/event-stream` or JSON Lines (`application/jsonl`, `application/x-ndjson`, `application/x-jsonlines`) can also be answered with an `AsyncIterable` of its items, such as an async generator. The response type has a member per streamed media type whose `contentType` is that media type, required when the response has several media types. The items are typed by `itemSchema` (`x-itemSchema` in OpenAPI 3.0 and 3.1 documents) in `src/types.ts`. An inline schema gets a type named after the operation, such as `GetTrackingEventsEventStreamItem` or `GetTrackingEventsJsonlItem`. A schema in a shared response gets a type named after the response component, such as `LogStreamEventStreamItem`. Without an `itemSchema`, an event is a `ServerSentEvent` (`{ data?: unknown; event?: string; id?: string; retry?: number }`) and a JSON line `unknown`. The router sets `Cache-Control: no-cache` unless the handler set it, waits for the first item, sends the headers, and writes each item as it comes. A JSON Lines item becomes one line of JSON. An event item becomes its `id`, `event` and `retry` fields, then a `data:` line per line of its `data`: the string itself, or its JSON for another value. An item that isn't an object is its `data`. An item without `data` writes its fields but no `data:` line, so no event is dispatched; an `EventSource` still applies its `id` and `retry`. - An error before the first item is answered with a problem, with the headers already set. A later error aborts the connection, so the client sees a truncated stream, not a complete one. - An item that `JSON.stringify` throws on, such as one holding a `bigint` or a cycle, also aborts the connection. The router then calls the iterator's `return()`. - When the client disconnects, the router stops at the next item and calls the iterator's `return()`, so an async generator's `finally` blocks run. `context.signal` is aborted at once, for a handler that waits long for its next item. - A `HEAD` request gets the status and headers only: the router reads no item and calls the iterator's `return()`, so an async generator's body doesn't run at all. - An `AsyncIterable` in a media type that isn't streamed is a 500. `validateResponses` doesn't check streamed items. ```ts const tracking: Partial = { async getTrackingEvents(request) { async function* events() { for await (const update of carrier.updates(request.params.shipmentId)) { yield { event: "tracking" as const, id: update.id, data: JSON.stringify(update) }; } } return { status: 200, contentType: "text/event-stream", body: events() }; }, }; ``` The client receives: ```text id: evt_1 event: tracking data: {"id":"evt_1","status":"in_transit","occurredAt":"2026-11-03T09:00:00Z"} ``` For every request, the router: 1. checks the security requirements of the operation: any of them, with all the schemes of a requirement, must be satisfied. A security handler receives the credential (the API key, the bearer token or the decoded `user:password` of basic authentication) and the required scopes, and returns the principal, or `undefined` to reject the request with 401 Unauthorized. It may throw an `HttpError`, e.g. 403 Forbidden for missing scopes. Schemes without handlers reject every request. 2. decodes the parameters in all OpenAPI styles (`simple`, `label`, `matrix`, `form`, `spaceDelimited`, `pipeDelimited` and `deepObject`, exploded or not) and converts them to the types of their schemas; parameters with `content` are parsed as JSON. Absent parameters get their default values. 3. reads the body: JSON, `application/x-www-form-urlencoded` (converted to the types of its schema), `multipart/form-data` (see below), text and binary bodies are parsed. A body that middleware already parsed is used as it is (`req.body`), except a `multipart/form-data` one whose schema has properties. A media type that isn't declared is answered with 415 Unsupported Media Type, a missing required body with 400. 4. validates the parameters and the body against their schemas (see `validation`) and answers invalid requests with 400 Bad Request. 5. calls the handler, or answers with 501 Not Implemented when there's none. 6. writes the response, optionally validating it first (`validateResponses`). Since 0.12.0, a `multipart/form-data` body whose schema has properties is decoded into an object with a property per part. Its type, `RequestBody` in `src/types.ts`, has a `globalThis.File` per file. The first rule that applies decides how a part is decoded: 1. When the encoding of the property names a `contentType`, its first media type decides: a JSON type is parsed as JSON, a `text/*` type is text and any other type is a `File`. 2. A binary string is a `File`: `format: binary`, a `contentEncoding`, or in OpenAPI 3.1 and 3.2 documents a `contentMediaType`. 3. A schema whose `type` includes `object` or `array` is parsed as JSON, and so is a schema without `type` that has `properties`, `patternProperties`, `additionalProperties`, `items`, `prefixItems`, `allOf`, `anyOf` or `oneOf`. 4. Any other schema without `type`, `{}` included, is a `File`. 5. Any other value is text, converted to the types of its schema like a query parameter. A `File` has the file name, media type and content of the part. A file part without a file name or without a `Content-Type` becomes a `File` of `text/plain`. A property of `type: array` with `items` collects its repeated parts, and its `items` decide how each is decoded. Any other property may appear once, and a part that no property names is kept as it is: a string, or a `File` when it has a file name. A request is answered with 400 Bad Request when one of its parts fails these checks: | `keyword` | When | | --- | --- | | `contentMediaType` | A file whose media type isn't in the `contentType` of its encoding (`image/*` ranges included), or a JSON part that isn't valid JSON | | `multipart` | A part appears more than once, and its property isn't of `type: array` with `items` | A body that can't be read as multipart is answered with 400 and the detail "The multipart body can't be read". The decoded object is then validated against the schema. A file stands for an empty string there, so a `type` without `string`, a `minLength` above 0, or a `pattern`, `enum` or `const` that doesn't accept `""` rejects every file. The headers of the parts aren't available, so the `headers` of an encoding aren't checked. The router reads the multipart body itself, up to `bodyLimit` (`"100kb"` by default). Middleware that reads the raw body, such as `express.raw({ type: "multipart/*" })`, is fine. Middleware that parses it, such as multer, is answered with 500 Internal Server Error, so leave it out for these routes. Without a schema with properties, the body is left to middleware and typed `unknown`. Errors are answered with [problem details](https://www.rfc-editor.org/rfc/rfc9457) (`application/problem+json`). Validation errors list the failed checks: ```json { "type": "about:blank", "title": "Bad Request", "status": 400, "detail": "The request is invalid", "errors": [ { "in": "query", "name": "limit", "path": "", "keyword": "maximum", "message": "must be <= 50" }, { "in": "body", "path": "/name", "keyword": "required", "message": "must have required property 'name'" } ] } ``` Routes are registered so that literal path segments win over parameters (`/pets/mine` before `/pets/{petId}`). Deprecated operations are marked `@deprecated`, and operations disabled with the `x-apigenie` extension (`codegen.disabled`) are left out. An operation can have servers of its own, given on the operation or else on its path item. The path of its first server, with the default values of its variables, can differ from `BASE_PATH`. `createRouter` still serves such an operation under `BASE_PATH`. Since 0.12.0, `createRootRouter(handlers, options)` serves each operation under the path of its first server instead, and the operations without servers under `BASE_PATH`, ordering the routes by these full paths. Mount it at the root: ```ts app.use(createRootRouter({ pets }, { handleNotFound: true })); ``` With `handleNotFound`, the root router answers 404 for every request that no earlier route or middleware answered: register other routes and middleware first. The root router answers `serveDocument` under `BASE_PATH`. It checks the path only: a server's host isn't checked, so an application that serves several hosts checks `req.hostname` itself. A server path with a variable the server doesn't declare can't be routed, and its operation stays under `BASE_PATH`. Since 0.12.0, an operation in `OPERATIONS` with servers of its own, or of its path item, has `servers`: their URLs, with the default values of their variables. ### Generated files The generated package contains: - `src/types.ts`: the types of the component schemas, mapped as in the [fetch client](/docs/reference/generator/client-fetch#types), and the request and response types of every operation - `src/handlers.ts`: the handler interfaces, `Handlers`, `SecurityHandlers`, `createRouter(handlers, options)` and `createRootRouter(handlers, options)` - `src/metadata.ts`: the operations (`OPERATIONS`), webhooks and callbacks (`OUTGOING_OPERATIONS`) and security schemes described for the runtime, and the port (`DEFAULT_PORT`) and path (`BASE_PATH`) of the first server - `src/senders.ts`: `createWebhooks()` when the document has webhooks, and `createCallbacks()` when its operations have callbacks, with `src/outgoing.ts`, the code sending their requests, which the [oRPC server](/docs/reference/generator/server-orpc) shares - `src/validation.ts` and, depending on `validation`, `src/schemas.ts` and `src/ajv_engine.ts`, or `src/validators.ts` - `src/runtime.ts`: the request handling code, which doesn't depend on the document - `src/document.ts`: the OpenAPI document, with `copy_document` - `src/index.ts`, `package.json`, `tsconfig.json` and `README.md` - `src/server.ts`: an example server with stub handlers, with `scaffold`. It mounts `createRootRouter` when the operations have paths other than `BASE_PATH`, and `createRouter` otherwise `README.md` and `server.ts` are written only if they don't exist; the other files are overwritten. ### Webhooks and callbacks Since 0.12.0, the requests your application sends are generated too. They are the webhooks of the document (`x-webhooks` in OpenAPI 3.0 documents) and the callbacks of its operations. `src/senders.ts` then has `createWebhooks(options)`, `createCallbacks(options)` or both, whose senders send each request with `fetch`: ```ts import { createCallbacks, createWebhooks, type ShipmentsHandlers } from "carpet-express-server"; const webhooks = createWebhooks({ headers: { "User-Agent": "carpet-express" } }); await webhooks.onShipmentStatusChanged(subscription.url, { headers: { "CarpetExpress-Signature": sign(event) }, body: event, }); const callbacks = createCallbacks(); const shipments: Partial = { async createShipment(request) { const shipment = await db.shipments.create(request.body); queue.onStatusChange(shipment, async (event) => { const response = await callbacks.createShipment.statusChanged( { request }, { headers: { "CarpetExpress-Signature": sign(event) }, body: event }, ); if (response.status === 410) { queue.stop(shipment); } }); return { status: 201, body: shipment, headers: { ETag: etag(shipment) } }; }, }; ``` A webhook sender is named like a handler, from the sources `action_naming` lists, or else after its method and name, and takes the subscriber's URL. A callback sender is grouped under the handler name of its operation. It is named after the callback, followed by the method when the callback has several requests. It takes a `source`: the decoded request of the operation, and optionally its response and the Express request (`req`). The runtime expressions in the callback's URL, such as `{$request.body#/callbackUrl}`, are resolved against it: | Expression | Value | | --- | --- | | `$request.body`, `$request.body#/pointer` | The body of `source.request`, or the value at the JSON Pointer | | `$request.query.name`, `$request.path.name` | A parameter of `source.request` | | `$request.header.name` | A header of `source.request`, or else of `source.req` | | `$response.body`, `$response.body#/pointer` | The body of `source.response`, or the value at the JSON Pointer | | `$response.header.name` | A header of `source.response` | | `$statusCode` | The status of `source.response` | | `$url`, `$method` | The URL and method of `source.req` | A value at the start of the URL is used as it is, as the base URL. Later values are percent-encoded, so the scheme and the host come from the literal start of the URL or from the value at its start. In `{$request.body#/url}/verify/{$response.body#/id}`, a slash in the id is sent as `%2F`. When an expression has no value, or its value is an object or an array, the promise rejects with an `Error` and nothing is sent. A URL that isn't valid rejects with a `TypeError`. A sender's request is typed like a handler's, as `Request` in `src/types.ts`, with no `params`. `` is the name of a webhook sender. For a callback, it is the name of the callback component it refers to, when no other callback refers to that component (`ShipmentStatusCallbackRequest`). Otherwise it is the handler name and the callback name (`CreateWebhookSubscriptionVerificationRequest`). The method follows when the callback has several requests. `query`, `headers`, `cookies` and the body are optional unless they hold something required. The body is sent in the first declared media type, or in the one `contentType` names; a `contentType` the operation doesn't declare rejects with an `InvalidRequestError`. It can be JSON, form fields or text, a `FormData` for `multipart/form-data`, or a `Uint8Array` or `Blob`. The sender first checks the query, header and cookie parameters and a JSON, form or text body against their schemas, with the `validation` of the package. A `multipart/form-data` or binary body is only checked for presence. When a check fails, the promise rejects with an `InvalidRequestError` and nothing is sent; its `issues` list the failed checks. A sender resolves with a response that its operation declares, typed as `Response`. Its `headers` are strings by lowercase name. Its body is decoded as the declared media type its Content-Type matches, which `contentType` then holds: | Declared media type | `body` | Empty body | Checked | | --- | --- | --- | --- | | JSON, such as `application/json` or `*+json` | The parsed JSON | Rejects | Valid JSON, and the schema | | `application/x-www-form-urlencoded` | The fields, as a string or an array of strings by name | Rejects | Presence | | `text/*`, including the `text/*` range | The text | `""` | The schema | | Any other, including `multipart/*` and `*/*` | A `Uint8Array` | Rejects | Presence | | None (declared without content) | `undefined`, whatever is received | `undefined` | Nothing; `contentType` is the Content-Type as received | A response whose status or media type isn't declared, or that the table says rejects, makes the promise reject with an `UnexpectedResponseError`. The error's `response` holds the response, and its `issues` say what didn't match. An operation without declared responses accepts any response, decoded by its Content-Type, which `contentType` then holds. A network error rejects with the error of `fetch`. | Option | Description | | --- | --- | | `fetch` | The `fetch` function that sends the requests (default: `globalThis.fetch`) | | `validation` | Validation of the requests and responses (default: the engine of the `validation` setting) | | `headers` | Headers of every request | | `onRequest` | Called with each `Request` and the `OperationInfo` of its webhook or callback before it's sent; returns it or another `Request`, e.g. to sign it | Declared header parameters replace the `headers` option of the same name. The last argument of a sender takes the `headers` and the `signal` of that request only. Its headers replace those of the same name and aren't validated. `OUTGOING_OPERATIONS` in `src/metadata.ts` describes the webhooks and callbacks. The path of a webhook is its name, and that of a callback is its URL expression. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | name of the type of a component schema | | `x-apigenie.codegen.controller-name` | on an operation or its path item: the handler interface of the operation, when `grouping` lists `extension` | | `x-apigenie.codegen.action-name` | name of the handler of an operation, or of the sender of a webhook, when `action_naming` lists `extension` | | `x-apigenie.codegen.disabled` | `true` on an operation, on the operation of a webhook or of a callback URL expression, or on its path item, leaves it out (for a webhook or a callback, its sender), unless `skip_disabled` is `false` | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn't mapped | | `x-itemSchema` | `itemSchema` of a media type in OpenAPI 3.0 and 3.1 documents: the type of the items of a streamed response | | `x-webhooks` | `webhooks` of an OpenAPI 3.0 document: the requests the senders of `src/senders.ts` send | The extensions can live in an overlay for this target instead of in the document, e.g. `express.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: TypeScript names version: 1.0.0 actions: - target: $.components.schemas.Pet update: x-apigenie: codegen: name: Animal - target: $.paths['/admin'] update: x-apigenie: codegen: disabled: true ``` ```sh apigenie-generator server express openapi.yaml --overlay express.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_express.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the package is generated. ### --package-name Name of the generated package. Defaults to the title of the API followed by `-server`. ### --package-version Version of the generated package. Defaults to the version of the API. ## Configuration ```yaml version: '1.0' commands: generate: server_express: validation: ajv validate_responses: true scaffold: true ``` | Option | Description | | ------ | ----------- | | `layout` | `package` (default): an npm package with sources in `src/`; `sources`: the sources only | | `import_extension` | Extension of relative imports: `.js` (default, Node.js) or an empty string (bundlers) | | `validation` | `ajv` (default): JSON Schemas validated with [Ajv](https://ajv.js.org); `generated`: generated TypeScript validators, without dependencies; `none` | | `validate_responses` | Generate what's needed to validate responses, enabled by the `validateResponses` router option (default: false) | | `grouping` | How operations are grouped into handler interfaces: `tag` (default), `extension` (`x-apigenie` `codegen.controller-name`) or `url`, or a list of them, in order of preference | | `action_naming` | Sources of handler and webhook sender names: `id`, `extension` (`x-apigenie` `codegen.action-name`) or `url`, or a list of them (default: `[id, url]`) | | `skip_deprecated` | Leave deprecated operations, webhooks and callbacks out (default: false) | | `skip_disabled` | Leave out operations, webhooks and callbacks disabled with `x-apigenie` (default: true) | | `copy_document` | Include the document in the package, so that the router can serve it (default: false) | | `scaffold` | Write an example server, `src/server.ts`, unless it exists (default: false) | | `security` | Check the security requirements of operations (default: true) | Both validation modes report the same issues with the same messages, and both convert OAS 3.0 schemas (`nullable`, boolean `exclusiveMinimum` and `exclusiveMaximum`) and leave `readOnly` properties out of the required properties of requests and `writeOnly` ones out of responses. Since 0.12.0, they check `if`/`then`/`else`, `dependentRequired`, `dependentSchemas` and draft-07 `dependencies`. The generated validators don't check `unevaluatedProperties`, `unevaluatedItems`, `contains`, `propertyNames`, `contentSchema` and `$dynamicRef`; the generator warns about them. Formats are checked as JSON Schema defines them, the generated validators knowing the common ones (`date-time`, `date`, `time`, `duration`, `email`, `hostname`, `ipv4`, `ipv6`, `uri`, `uri-reference`, `uuid`, `byte`, `int32` and `int64`). ## Router options | Option | Description | | ------ | ----------- | | `security` | Security handlers, by scheme name | | `validation` | A validation engine replacing the generated one, e.g. `noValidation` | | `validateResponses` | Validate the bodies returned by handlers, except streams; invalid ones are answered with 500 | | `handleNotFound` | Answer requests to unknown paths with 404 and unknown methods with 405 | | `notImplemented` | `"501"` (default) or `"next"`: pass requests to operations without handlers to the next middleware | | `exposeErrors` | Put the messages of unexpected errors into 500 responses | | `onError` | Called with unexpected errors, which are logged with `console.error` otherwise | | `bodyLimit` | Maximum size of request bodies, multipart ones included, e.g. `"1mb"` (default: `"100kb"`) | | `serveDocument` | Serve the document as JSON at this path, e.g. `"/openapi.json"` (needs `copy_document`) | | `caseSensitive`, `strict` | Options of the Express router | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet, 1 not checked | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, Express 5) | ✓ 72 of 77 operations pass (node) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet, 1 not checked | runs before a release | runs before a release | --- # apigenie-generator server fastapi Source: https://apigenie.pl/docs/reference/generator/server-fastapi Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 1](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Python [FastAPI](https://fastapi.tiangolo.com) server from an OpenAPI document. ## Usage ```sh apigenie-generator server fastapi [...OPTIONS] INPUT_FILE ``` ## Description The generated project has the layout of the `python-fastapi` generator of [openapi-generator](https://openapi-generator.tech) and accepts its options, so a project generated by openapi-generator can be generated again by API Genie. The input is an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle a document that references other files with `apigenie bundle` first. The code itself is written for FastAPI 0.115+, pydantic 2.7+ and Python 3.10+: ``` pyproject.toml, requirements.txt, README.md, Dockerfile, docker-compose.yaml, openapi.yaml src/openapi_server/ main.py the application: includes the routers, loads the implementation apis/pets_api.py the routes of the "pets" API (one module per tag) apis/pets_api_base.py BasePetsApi: the methods to implement impl/__init__.py the implementation package, yours models/ pydantic models, one module per schema parameters.py since 0.12.0, the decoding of delimited, deepObject and content parameters, when there are any security_api.py the dependencies checking credentials streaming.py since 0.12.0, the reading and writing of streamed bodies, when there are any webhooks.py since 0.12.0, the webhooks of the API, when it has some tests/ pytest tests with FastAPI's TestClient ``` Routes validate requests, then call the methods of the base class of their API, which answer 501 Not Implemented. Implement them in a subclass, in a module of the implementation package: ```python from openapi_server.apis.pets_api_base import BasePetsApi from openapi_server.models import Pet class PetsApi(BasePetsApi): async def show_pet_by_id(self, *, pet_id: str) -> Pet: return Pet(id=1, name="Rex") ``` The application imports the modules of the implementation package when it starts, and the first subclass of a base class serves its requests. Tests can replace it with `app.dependency_overrides[get_pets_api]`. Credentials are validated the same way, by a subclass of `BaseSecurity` of `security_api.py`. The generated code covers: - routes with the status code, response class, documented responses (including `default`, ranges like `4XX` and headers), tags, summary, description, operation ID and deprecation of operations; routes of concrete paths come before the routes of templates matching them - path, query, header and cookie parameters with their aliases, defaults and constraints. Since 0.12.0, `pipeDelimited`, `spaceDelimited`, non-exploded `form` and header arrays are split into their items. `deepObject` query parameters, and parameters described with JSON `content` in a query, a header or a cookie, are validated into their models, with FastAPI's 422 errors - JSON, text and binary request bodies, forms and file uploads (`UploadFile`) - since 0.12.0, streams. A response whose only content is `text/event-stream`, JSON Lines (`application/jsonl`, `application/x-ndjson` and the like) or `application/json-seq` is streamed from the operation's method, which returns an `AsyncIterator` of the items. When the response has other content too, the items come from `_stream`, and they are streamed only when the `Accept` header names one of those media types before any other. In `text/event-stream`, each item is the `data` of an event, without an `id` or `event` field. JSON Lines and JSON text sequence request bodies reach the implementation as an `AsyncIterator` of validated items - since 0.12.0, callbacks and webhooks as routes that the served OpenAPI document describes but the application doesn't serve, and response links in the documented responses - since 0.12.0, operations marked `x-internal: true`, served but left out of the served OpenAPI document - models: classes with aliases for names that aren't valid Python names, constraints, defaults and descriptions; enums; `allOf` merged into one class; `oneOf`/`anyOf` as unions, with discriminators where the document has them; nullable types of OpenAPI 3.0 and 3.1; recursive and mutually referencing models. Since 0.12.0: `prefixItems` as `tuple[...]` when the array has exactly one item per schema (`minItems`, and `items: false` or `maxItems`), lists of the union of the item schemas otherwise; `if`/`then`/`else`, `dependentRequired`, `dependentSchemas`, `not` and draft-07 `dependencies` checked by a `model_validator` when they only test the presence and the values of properties; `unevaluatedProperties: false` rejecting unknown properties - since 0.12.0, `readOnly` and `writeOnly`: a model with such properties, or referring to such a model, has an input variant for request bodies, e.g. `PetInput`, without the `readOnly` properties, and the model itself leaves the `writeOnly` ones out - security: API keys (header, query, cookie), HTTP basic, bearer and other HTTP schemes, OAuth2 (all flows, with scopes), OpenID Connect and, since 0.12.0, mutual TLS, with global security, alternatives (a request needs to meet one of the security requirements) and anonymous access (`{}`). For a `mutualTLS` scheme, `validate_` of `BaseSecurity` (e.g. `validate_mutual_tls` for a scheme named `mutualTLS`) receives the client certificate as PEM. The ASGI server reports it in the `tls` extension of the request, and the value is `None` without one. Uvicorn reports none, so `validate_` receives `None`: started with `--ssl-ca-certs` and `--ssl-cert-reqs 2`, Uvicorn refuses connections without a valid certificate itself Files are generated again on every run, except the implementation package, the tests of the APIs, `tests/conftest.py` and `.openapi-generator-ignore`, which are generated only when they don't exist. Files listed in `.openapi-generator-ignore` (which uses the syntax of `.gitignore`) aren't written. `.openapi-generator/FILES` lists the generated files, including the ones kept because they exist, so generating again doesn't change it (since 0.12.0). Differences from openapi-generator: - routes declare their status code and response class, e.g. 201 or 204 without a body, instead of documenting every response as 200 - the implementation is one instance of the subclass, resolved by a FastAPI dependency, instead of an instance per request; the tokens of security schemes are passed to it - models are idiomatic pydantic 2 models: `oneOf`/`anyOf` are unions (discriminated where possible) instead of wrapper classes, constraints use `pattern=` instead of the deprecated `regex=`, and there are no `to_dict()`/`from_dict()` helpers - OAuth2 schemes of the same flow don't collide, and OpenID Connect schemes are supported - since 0.12.0, mutual TLS security schemes are checked by the `validate_` method of `BaseSecurity` instead of being left out - unknown options are errors, not ignored Constructs that FastAPI can't express are reported (object parameters and request bodies accepted under one media type only as warnings, the others as information) and simplified: object parameters other than `deepObject` query parameters are left out and the route receives the request instead; arrays in paths and cookies are received as strings; parameters described with `content` in a path, or with a media type other than JSON, are received as strings; nested objects in forms are received as strings. A request body with a JSON or form media type next to JSON Lines or `application/json-seq` is accepted as JSON or as the form only, because FastAPI decodes that body before the route runs. The served OpenAPI document leaves out `deepObject` query parameters and JSON `content` parameters, which dependencies in `parameters.py` read from the request, describes delimited arrays without their style, and leaves mutual TLS out. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.controller-name` | on an operation or its path item: the API module of the operation, instead of its first tag | | `x-apigenie.codegen.action-name` | name of the function of an operation, instead of its `operationId` | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out, with `skipDisabled` | | `x-internal` | since 0.12.0, `true` on an operation or its path item leaves the operation out of the served OpenAPI document; the route is still served | | `x-codegen-request-body-name` | on an operation or its request body: the name of the body parameter | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn't mapped | The extensions can live in an overlay for this target instead of in the document, e.g. `fastapi.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: FastAPI names version: 1.0.0 actions: - target: $.paths['/pets'].post update: x-codegen-request-body-name: pet x-apigenie: codegen: action-name: add_pet ``` ```sh apigenie-generator server fastapi openapi.yaml --overlay fastapi.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_fastapi.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the project is generated. ### --package-name Python package of the generated code (`packageName`), e.g. `pet_store` or `acme.pet_store`. Defaults to `openapi_server`. ### --package-version Version of the generated project (`packageVersion`). Defaults to the version of the API when pip accepts it, otherwise to `1.0.0`. ### -p, --property NAME=VALUE Sets a generator option (see below), e.g. `-p serverPort=8000`. Options given on the command line take precedence over the configuration file. Mapping options take comma-separated lists, e.g. `-p 'nameMappings=_links=links,$type=kind'`. ## Configuration Options can also be set in the configuration file, either directly or in an `additionalProperties` section, like in configuration files of openapi-generator: ```yaml version: '1.0' commands: generate: server_fastapi: packageName: pet_store serverPort: 8000 nameMappings: _links: links ``` | Option | Description | | ------ | ----------- | | `packageName` | Python package of the generated code (default `openapi_server`) | | `packageVersion` | Version of the project (defaults to the version of the API when pip accepts it, otherwise `1.0.0`) | | `serverPort` | Port the server listens to (defaults to the port of the first server, or 8080) | | `sourceFolder` | Directory of the package, relative to the output directory (default `src`) | | `fastapiImplementationPackage` | Package of the implementation of the APIs (default `impl`), inside the generated package unless useExternalImplementationPackage is set | | `useExternalImplementationPackage` | The implementation package is outside the generated package and isn't generated (default `false`) | | `generateTests` | Generate tests (tests/) (default `true`) | | `generateDocker` | Generate a Dockerfile and docker-compose.yaml (default `true`) | | `generatorVersion` | Version of the generator written into generated files | | `sortParamsByRequiredFlag` | Put required parameters before optional ones (default `true`) | | `skipDeprecated` | Don't generate code for deprecated operations (default `false`) | | `skipDisabled` | Don't generate code for operations disabled with x-apigenie (default `false`) | | `modelsLayout` | Where models are written: `modules` (a module per model, the default) or `single` (one module) | | `disallowAdditionalPropertiesIfNotPresent` | Models of schemas without additionalProperties reject unknown properties (extra="forbid") (default `false`) | | `hideGenerationTimestamp` | Accepted for compatibility with openapi-generator; generated files have no timestamps | | `modelNamePrefix` | Prefix of model names | | `modelNameSuffix` | Suffix of model names | | `modelNameMappings` | Mappings of schema names to model names (Schema=Model,...) | | `nameMappings` | Mappings of property names to field names (name=field_name,...) | | `parameterNameMappings` | Mappings of parameter names to Python names (name=python_name,...) | | `enumNameMappings` | Mappings of enum values to member names (value=NAME,...) | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Tier 1](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, with the goal of supporting every feature of the fixture. Its unsupported features are worked on first. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | ✓ pass (python 3.12.11 fastapi 0.142.2 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | ✓ 72 of 77 operations pass (python) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator server go Source: https://apigenie.pl/docs/reference/generator/server-go Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 1](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Go server for the `net/http` router of Go 1.22 from an OpenAPI document. From an AsyncAPI document, the command generates a Go Kafka application instead; see [`apigenie-generator server go` (AsyncAPI)](/docs/reference/generator/server-go-asyncapi). ## Usage ```sh apigenie-generator server go [...OPTIONS] INPUT_FILE ``` ## Description The generator writes a Go package whose code uses the standard library only. Its names and layering follow [oapi-codegen](https://github.com/oapi-codegen/oapi-codegen) (the `std-http-server` and `strict-server` targets), so code written against one of them is easy to move to the other. | File | Contents | | ---- | -------- | | `types.gen.go` | the types of the component schemas the operations use, and of their inline schemas | | `server.gen.go` | `ServerInterface`, the parameters structs, `ServerInterfaceWrapper`, `Operations`, `SecuritySchemes` and `HandlerWithOptions` | | `strict.gen.go` | `StrictServerInterface`, the request and response objects, and `NewStrictHandler` | | `senders.gen.go` | since 0.12.0, `WebhookSender` and the senders of the callbacks, for documents that have webhooks or callbacks | | `spec.gen.go`, `openapi.yaml` | the OpenAPI document, embedded with `//go:embed` (`RawSpec()`) | | `runtime_*.gen.go` | parameter binding, validation, problem details, `Nullable[T]`, `Date`, multipart helpers, the writers of server-sent events and JSON Lines, and the request encoding of the senders | | `go.mod`, `cmd//main.go` | with `layout: module` (and `main: true`) | There are two ways to implement the server: - **`ServerInterface`**: one method per operation receives the `http.ResponseWriter`, the request, the path parameters and a struct with the query, header and cookie parameters, bound and validated. The method decodes the body and writes the response. - **`StrictServerInterface`**: one method per operation receives a request object (parameters and decoded, validated body) and returns a response object, e.g. `GetPet200JSONResponse`, with its status, typed headers and body. `NewStrictHandler` turns it into a `ServerInterface`. ```go mux := http.NewServeMux() api.HandlerWithOptions(api.NewStrictHandler(server, nil), api.StdHTTPServerOptions{ BaseURL: "/api/v1", BaseRouter: mux, SecurityHandler: authenticator, // runs before parameters are bound }) log.Fatal(http.ListenAndServe(":8080", mux)) ``` `HandlerWithOptions` registers one pattern per operation, e.g. `GET /pets/{petId}`, so routing, `405 Method Not Allowed` (with `Allow`) and `HEAD` requests are handled by `http.ServeMux`: - paths ending with `/` are registered as `/{$}`, so that they don't match the paths below them; - path parameters whose names aren't Go identifiers (`{pet-id}`) are renamed, and parameters sharing a path segment with other text (`/files/{name}.{ext}`) are split out of it; - patterns `http.ServeMux` can't register together (it panics), such as `GET /a/{x}/b` and `GET /a/b/{y}`, are served through one pattern generalizing them, which sends each request to the most specific operation. `route_conflicts: error` reports them as errors instead; - since 0.12.0, an operation with its own server is registered below the path of that server's URL instead of `BaseURL`. Its server is the first of the `servers` of the operation, or else of its path item, with the default values of its variables: `POST /v2/shipments/imports` for `https://uploads.example.com/v2`. A URL without a path registers the operation at the root (`GET /health` for `https://status.example.com`). The `Server` and `ServerPath` fields of the operation's entry in `Operations` hold the URL and its path. Since 0.12.0, operations marked `x-internal: true` (on the operation or its path item) are left out, and so are webhooks and callback requests marked so. `internal_operations: true` generates them too. `include_tags` and `exclude_tags` don't apply to webhooks; callbacks follow their operation. ### Streams Since 0.12.0, responses of `text/event-stream` get an `Events` field, a `<-chan ServerSentEvent[T]`. `ServerSentEvent` has the fields `ID`, `Event`, `Retry` (milliseconds) and `Data`. `ID` and `Event` aren't written when empty, nor `Retry` unless it is positive. `T` is the type of the `contentSchema` of the `data` property of the `itemSchema`. A `data` property without `contentSchema`, or a response without `itemSchema`, gives `string`. An `itemSchema` without a `data` property is the type of `Data` itself. A `string` is written as is, other types as JSON. Responses of `application/jsonl`, `application/x-jsonlines` and `application/x-ndjson` with an `itemSchema` get an `Items` channel of the item type. Each event or line is written and flushed as it arrives, until the handler closes the channel; when the channel is nil, `Body` is written instead. A write stops at the first error, for example when the client disconnects, so the producer must stop when the request's context is done: ```go func (s *server) GetTrackingEvents(ctx context.Context, request api.GetTrackingEventsRequestObject) (api.GetTrackingEventsResponseObject, error) { events := make(chan api.ServerSentEvent[api.TrackingEvent]) go func() { defer close(events) for event := range s.tracking.Watch(ctx, request.ShipmentID) { select { case events <- api.ServerSentEvent[api.TrackingEvent]{Event: "tracking", Data: event}: case <-ctx.Done(): return } } }() return api.GetTrackingEvents200TextEventStreamResponse{Events: events}, nil } ``` ### Webhooks and callbacks Since 0.12.0, `WebhookSender` has one method per webhook, named after its `operationId` (`OnShipmentDelivered`), or after the webhook's name and method without one. Each callback of an operation gets a sender type named after the operation and the callback, e.g. `CreateShipmentStatusChangedCallback`. Its method is `Send`, or one method per HTTP method (`Post`, `Put`) when the callback has several. A method takes a `context.Context` and the URL to send to. Then it takes the parameters struct, when the request has query, header or cookie parameters, and the body, when it has one. An optional JSON body is a pointer, unless its type is a slice, a map or `any`, and is sent only when it is set. It returns the `*http.Response`, whose body the caller closes. The caller gives the URL: the subscriber's, or the value the callback expression selects from the request, which the method's doc comment names (`given by {$request.body#/callbackUrl}`). Path parameters are part of that URL. Parameters are serialized like those of [`client go`](/docs/reference/generator/client-go), in their style: ```go sender := api.WebhookSender{Client: httpClient} // http.DefaultClient when nil params := api.OnShipmentDeliveredParams{CarpetExpressSignature: signature} if err := params.Validate(); err != nil { return err } response, err := sender.OnShipmentDelivered(ctx, subscription.URL, params, event) if err != nil { return err } defer response.Body.Close() ``` A sender sends the first media type of the request body it can encode: JSON, text, binary, or a form without declared fields (`url.Values`). A request body with only other media types, multipart included, is left out, and the generator warns. For a webhook `orderForm`, the warning is `The request body of POST orderForm has no media type the sender can encode (JSON, text, binary or a form without declared fields); the request is sent without a body`. ### Types - Optional properties are pointers with `omitempty`; slices, maps and `any` stay values. `optional_fields: omitzero` uses values with `omitzero` (Go 1.24). - Optional properties that can be null are `Nullable[T]`, which tells absent, null and set values apart; required ones are pointers. `nullable_type: pointer` uses pointers for both. - Required properties that are `readOnly` or `writeOnly` are pointers, as they are absent from requests or responses. - Structs that would contain themselves hold pointers. - Enums are defined types with constants named after the type and the value (`PetStatusAvailable`), `PetStatusValues()`, `IsValid()` and `Validate()`. - `oneOf` and `anyOf` schemas are structs with one pointer per variant. With a discriminator, the value goes to the variant its property selects: through the `mapping`, the name of the schema or the value the schema gives the property (`const`); other values go to the `defaultMapping` variant (`x-defaultMapping` in 3.0 and 3.1 documents), or are kept in `Raw`. Without a discriminator, the value goes to the first variant it decodes into without unknown properties and validates against. - since 0.12.0, `prefixItems` tuples without `items`, or with `items: false`, are slices. When every position is a reference or a scalar of the same Go type and nullability, it's a slice of that type (`[]float64`), and `Validate()` checks each position; otherwise it's `[]any`. With `items: false`, `Validate()` checks the length too. - since 0.12.0, a schema whose only properties are `patternProperties` is a map. With one pattern and `additionalProperties: false`, it maps to the pattern's type. When the patterns and a schema of `additionalProperties` have the same type, it maps to that type; otherwise to `any`. `Validate()` checks the keys against the patterns when `additionalProperties` is `false`. It checks the values of each pattern, and those of the other keys against `additionalProperties`, when their type has a `Validate()` method, or is a boolean, an integer, a number or a string. - `allOf` schemas are merged into one struct; an `anyOf` or `oneOf` whose members only list required properties (`anyOf: [{required: [email]}, {required: [phone]}]`) is checked by `Validate()`. - `additionalProperties` are kept in an `AdditionalProperties` map. - `date-time` strings are `time.Time`, `date` strings `Date`, `byte` and `binary` strings `[]byte` (files in multipart bodies). ### Validation Every type has a `Validate()` method that checks the constraints of its schema. The checks cover lengths, patterns, bounds, `multipleOf`, items, tuple positions, properties, pattern properties, `if`/`then`/`else`, `dependentRequired`, `dependentSchemas` and enums (the tuple, pattern and condition checks since 0.12.0), and since 0.12.0 `not` and draft-07 `dependencies` within the same limits as `if`/`then`/`else` (see below). They also cover the `email`, `uuid`, `uri`, `hostname`, `ipv4`, `ipv6`, `date`, `date-time` and `time` formats; `contentEncoding: base64` strings are `[]byte`. Parameters and request bodies are validated before the handlers are called, and failures are answered with [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) problem details listing the failed checks: ```json {"title":"Bad Request","status":400,"detail":"The request is not valid.", "errors":[{"path":"limit","check":"maximum","message":"must be less than or equal to 100"}]} ``` `DefaultErrorHandler` maps errors to statuses: 400 for parameters and bodies, 413 for bodies larger than `max_body_bytes`, 415 for unsupported media types, the status of a `SecurityError` (401 by default) or of an error implementing `StatusCode() int`, and 500 otherwise. ### Extensions | Extension | Effect | | --------- | ------ | | `x-go-name` | name of the type of a schema, or of the field of a property | | `x-go-type` | Go type of a schema, e.g. `decimal.Decimal`; with `x-go-type-import: {path: ...}` for its package | | `x-go-type-skip-optional-pointer` | the optional property isn't a pointer | | `x-go-json-ignore` | the field gets the tag `json:"-"` | | `x-omitempty` | `true` or `false` overrides the `omitempty` of the field | | `x-enum-varnames`, `x-enumNames` | names of the enum constants | | `x-enum-descriptions` | comments of the enum constants | | `x-apigenie.codegen.name` | name of the type of a component schema, when it has no `x-go-name` | | `x-apigenie.codegen.action-name` | name of the handler method of an operation without an `operationId` (with the default `action_naming`, which lists `id` first) | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn't mapped | The extensions can live in an overlay for this target instead of in the document, e.g. `go.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Go types version: 1.0.0 actions: - target: $.components.schemas.Pet update: x-go-name: Animal - target: $.components.schemas.Pet.properties.price update: x-go-type: decimal.Decimal x-go-type-import: path: github.com/shopspring/decimal ``` ```sh apigenie-generator server go openapi.yaml --overlay go.overlay.yaml -o out ``` ### Limitations - Links aren't generated: they describe follow-up requests of clients. - The senders don't validate what they send: call `Validate()` on the parameters struct and the body first. Multipart bodies aren't sent. - Operations with their own server that share a pattern with other operations (see `route_conflicts`) are served below `BaseURL`, and the host of the server isn't checked. - Request streams are `io.Reader` bodies; only responses are typed streams. - `Validate()` doesn't check `unevaluatedProperties`. It checks `if`/`then`/`else`, `not`, `dependentSchemas` and the schemas of draft-07 `dependencies` only when their schemas use `required` and the `const` and `enum` of properties, and skips the others. - XML bodies are passed as streams (`io.Reader`), and form or multipart responses too. - Patterns using lookaround or backreferences, which Go's `regexp` package doesn't support, aren't checked (a warning says so). Patterns are compiled when first used. - `allOf` schemas are flattened: there are no type hierarchies. - Exported names of the runtime (`Problem`, `Date`, `File`, `Nullable`, `Operation`, ...) are reserved: schemas with these names get numbered types, e.g. `Problem2`. - The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle documents referencing other files with `apigenie bundle`. ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_go.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the package is generated. ### --package-name Name of the Go package. Defaults to the name of the output directory (`api` when it isn't a valid package name). ### --package-version Ignored: Go packages have no version. ### -p, --property NAME=VALUE Sets a generator option (see below), e.g. `-p layout=module`. Options given on the command line take precedence over the configuration file. Lists are comma-separated (`-p include_tags=pets,store`) and mappings too (`-p type_mappings=uuid=github.com/google/uuid.UUID`). ## Configuration ```yaml version: '1.0' commands: generate: server_go: package: petstore layout: module module: github.com/acme/petstore type_mappings: uuid: github.com/google/uuid.UUID ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `package` | string | name of the output directory | Name of the Go package; also set by `--package-name`. | | `layout` | `package` or `module` | `package` | `module` also writes `go.mod`, making the output a module of its own. | | `module` | string | `example.com/` | Module path written to `go.mod`. | | `main` | boolean | `false` | With `layout: module`, writes `cmd//main.go` running a server whose operations answer 501, unless the file exists. | | `generate` | list of `types`, `server`, `strict` | all | Files to write. `strict` requires `server`, which requires `types`. | | `embedded_spec` | boolean | `true` | Writes `openapi.yaml` and `spec.gen.go` embedding it. | | `optional_fields` | `pointer` or `omitzero` | `pointer` | Optional properties as pointers with `omitempty`, or as values with `omitzero` (Go 1.24). | | `nullable_type` | `tristate` or `pointer` | `tristate` | Optional nullable properties as `Nullable[T]`, or as pointers. | | `include_tags` | list of strings | | Generates only the operations with one of these tags. | | `exclude_tags` | list of strings | | Skips the operations with one of these tags. | | `skip_prune` | boolean | `false` | Keeps the component schemas that no generated operation uses. | | `internal_operations` | boolean | `false` | Also generates the operations marked `x-internal: true` (on the operation or its path). | | `validate_requests` | boolean | `true` | Validates parameters and request bodies against their schemas. | | `validate_responses` | boolean | `false` | Validates the bodies of strict responses before writing them (500 when they aren't valid). | | `route_conflicts` | `warn` or `error` | `warn` | Serve the patterns `http.ServeMux` can't register together through a shared pattern, or report them as errors. | | `initialisms` | list of strings | | Words written in upper case in identifiers, besides `ID`, `URL`, `HTTP`, `JSON` and the other initialisms of golint. | | `type_mappings` | map of strings | | Go types of string formats or `x-go-type` names, e.g. `uuid: github.com/google/uuid.UUID`. | | `max_body_bytes` | integer | `0` (no limit) | Largest request body the strict server reads (413 beyond). | | `max_multipart_memory` | integer | `33554432` | Memory multipart bodies may take before their files are stored on disk. | | `action_naming` | list of `id`, `extension`, `url` | `id, extension, url` | Where operation names come from, in order of preference. | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Tier 1](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, with the goal of supporting every feature of the fixture. Its unsupported features are worked on first. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | ✓ pass (go version go1.22.5 linux/amd64) | ✓ 70 of 77 operations pass, 2 known failures (go) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | runs before a release | runs before a release, 2 known failures | --- # apigenie-generator server hummingbird Source: https://apigenie.pl/docs/reference/generator/server-hummingbird Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Experimental](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Swift server package for Hummingbird 2 from an OpenAPI document. > **(experimental, outside the 1.0 compatibility promise)** Levels 2 and 3 of the conformance suite > are wired for the generated packages but haven't passed a run yet, so their types and methods can > still change. `server hummingbird` says so in its `--help` and on the first line it prints, on the > standard error. See the [experimental commands](/docs/reference/cli#experimental-commands). ## Usage ```sh apigenie-generator server hummingbird [...OPTIONS] INPUT_FILE ``` ## Description The generator writes a Swift package with one library target, depending on Hummingbird. Its code is that of the [`server vapor`](/docs/reference/generator/server-vapor) packages except `Server/Hummingbird.swift`, the platform and the dependencies in `Package.swift`, and schemas named like a Hummingbird type (see [Limitations](#limitations)). Code written against one moves to the other by changing the few lines that start the server. | File | Contents | | ---- | -------- | | `Package.swift` | tools version 6.0, macOS 14, the Hummingbird 2 and swift-http-types dependencies and a library product of the module | | `.swift-format` | the swift-format settings the generated code follows (`swift format lint`) | | `Sources//Server/APIHandler.swift` | the `APIHandler` protocol, with an async method per operation, and `UnimplementedHandler` | | `Sources//Server/Requests.swift` | the request struct of each operation: its parameters, its body and the credentials it was sent with | | `Sources//Server/Routes.swift` | `APIRoutes`: an `APIRoute` per operation, which reads the request, checks it and calls the handler | | `Sources//Server/Senders.swift` | `WebhookSender` and `CallbackSender`, for documents with webhooks or callbacks | | `Sources//Server/Hummingbird.swift` | `APIRoutes.register(on:handler:)`, which registers the routes with a Hummingbird router | | `Sources//Operations.swift` | per operation, the enum of its responses, the structs of their headers and the enums of bodies of several media types | | `Sources//Models.swift` | the types of the component schemas the operations use, and of their inline schemas | | `Sources//Runtime/*.swift` | requests and responses of the routes, JSON coding, parameter styles, streams, multipart bodies, validation, `Nullable`, `CalendarDate`, `Indirect`, `JSONValue`, and the transport of the senders | The module is named after the document's title followed by `Server` (`Carpet Express Shipping API` gives `CarpetExpressShippingAPIServer`; `APIServer` when the title gives no name), unless `--package-name` or `package` names it. A server implements `APIHandler` and registers it: ```swift import CarpetExpress import Hummingbird struct Shipments: APIHandler { func getShipment(_ request: GetShipmentRequest) async throws -> GetShipmentResponse { guard let stored = try await store.shipment(request.shipmentID) else { return .notFound(Problem(type: "about:blank", title: "No such shipment", status: 404)) } return .ok(body: stored.shipment, headers: GetShipmentOkHeaders(eTag: stored.eTag)) } // ... a method per operation } let router = Router() APIRoutes.register(on: router, handler: Shipments()) let app = Application( router: router, configuration: .init(address: .hostname("0.0.0.0", port: 8080)) ) try await app.runService() ``` ### Handler `APIHandler` has a method per operation, named after its `operationId`, taking the operation's request struct and returning its response enum, the same enum the [Swift client](/docs/reference/generator/client-swift) returns: ```swift func createShipment(_ request: CreateShipmentRequest) async throws -> CreateShipmentResponse public enum CreateShipmentResponse: Sendable { /// `201`: Shipment booked. case created(body: Shipment, headers: CreateShipmentCreatedHeaders) /// `400`: The request could not be parsed. case badRequest(Problem) // ... 202, 401, 403, 409, 422, 429 /// `5XX`: A carrier or Carpet Express itself is unavailable. case serverError(statusCode: Int, body: Problem, headers: CreateShipmentServerErrorHeaders) } ``` - The request struct has a property per path, query, header and cookie parameter, `body` (an optional when the body is), and `credentials`, the credentials of the security requirement the request met, by scheme. - A case of the response enum is written with its status (the status code of ranges and `default`), its headers and its body, as JSON, text, bytes, a form, multipart parts or a stream of the media type the case holds. - A method that throws `HandlerError.problem(status:title:detail:)` answers that status with [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) problem details; `HandlerError.notImplemented` answers 501, and any other error 500. - `UnimplementedHandler` answers every operation with 501: a starting point, and a server for tests of the routes. - Deprecated operations say so in their documentation, but aren't `@available(*, deprecated)`: the routes call every method. ### Routes Before the handler runs, the route of an operation: 1. checks the security requirements: the request needs the credentials of one alternative, or it gets `401`; 2. reads the path, query, header and cookie parameters in their style and `explode` mode (`simple`, `label` and `matrix` path parameters, `form`, `spaceDelimited`, `pipeDelimited` and `deepObject` query parameters; JSON for parameters described with `content`), and checks them against their schemas; 3. reads the body by its `Content-Type`: JSON, `application/x-www-form-urlencoded`, `multipart/form-data`, JSON Lines and JSON text sequences, text and bytes, including media type ranges such as `image/*`. A body of another media type gets `415`, a missing required body `400`. A request that breaks the document gets `400` with problem details whose `errors` list the JSON pointers of the values that break it, also of a parameter that can't be read as its schema's type (`/query/limit` for `?limit=abc`); pretty-printed here, and the order of the keys varies: ```json { "type": "about:blank", "title": "Bad Request", "status": 400, "detail": "/path/shipmentId: must match the pattern ^shp_[0-9A-Za-z]{24}$", "errors": [ { "pointer": "/path/shipmentId", "detail": "must match the pattern ^shp_[0-9A-Za-z]{24}$" } ] } ``` The routes are registered below the path of the first server of the operation or its path item, else of the document's first server (`/v2/shipments` for `https://api.carpetexpress.example/v2`). `APIRoutes.all(_:)` returns them, and `APIRoutes.register(_:on:)` registers them with other prefixes: ```swift let routes = APIRoutes.all(Shipments()).map { route in var moved = route moved.prefix = "/api" return moved } let router = Router() router.add(middleware: APIKeyCheck()) APIRoutes.register(routes, on: router) ``` `register` takes a `Router` of any `RequestContext`, and the routes run its middleware. Request bodies are collected before the routes read them, up to `maxBodySize` bytes (10 MB by default); a larger body gets `413` from Hummingbird. ### Streams A response of `text/event-stream`, `application/jsonl` or `application/json-seq` holds an `AsyncThrowingStream` of its items, typed by the media type's `itemSchema` (OpenAPI 3.2; `x-itemSchema` in 3.0 and 3.1 documents), and the route writes each item as it comes: ```swift let events = AsyncThrowingStream, any Error> { continuation in // yield the events as they happen } return .ok(.eventStream(events)) ``` JSON Lines and JSON text sequence request bodies are arrays of their items. ### Multipart bodies `multipart/form-data` bodies of object schemas are structs with a property per part. Binary parts (`format: binary`, or `contentMediaType` in 3.1 and 3.2) are `MultipartFile` values (data, file name and media type), arrays of them `[MultipartFile]`. Object parts, and parts whose encoding has a JSON `contentType`, are read as JSON; other parts as text, a part per item of arrays. ### Security The route of an operation gives the request the credentials of the first alternative of its security requirements whose schemes all have some; checking them is up to the handler: | Scheme | Credential in `request.credentials` | | ------ | ----------------------------------- | | `apiKey` in a header, the query or a cookie | the key | | `http` `basic` | `username:password` | | `http` `bearer`, `oauth2`, `openIdConnect` | the bearer token | | `mutualTLS` | an empty string: the server doesn't check client certificates, so the TLS layer in front of it must require them (the generator warns) | An operation with `security: []` gets no credentials; an empty alternative lets requests without credentials through. ### Webhooks and callbacks `WebhookSender` has a method per webhook of the document and `CallbackSender` one per callback of the operations. A method is named after the request's `operationId`, else its `x-apigenie.codegen.action-name`, else the webhook, or the operation and the callback (`createShipmentStatusChanged`). Each takes the URL the receiver gave, the request's body and its parameters, and returns the request's response enum: ```swift let sender = WebhookSender() let response = try await sender.onShipmentStatusChanged( to: subscription.url, body: event, carpetExpressSignature: signature ) ``` The senders send through an `HTTPTransport`, `URLSessionTransport` by default, and check request bodies against their schemas (`validatesRequests`). The credentials of the security requirements of webhooks and callbacks are up to the transport. ## Stability Experimental, since 0.12.0. ## What you depend on - Swift 6.0 or later, in the Swift 6 language mode (strict concurrency). - Swift Package Manager (`swift build`), which reads `Package.swift` (tools version 6.0). - [Hummingbird](https://github.com/hummingbird-project/hummingbird) 2.0 or later, and [swift-http-types](https://github.com/apple/swift-http-types) 1.0 or later. - macOS 14 or later, or Linux. ## Features | Feature | Support | | ------- | ------- | | Authentication schemes | partial: the credentials of API keys, HTTP basic and bearer, OAuth 2 and OpenID Connect tokens reach the handler, which checks them | | Streaming | yes: server-sent events, JSON Lines and JSON text sequences are written as the items come | | Pagination | no | | File upload | yes: multipart bodies and binary bodies | | Enums | yes; values the document doesn't list get `400` | | Discriminators | yes, with `mapping` and `defaultMapping` | | Nullable | yes: `Nullable?` tells missing, null and set values apart | | Errors | yes: a case per documented status, RFC 9457 problem details for invalid requests | | Retries | no: the senders send each request once; an `HTTPTransport` of your own can retry | | Webhooks and callbacks | yes: typed senders | ## Type mapping The types are those of the [Swift client](/docs/reference/generator/client-swift#type-mapping), except enums, which have no `unknown` case: a server rejects values the document doesn't list. Bodies are checked against their schemas as they are decoded. ## Extensions | Extension | Effect | | --------- | ------ | | `x-swift-name` | name of the type of a schema, or of the property of a property | | `x-enum-varnames`, `x-enumNames` | names of the enum cases | | `x-enum-descriptions` | documentation of the enum cases | | `x-apigenie.codegen.name` | name of the type of a component schema, when it has no `x-swift-name` | | `x-apigenie.codegen.action-name` | name of the method of an operation without an `operationId` (with the default `action_naming`) | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out | | `x-internal` | `true` on an operation, a webhook or a callback (or its path item) leaves it out, unless `internal_operations` is set | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents | | `x-itemSchema` | `itemSchema` of a media type in OpenAPI 3.0 and 3.1 documents | ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_hummingbird.overlay` in the configuration file. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning. ### --no-config Doesn't look for `apigenie.yaml` (or `.apigenie.yaml`) in the current directory and its parents up to the root of the repository. ### --json Prints one JSON document on the standard output (`formatVersion`, `command`, `exitStatus`, `messages`) instead of the messages. ### -o, --output Directory where the package is generated. ### --package-name Name of the Swift module, its library product and the package. Defaults to the document's title followed by `Server`. ### --package-version Ignored: Swift packages take their versions from Git tags. ### -p, --property NAME=VALUE Sets a generator option (see below), e.g. `-p internal_operations=true`. Options given on the command line take precedence over the configuration file. Lists are comma-separated (`-p include_tags=shipments,rates`). ## Configuration ```yaml version: '1.0' commands: generate: server_hummingbird: package: CarpetExpress exclude_tags: [internal] ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `package` | string | the document's title followed by `Server` | Name of the module, its library product and the package; also set by `--package-name`. | | `include_tags` | list of strings | | Generates only the operations with one of these tags. | | `exclude_tags` | list of strings | | Skips the operations with one of these tags. | | `skip_prune` | boolean | `false` | Keeps the component schemas that no generated operation uses. | | `internal_operations` | boolean | `false` | Also generates the operations, webhooks and callbacks marked `x-internal: true`. | | `initialisms` | list of strings | | Words written in one case in identifiers, besides `ID`, `URL`, `HTTP`, `JSON` and the other common initialisms. | | `action_naming` | list of `id`, `extension`, `url` | `id, extension, url` | Where method names come from, in order of preference. | ## Exit status 0 when the package was generated; 2 when the options, the configuration, an overlay or the input document can't be used (with `--strict`, also when an overlay action selects nothing). See [`apigenie-generator`](/docs/reference/generator). ## Limitations - What the conformance fixture doesn't cover is listed under [Verification](#verification); links are out of scope there. - The routes don't check credentials, only that a request has them: the handler decides whether they are valid. HTTP schemes other than `basic` and `bearer` get a warning, and the operations requiring them answer `401`. - Requests are checked as the Swift client's `validate()` checks bodies: patterns Swift's `Regex` can't compile, `unevaluatedProperties` other than `false`, and formats other than `email`, `uri`, `uuid`, `date`, `date-time`, `ipv4` and `ipv6` aren't checked, and such values reach the handler. `if`/`then`/`else` and `dependentSchemas` are checked only when their schemas use `required` and the `const` and `enum` of properties. - `format: decimal` numbers are decoded by `JSONDecoder`, which reads them through `Double` on macOS before 15. - Response bodies aren't checked against their schemas. - A `oneOf` without a discriminator decodes as its first variant that decodes, even when another one matches too. - Types of the standard library, Foundation, the runtime, the server and the Hummingbird types the adapter uses (`Data`, `Error`, `APIHandler`, `APIRoutes`, `ServerRequest`, `Request`, `Response`, `Router`, ...) are reserved: schemas with these names get types with `Model` after their names, e.g. `ResponseModel`. - The input must be an OpenAPI 3.0, 3.1 or 3.2 document or a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle documents referencing other files with `apigenie bundle`. ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Experimental](/docs/reference/generator/conformance#tiers). It isn't run at every level yet. It is outside the [1.0 compatibility promise](/docs/reference/cli/compatibility): its options and the shape of its output can change, or it can go away, in a minor release. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | ✓ pass (Swift version 6.0.3 (swift-6.0.3-RELEASE)) | ✓ 70 of 77 operations pass, 2 known failures (swift) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | runs before a release | runs before a release, 2 known failures | --- # apigenie-generator server mcp Source: https://apigenie.pl/docs/reference/generator/server-mcp Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2, experimental](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · 1 feature of the fixture not supported yet · [Verification](#verification) Generate a [Model Context Protocol](https://modelcontextprotocol.io) server in TypeScript from an OpenAPI document, so that AI agents call the API through typed tools. > **(experimental, outside the 1.0 compatibility promise)** MCP and its SDK are still moving, and > tool names and result shapes can change with them. `server mcp` says so in its `--help` and on > the first line it prints, on the standard error. See the > [experimental commands](/docs/reference/cli#experimental-commands). ## Usage ```sh apigenie-generator server mcp [...OPTIONS] INPUT_FILE ``` ## Description The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle documents referencing other files with [`apigenie bundle`](/docs/reference/cli/bundle). The generated npm package is a server on the official MCP SDK ([`@modelcontextprotocol/server`](https://www.npmjs.com/package/@modelcontextprotocol/server) 2), which MCP clients (Claude Code, Claude Desktop, IDEs) start and talk to over stdio: | File | Content | | ---------------- | ------------------------------------------------------------------------------- | | `src/client/` | a [fetch client](/docs/reference/generator/client-fetch) of the API, which the tools call | | `src/schemas.ts` | [Zod](https://zod.dev) (v4) schemas of the components, and of the arguments and results of the tools | | `src/tools.ts` | `registerTools(server)`, registering a tool per operation | | `src/config.ts` | the base URL, whether operations go to their own servers, the credentials and the client certificate, read from environment variables | | `src/runtime.ts` | the call of an operation and its result as a tool result | | `src/server.ts` | `createServer()`, an `McpServer` with the tools | | `src/index.ts` | the entry point (the package's `bin`): the server on stdio | | `README.md` | the environment variables, the tools, and how to add the server to a client | ```sh apigenie-generator server mcp openapi.yaml -o petstore-mcp cd petstore-mcp && npm install && npm run build claude mcp add petstore --env PET_STORE_BASE_URL=https://petstore.example.com/v1 -- node "$PWD/dist/index.js" ``` ### Tools Every operation becomes a tool: - its name is the `operationId`, with other characters than letters, digits, `_` and `-` replaced by `_` (at most 64 characters), or the name of the client's function for operations without one; - its title is the summary, and its description the summary and the description (or the method and path), starting with "Deprecated." for deprecated operations; - its arguments are the parameters, by name, and the request body as `body` (`requestBody` when a parameter is named `body`), validated by their schemas before the API is called. Binary bodies, and the files of `multipart/form-data` bodies, are base64-encoded strings. Since 0.12.0, a body that the operation accepts in several media types of one kind (two JSON patch formats, for example) takes any of their schemas. The `contentType` argument (`bodyContentType` when a parameter has that name) names the one sent, the first of them in the document by default, and the body has to match its schema (a media type without a schema takes any body); - since 0.12.0, a oneOf with a discriminator and a `defaultMapping` (`x-defaultMapping` in 3.0 and 3.1 documents) validates a value (an argument or a result) against the option its property selects, or against the default one when the property is missing or its value isn't mapped. The members of the oneOf have to be local references; a `defaultMapping` naming none of them is reported as a warning and ignored; - GET, HEAD and QUERY operations are marked read-only, DELETE operations destructive, and PUT and DELETE operations idempotent. A tool returns the status and the body of the response, as structured content (`{ "status": 200, "body": ... }`) described by the tool's output schema, and as JSON text. Binary bodies are returned as an embedded resource, with `{ status, contentType, size }`. A failed request is an error result with the status and the body of the response, and so is a response the API document doesn't describe, which lists what doesn't match. Operations with `x-mcp: false`, on the operation or its path item, don't become tools, nor do operations marked `x-internal: true` (unless `internal_operations` is set) or disabled with `x-apigenie`. ```yaml paths: /admin/reset: post: x-mcp: false ``` ### Environment variables The server reads its settings from environment variables, prefixed by the API title in upper snake case (`PET_STORE` for "Pet Store", see `env_prefix`). They hold the base URL of the API, whether operations with servers of their own are sent there, and the credentials and TLS files of its security schemes: | Variable | Value | | ------------------------------------------------ | ----------------------------------------------------- | | `_BASE_URL` | base URL of the API; the first server of the document by default | | `_OPERATION_SERVERS` | since 0.12.0, `true` sends an operation with servers of its own to the first of them, `false` to the base URL; by default `true` while `_BASE_URL` isn't set (`false` with `--mock`); case is ignored, and any other value makes the server exit with status 1 at start | | `_` | API key of an `apiKey` scheme | | `__TOKEN` | token of an HTTP `bearer` scheme | | `__USERNAME`, `..._PASSWORD` | user name and password of an HTTP `basic` scheme | | `__ACCESS_TOKEN` | access token of an `oauth2` or `openIdConnect` scheme | | `__CERT`, `..._KEY` | since 0.12.0, paths of the PEM files of the client certificate and its key, of a `mutualTLS` scheme; set both or neither. Only one of them set, or a file that can't be read, makes the server exit with status 1 at start | | `__CA` | since 0.12.0, path of the PEM file of the CA bundle the API's certificate is checked against, in place of the default CAs, of a `mutualTLS` scheme; optional. A file that can't be read makes the server exit with status 1 at start | `` is the name of the scheme in upper snake case (`apiKey` gives `API_KEY`). The generated `README.md` lists the variables of the API. Since 0.12.0, when `__CERT` and `__KEY` are set, the server presents that client certificate on every connection, to every server of the API, through an [undici](https://undici.nodejs.org) `Agent`. `__CA` alone makes the server check the API's certificate against that bundle instead of the default CAs, without presenting a client certificate. Only the first `mutualTLS` scheme of the document (OpenAPI 3.1 and 3.2) has these variables; the generator warns about the others. A package generated from such a document depends on `undici` 7. ### Mock server With `--mock`, the package also contains the document (`openapi.json`) and an `npm run mock` script serving it with [`apigenie-server`](/docs/reference/server), and the tools call `http://127.0.0.1:4010` when no base URL is set, with the placeholder `mock` for the credentials that aren't set (the mock server only checks that they are present): a demo of the tools needs no running API and no credentials. ```sh apigenie-generator server mcp openapi.yaml -o petstore-mcp --mock cd petstore-mcp && npm install && npm run build npm run mock # in another terminal ``` ## Extensions | Extension | Effect | | --------- | ------ | | `x-mcp` | `false` on an operation or its path item: the operation isn't a tool | | `x-internal` | `true` on an operation or its path item leaves it out, unless `internal_operations` is set | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves it out | The extensions can live in an overlay for this target instead of in the document, e.g. `mcp.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: MCP tools version: 1.0.0 actions: - target: $.paths['/admin/reset'].post update: x-mcp: false ``` ```sh apigenie-generator server mcp openapi.yaml --overlay mcp.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_mcp.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the package is generated. ### --package-name Name of the package and of the MCP server, `-mcp` by default. ### --package-version Version of the package and of the MCP server, the version of the API by default. ### --mock Make the tools call `apigenie-server` mocking the API when no base URL is set, as described above. Same as `mock: true`. ## Configuration ```yaml version: '1.0' commands: generate: server_mcp: include_tags: [pets, store] env_prefix: PETSTORE ``` | Option | Description | | --------------------- | ------------------------------------------------------------------------------------------------------------ | | `include_tags` | only the operations with one of these tags become tools (a list or a comma-separated string); all by default | | `exclude_tags` | the operations with one of these tags don't become tools | | `internal_operations` | `true` also makes tools of the operations marked `x-internal: true` (default: `false`) | | `env_prefix` | prefix of the environment variables, e.g. `PETSTORE`; the API title in upper snake case by default | | `output_schema` | `false` leaves out the output schemas of the tools (default: `true`) | | `mock` | `true` points the tools at `apigenie-server` by default, as `--mock` does (default: `false`) | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Tier 2, experimental](/docs/reference/generator/conformance#tiers). It goes through all three levels like Tier 2, but follows a specification and SDK that are still changing. It is outside the [1.0 compatibility promise](/docs/reference/cli/compatibility): its options and the shape of its output can change, or it can go away, in a minor release. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 34 supported, 1 not yet, 2 not checked | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, @modelcontextprotocol/server 2) | ✓ 38 of 39 operations pass, 1 known failure (node) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 34 supported, 1 not yet, 2 not checked | runs before a release | runs before a release, 1 known failure | Not supported yet, as the target's manifest says: - `schemas.read-write-only`: readOnly and writeOnly are ignored; one schema serves arguments and results, so createWebhookSubscription's result declares the writeOnly `secret`. --- # apigenie-generator server orpc Source: https://apigenie.pl/docs/reference/generator/server-orpc Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a TypeScript server based on [oRPC](https://orpc.dev) from an OpenAPI document. ## Usage ```sh apigenie-generator server orpc [...OPTIONS] INPUT_FILE ``` ## Description The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle documents referencing other files with [`apigenie bundle`](/docs/reference/cli/bundle). Every operation becomes an oRPC procedure, with [Zod](https://zod.dev) (v4) schemas validating its input and output. The generated npm package contains: | File | Content | | ------------------------- | -------------------------------------------------------------------------- | | `src/schemas.ts` | Zod schemas, with their types, of the components, bodies, inputs and outputs | | `src/contract/<group>.ts` | the contract of each procedure: route, input, output and errors | | `src/contract/index.ts` | the contract router, by group | | `src/handlers/<group>.ts` | a handler per procedure, throwing `NOT_IMPLEMENTED` | | `src/orpc.ts` | the context of the procedures and `implement(contract)` | | `src/router.ts` | the router assembling the handlers | | `src/server.ts` | a Node.js HTTP server with oRPC's `OpenAPIHandler` | | `src/main.ts` | starts the server on the port in `PORT` (3000 by default) | | `src/senders.ts` | `createWebhooks()` and `createCallbacks()`, when the document has webhooks or callbacks | | `src/outgoing.ts` | the module sending their requests, shared with the Express server | | `src/index.ts` | exports of the package | Procedures are grouped by the first tag of their operations, or the first segment of their paths, and named after their `operationId`s. The handlers, `orpc.ts`, `server.ts`, `main.ts`, `package.json` and `tsconfig.json` are meant to be edited, and are only written when they don't exist. Regenerating updates the schemas, the contract, the router and the senders (`senders.ts`, `outgoing.ts`); the TypeScript compiler then reports the handlers that new operations need. ```sh apigenie-generator server orpc openapi.yaml -o server cd server && npm install && npm run dev ``` The server answers the operations under the path of the first server of the document (e.g. `/v1`), and serves its OpenAPI document at `/spec.json` and an API reference at `/`. Operations with servers of their own (operation or path item `servers`) with another path, e.g. a health check on the root of a status host, are also answered at that path. ### Inputs and outputs A procedure receives the path parameters merged with the query parameters (GET) or the body (other methods), oRPC's `compact` input structure, unless that would lose part of the request: operations with header or cookie parameters, query parameters in other methods than GET, or bodies which can't be merged with the path parameters get the `detailed` structure, with `params`, `query`, `headers` (in lower case) and `body`. Parameters are converted from strings to the types of their schemas, and array parameters accept repeated values, a single value, and the delimited values of the `form` (with `explode: false`), `spaceDelimited` and `pipeDelimited` styles. Cookie parameters are read from the `Cookie` header (`headers.cookie`), parameters described by `content: application/json` are parsed as JSON, and a path segment of several parameters, such as `/labels/{labelId}.{extension}`, is routed as one parameter and split into its parameters. The body is read in any of the operation's media types: - JSON bodies, including other JSON media types such as `application/merge-patch+json`, which the server parses before oRPC, and JSON Lines, which the procedure receives as an array; - `application/x-www-form-urlencoded` and `multipart/form-data` bodies, whose fields are converted to the types of their schemas (an empty field is `null` where the schema allows it) and whose binary parts are `File`s; - `text/plain` bodies as strings, other text and binary bodies as `File`s. A procedure returns the body of its response. When an operation has success responses with different bodies, or response headers, it returns `{ status, headers, body }` objects instead. JSON bodies are objects; other bodies (text, files) are `Blob`s, which the server sends with their media type. A `text/event-stream` response is an `eventIterator()` of its `itemSchema` (the `contentSchema` of the events' `data`, or the item of the operation's JSON Lines response); when the operation also answers JSON, the handler returns either a value or an async iterator, as the client accepts. The `writeOnly` properties of a response are left out of what the server sends, and the `readOnly` properties of a request out of what the handler receives. A oneOf with a discriminator and a `defaultMapping` (`x-defaultMapping` in 3.0 and 3.1 documents) validates the option its property selects, or the default one; closed allOf compositions (`unevaluatedProperties: false`) reject properties none of their schemas declare. Each 4xx and 5xx response becomes an error of the procedure: `NOT_FOUND`, `CONFLICT` and the other codes of oRPC, or `HTTP_<status>` for other statuses. `4XX` and `5XX` ranges become the errors of their first status (`BAD_REQUEST`, `INTERNAL_SERVER_ERROR`), and a `default` response next to success responses `INTERNAL_SERVER_ERROR`, unless the document declares those statuses. Their response bodies are their `data`, which the server sends as the body of the response: ```ts throw errors.NOT_FOUND({ data: { code: 404, message: "No such pet" } }); ``` Not supported, and reported as warnings: path parameters in other styles than `simple`, object query parameters in the `form` style (read in the `deepObject` style), and OPTIONS and CONNECT operations, which are skipped. The CORS plugin answers every OPTIONS request with 204 before routing, and Node.js doesn't pass CONNECT requests to the server's handler. Since 0.12.0, operations with methods other than GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS and CONNECT are also routed. Examples are QUERY and an `additionalOperations` COPY. oRPC routes any method, but the method type of its routes lists only the first six, and QUERY in oRPC 2. The contract declares the other methods with a cast: `method: "COPY" as HTTPMethod` in oRPC 1, `method: "COPY" as NonNullable<OpenAPIMeta["method"]>` in oRPC 2. The CORS plugin adds them to the methods it allows in its answer to a preflight. Node.js parses only the methods in `http.METHODS`, which include COPY, the other WebDAV methods and, in recent versions, QUERY. It answers a request with any other method with `400 Bad Request` before oRPC sees it. oRPC's `/spec.json` is an OpenAPI 3.1.1 document, which has no other methods: it lists these operations under keys such as `copy` and `query`, which 3.1 validators reject. oRPC streams async iterators as server-sent events only, so a JSON Lines response is answered as a `Blob` the handler builds. ### Webhooks and callbacks Since 0.12.0, the requests your application sends are generated too. They are the webhooks of the document (`x-webhooks` in OpenAPI 3.0 documents) and the callbacks of its operations. `src/senders.ts` then has `createWebhooks(options)`, `createCallbacks(options)` or both, whose senders send each request with `fetch`: ```ts // src/handlers/shipments.ts import { os } from "../orpc.js"; import type { ShipmentStatusChangedEvent } from "../schemas.js"; import { createCallbacks, createWebhooks } from "../senders.js"; const webhooks = createWebhooks({ headers: { "User-Agent": "carpet-express" } }); export async function notify(url: string, event: ShipmentStatusChangedEvent) { await webhooks.onShipmentStatusChanged(url, { headers: { "CarpetExpress-Signature": sign(event) }, body: event, }); } const callbacks = createCallbacks(); export const createShipment = os.shipments.createShipment.handler(async ({ input }) => { const shipment = await db.shipments.create(input.body); queue.onStatusChange(shipment, async (event) => { const response = await callbacks.createShipment.statusChanged( { request: input }, { headers: { "CarpetExpress-Signature": sign(event) }, body: event }, ); if (response.status === 410) { queue.stop(shipment); } }); return { status: 201, headers: { etag: etag(shipment) }, body: shipment }; }); ``` A webhook sender is named like a procedure, from the sources `action_naming` lists, or else after its method and name, and takes the subscriber's URL. A callback sender is grouped under the procedure that declares the callback. It is named after the callback, followed by the method when the callback has several requests. A sender's request and response are typed in `src/schemas.ts` as `<Name>Request` and `<Name>Response`. `<Name>` is the name of a webhook sender in PascalCase. For a callback, it is the name of the callback component it refers to when no other callback refers to it (`ShipmentStatusCallbackRequest`). Otherwise it is the procedure name and the callback name (`CreateWebhookSubscriptionVerificationRequest`). The method follows when the callback has several requests. A request has the `query`, `headers` and `cookies` parameters by name, the `body`, and the `contentType` of the body, the first declared media type by default. A callback sender takes a `source`, against which the runtime expressions of the callback's URL, such as `{$request.body#/callbackUrl}`, are resolved. Its `request` is the procedure's input as `{ params, query, headers, body }`. A compact input merges the path parameters with the body or the query. Pass it as `body` for `$request.body` expressions. Pass the parameters that `$request.path` and `$request.query` expressions read as `params` and `query`. Its optional `response` is the output as `{ status, headers, body }`, with a compact output as `body`. `source.request` is typed as the input the handler receives. `source.response` is typed as the value the handler returns, before the output schema parses it, so the schema's defaults aren't applied: a `$response.body` expression that reads a field the handler leaves out resolves to nothing. The optional `url`, `method` and `headers` of `source` are those of the HTTP request, for `$url`, `$method` and the headers the input doesn't hold. The generated context has the headers (`context.headers`); `$url` and `$method` need the URL and method added to `Context` in `src/orpc.ts`. A sender validates the parameters and a JSON, form or text body with the Zod schemas of `OUTGOING_SCHEMAS` (`src/schemas.ts`). It also rejects a `contentType` the operation doesn't declare. On a failed check it rejects with an `InvalidRequestError` instead of sending the request. It resolves with the response, typed per declared status as `{ status, body, headers, contentType }`, and checks a JSON or text body against its Zod schema. How it serializes the request, resolves the URL, decodes the response and rejects with an `UnexpectedResponseError` is described for the [Express server's senders](/docs/reference/generator/server-express#webhooks-and-callbacks): both use `src/outgoing.ts`. The options of `createWebhooks` and `createCallbacks`: | Option | Description | | --- | --- | | `fetch` | The function sending the requests; `globalThis.fetch` by default | | `validation` | Checks the requests and responses; `outgoingValidation`, with the Zod schemas, by default | | `headers` | Headers of every request, e.g. a `User-Agent` | | `onRequest(request, operation)` | Called with each `Request` before it's sent, e.g. to sign it; returns the request to send | Each sender also takes the `headers` and the `signal` of one request as its last argument. `OUTGOING_OPERATIONS` in `src/senders.ts` describes the webhooks and callbacks; `onRequest` receives its entry as `operation`. The path of a webhook is its name, and that of a callback its URL expression. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | name of the schema and type of a component schema (`AnimalSchema`, `Animal`) | | `x-apigenie.codegen.action-name` | name of the procedure of an operation, or of the sender of a webhook, when `action_naming` lists `extension` | | `x-webhooks` | `webhooks` of an OpenAPI 3.0 document: the requests the senders of `src/senders.ts` send | The extensions can live in an overlay for this target instead of in the document, e.g. `orpc.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: TypeScript names version: 1.0.0 actions: - target: $.components.schemas.Pet update: x-apigenie: codegen: name: Animal ``` ```sh apigenie-generator server orpc openapi.yaml --overlay orpc.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_orpc.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the package is generated. ### --package-name Name of the package, `<title>-server` by default. ### --package-version Version of the package, the version of the API by default. ## Configuration ```yaml version: '1.0' commands: generate: server_orpc: orpc_version: 1 input_structure: auto ``` | Option | Description | | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | `orpc_version` | `1` (default) for oRPC 1, `2` for oRPC 2 (beta): routes declared with `oc.meta(openapi(...))` and `queryStyles` | | `input_structure` | `auto` (default), `compact` (header parameters, and query parameters of other methods than GET, are dropped) or `detailed` | | `layout` | `package` (default) for an npm package, `sources` for the sources only | | `import_extension` | extension of relative imports: `.js` (default, Node.js) or `""` (bundlers) | | `action_naming` | sources of procedure and webhook sender names, in order: `id` (operationId), `extension` (`x-apigenie`), `url`; `[id, url]` by default | | `additional_properties` | `loose` (default) keeps the properties of objects their schemas don't list, `strip` removes them | | `describe` | `true` attaches the descriptions of schemas with `.describe()` (default: `false`) | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 38 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, oRPC 1) | ✓ 72 of 77 operations pass (node) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 38 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator server phoenix Source: https://apigenie.pl/docs/reference/generator/server-phoenix Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a [Phoenix](https://www.phoenixframework.org) 1.7 application from an OpenAPI document. From an AsyncAPI document, the command generates Phoenix channels and Kafka pipelines instead; see [`apigenie-generator server phoenix` (AsyncAPI)](/docs/reference/generator/server-phoenix-asyncapi). ## Usage ```sh apigenie-generator server phoenix [...OPTIONS] INPUT_FILE ``` ## Description The generator writes a Mix project (Elixir 1.18 or later) depending on Phoenix 1.7, Bandit and Jason, without Ecto, HTML, assets or a mailer. Since 0.12.0, a project that sends webhooks or callbacks depends on Req too. Its code passes `mix format --check-formatted`, `mix compile --warnings-as-errors` and `mix credo --strict`, and `mix phx.server` serves it. The input must be an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)). | File | Contents | | ---- | -------- | | `lib/<app>_web/router.ex` | the routes of the operations, under the path of the first server | | `lib/<app>_web/api/<tag>.ex` | a behaviour per tag (`Default` for operations without tags), with a callback per operation | | `lib/<app>_web/controllers/<tag>_controller.ex` | an action per operation, calling the implementation of the behaviour | | `lib/<app>/models/*.ex` | a module per schema: structs, enums, unions and aliases, with `new/1`, `new!/1` and `to_map/1` | | `lib/<app>_web/runtime/*.ex` | the checks of credentials, the decoding of parameters and bodies, the encoding of responses | | `lib/<app>_web/authenticator.ex` | the behaviour checking credentials | | `lib/<app>/senders.ex`, `lib/<app>/runtime/*.ex` | since 0.12.0, a function per webhook and per request of a callback, sending it with Req (only when the document has some) | | `lib/<app>_web/endpoint.ex`, `error_json.ex`, `lib/<app>/application.ex` | the endpoint, the errors Phoenix renders, the application | | `config/*.exs`, `mix.exs`, `.formatter.exs`, `.credo.exs`, `.gitignore`, `README.md` | the project | ```sh mix deps.get PORT=8080 mix phx.server ``` ### Routes Every operation has a route in `<App>Web.Router`, in the scope of the path of the first server (`/v2` for `https://api.example.com/v2`, or the `base_path` option). Methods without a Phoenix macro, such as `QUERY` and the `COPY` of `additionalOperations`, are routed with `match`. Static segments come before parameters (`/shipments/search` before `/shipments/{shipmentId}`), as Phoenix tries the routes in order. A segment holding parameters is captured whole and split by the runtime with its template, so `/labels/{labelId}.{extension}` works. ### Behaviours and implementations The operations of each tag are the callbacks of a behaviour, `<App>Web.Api.<Tag>`. A callback receives the connection, the parameters and the body: ```elixir defmodule MyApp.Shipments do @behaviour CarpetExpressWeb.Api.Shipments @impl true def get_shipment(_conn, %{shipment_id: id}, nil) do case MyApp.Store.fetch(id) do {:ok, shipment} -> {200, shipment} :error -> {404, %{"type" => "about:blank", "title" => "Not Found", "status" => 404}} end end end ``` and is configured as the implementation: ```elixir config :carpet_express, CarpetExpressWeb.Api.Shipments, impl: MyApp.Shipments ``` Operations without an implementation answer 501 Not Implemented. A callback returns `{status, body}`, `{status, body, headers}`, or the connection after sending a response itself (e.g. a chunked stream). The body is encoded in the media type the document gives the status (the exact code, then its range, then `default`): JSON with the type of the response, so a model struct or a plain map; text and bytes as they are; nothing for responses without content. Since 0.12.0, when a status has several media types, the first one in the document's order that the `Accept` header accepts (exactly, as `type/*` or as `*/*`) is sent, ignoring q-values. Without a match, or without an `Accept` header, the first media type is sent. Since 0.12.0, the body of a `text/event-stream`, JSON Lines (`application/jsonl`, `application/x-jsonlines`, `application/x-ndjson`, `application/ndjson`) or `application/json-seq` response is an enumerable of items. Each item is encoded with the `itemSchema` of the media type (OpenAPI 3.2), or as a plain JSON value without one, and sent as a chunk as it is enumerated. A `Stream` thus sends events as they happen, and a binary is sent as it is. The items of an event stream are maps with the string keys `"data"`, `"event"`, `"id"` and `"retry"`, or model structs of an `itemSchema` with only those properties. Any other value, including a struct with other properties, is sent as the event's data. Streamed bodies get `cache-control: no-cache`. ### Parameters and bodies The actions check the request before calling the implementation, and answer a problem document (RFC 9457, `application/problem+json`) when it doesn't match the description: - 401 when the request has none of the credentials of the operation's security requirements; - 400 when a parameter is missing or invalid (the `errors` list the parameters), or the body is missing, isn't JSON or doesn't match its schema; - 415 for a media type the operation doesn't accept. Parameters are decoded from their styles into a map with atom keys (`%{shipment_id: "...", limit: 20}`): `simple`, `label` and `matrix` path parameters, `form`, `spaceDelimited`, `pipeDelimited` and `deepObject` query parameters, headers, cookies, and parameters described with `content` as JSON. Integers, numbers and booleans are converted from text, models and enums decoded with their schemas. | Media type | Body | | ---------- | ---- | | JSON (`application/json`, `*+json`) | the model, a list or the value its schema describes | | `application/x-www-form-urlencoded` | the map of the fields | | `multipart/form-data` | the map of the parts, files as `Plug.Upload` structs | | `text/event-stream`, JSON Lines, `application/json-seq` | since 0.12.0, the list of the items, read whole (up to 20 MB) and decoded with the `itemSchema` | | `text/*` | a string | | anything else | the bytes | `Plug.Parsers` reads JSON, form and multipart bodies of up to 20 MB; the runtime parses the JSON and form bodies of methods Plug.Parsers leaves alone, such as `QUERY`. ### Security The first security requirement of an operation whose credentials the request presents is checked: API keys in headers, the query or cookies, HTTP bearer and basic, and OAuth2 and OpenID Connect tokens as bearer tokens. Without an implementation of `<App>Web.Authenticator`, every presented credential is accepted; with one, ```elixir config :carpet_express, CarpetExpressWeb.Authenticator, impl: MyApp.Authenticator ``` its `authenticate(conn, scheme, credential, scopes)` returns `{:ok, principal}`, assigned to the connection as `:principal`, or `{:error, reason}`, answered with 401. Since 0.12.0, the credential of a `mutualTLS` scheme is the peer data of a connection with a client certificate (`Plug.Conn.get_peer_data/1`, the certificate in `:ssl_cert`). Without an `Authenticator`, any certificate the CA certificates verify is accepted. When the document has such a scheme (OpenAPI 3.1 and later), setting `TLS_CERTFILE` and `TLS_KEYFILE` also serves the API over https, on port 4443 (`HTTPS_PORT`). `TLS_CERTFILE` alone stops the application at boot. With `TLS_CACERTFILE`, the server asks for client certificates without requiring them, and verifies them against its CA certificates. A certificate of another CA fails the handshake. A connection without a certificate is accepted, and only the `mutualTLS` operations answer 401 on it. Without `TLS_CACERTFILE`, no certificate is requested, and the `mutualTLS` operations answer 401. To serve https and verify client certificates: ```sh TLS_CERTFILE=server.pem TLS_KEYFILE=server-key.pem TLS_CACERTFILE=clients-ca.pem mix phx.server ``` ### Webhooks and callbacks Since 0.12.0, `<App>.Senders` has a function per webhook of the document and per request of a callback of a served operation. A webhook's function is named after its `operationId`, or its name and method without one. A callback's is named after the operation and the callback, and the method when the callback has several requests. A function takes the URL to send to, the body when the request has one, the parameters and the options: ```elixir event = CarpetExpress.Models.ShipmentDeliveredEvent.new!(event_fields) {:ok, response} = CarpetExpress.Senders.on_shipment_delivered( subscription.url, event, [carpet_express_signature: signature], req_options: [retry: :transient] ) ``` The parameters and the body are encoded as for the requests of [the Elixir client](/docs/reference/generator/client-elixir#parameters-and-bodies). The models are encoded as the API returns them, without their `writeOnly` properties. Missing or unknown parameters give `{:error, %ArgumentError{}}` before anything is sent, and a failed request gives `{:error, exception}` from Req. Any status gives `{:ok, %Req.Response{}}`, its body decoded by Req (JSON into plain maps, not models); pass `req_options: [decode_body: false]` for the raw body. The options are `:content_type`, `:headers` and `:req_options`. ### Types The models are the modules of [the Elixir models](/docs/reference/generator/client-elixir#types), shared with `client elixir`: a struct per object (with `allOf` flattened), atoms for string enums, a module dispatching on the discriminator for `oneOf` and `anyOf`, `Date`, `DateTime`, `NaiveDateTime` and `Time` for dates and times, binaries for `format: byte` (decoded from base64) and `format: binary`, `additional_properties` maps, and `| nil` for nullable values. Since 0.12.0, the models check the constraints of the schemas, `prefixItems`, `patternProperties` and the conditions between properties as [the client's](/docs/reference/generator/client-elixir#types) do, within [its limitations](/docs/reference/generator/client-elixir#limitations). `writeOnly` properties are left out of responses and `readOnly` properties ignored in requests. ### Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | name of the module of a component schema, unless `module_overrides` names it | | `x-apigenie.codegen.action-name` | name of the action and callback of an operation without an `operationId` (with the default `action_naming`, which lists `id` first) | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out | | `x-internal` | `true` on an operation or its path item leaves the operation out, unless `internal_operations` is set | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the schema of the values whose discriminator value isn't mapped | The extensions can live in an overlay for this target instead of in the document, e.g. `phoenix.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Elixir names version: 1.0.0 actions: - target: $.components.schemas.Pet update: x-apigenie: codegen: name: Animal - target: $.paths['/admin'] update: x-internal: true ``` ```sh apigenie-generator server phoenix openapi.yaml --overlay phoenix.overlay.yaml -o out ``` ### Limitations - Every operation is served under the base path; operation and path servers are ignored. - Links aren't generated. - Webhooks and callbacks are sent without their security requirements; pass credentials in `:headers`. - The bodies of webhooks and callbacks aren't checked against their schemas before they are sent. ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_phoenix.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the project is generated. ### --package-name Name of the Mix application, converted to snake_case (`carpet-express` gives `carpet_express`, the root module `CarpetExpress` and the web modules `CarpetExpressWeb`). Defaults to the name of the output directory. ### --package-version Version of the Mix project; `0.1.0` by default. ### -p, --property NAME=VALUE Sets a generator option (see below), e.g. `-p base_path=/api`. Options given on the command line take precedence over the configuration file. Lists are comma-separated (`-p include_tags=pets,store`) and mappings too (`-p module_overrides=pet-owner=Owner`). ## Configuration ```yaml version: '1.0' commands: generate: server_phoenix: app: carpet_express base_path: /v2 exclude_tags: [internal] ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `app` | string | name of the output directory | Name of the Mix application (snake_case, the directory under `lib/`); also set by `--package-name`. | | `namespace` | string | the application in PascalCase | Root module of the generated modules, e.g. `CarpetExpress`; the web modules are in `CarpetExpressWeb`. | | `base_path` | string | the path of the first server | Path the routes are mounted at, e.g. `/v2`; `/` mounts them at the root. | | `include_tags` | list of strings | | Generates only the operations with one of these tags. | | `exclude_tags` | list of strings | | Skips the operations with one of these tags. | | `skip_prune` | boolean | `false` | Keeps the component schemas that no generated operation uses. | | `internal_operations` | boolean | `false` | Also generates the operations marked `x-internal: true`. | | `dev_deps` | boolean | `true` | Lists credo as a dependency of `mix.exs` (`only: [:dev, :test]`). | | `action_naming` | list of `id`, `extension`, `url` | `id, extension, url` | Where the names of actions and callbacks come from, in order of preference. | | `field_prefix` | string | `field_` | Prefix of struct fields whose property names give no valid name. | | `module_overrides` | map of strings | | Module names of component schemas, e.g. `pet-owner: Owner`. | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 38 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 70 of 77 operations pass, 2 known failures (elixir) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 38 supported, 0 not yet | runs before a release | runs before a release, 2 known failures | --- # apigenie-generator server spring Source: https://apigenie.pl/docs/reference/generator/server-spring Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 1](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Spring Boot server, or Spring Cloud / HTTP interface clients, in Java. From an AsyncAPI document, the command generates a Spring Boot Kafka application instead; see [`apigenie-generator server spring` (AsyncAPI)](/docs/reference/generator/server-spring-asyncapi). ## Usage ```sh apigenie-generator server spring [...OPTIONS] INPUT_FILE ``` ## Description The generator produces the same code as the `spring` generator of [openapi-generator](https://openapi-generator.tech), and accepts the same options. A project generated by openapi-generator can be regenerated by API Genie, and vice versa. The input is an OpenAPI 3.0, 3.1 or 3.2 document or, since 0.12.0, a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)). Bundle a document that references other files with `apigenie bundle` first. It supports three libraries: - `spring-boot` (default): a Spring Boot application, with API interfaces (`PetApi`), controllers implementing them (`PetApiController`), optional delegates (`PetApiDelegate`), models, SpringDoc configuration and a Maven `pom.xml` - `spring-cloud`: Feign clients (`PetApiClient`) and their security configuration - `spring-http-interface`: `@HttpExchange` interfaces and a configurator creating their proxies The `spring-cloud` and `spring-http-interface` clients are generated by the writers of [`apigenie-generator client java`](/docs/reference/generator/client-java) (its `feign` and `http-interface` libraries), which also generates standalone clients on Spring's `RestClient` and `RestTemplate`. The generated project contains: - `pom.xml` and `README.md` - the application class, `RFC3339DateFormat`, `application.properties` and a copy of the OpenAPI document in `src/main/resources/openapi.yaml` (servers) - API interfaces, grouped by the first segment of their paths or, with `useTags`, by tags - models: classes with fluent setters, `equals`, `hashCode` and `toString`, enums, interfaces for `oneOf` schemas, and class hierarchies for `allOf` schemas with discriminators - `.openapi-generator/FILES` (the list of generated files) and `.openapi-generator/VERSION` Controllers (`*ApiController.java`) and `.openapi-generator-ignore` are generated only if they don't exist, so they can be implemented and edited. `.openapi-generator/FILES` lists the controllers in both cases, so generating again doesn't change it (since 0.12.0). Files listed in `.openapi-generator-ignore` (which uses the syntax of `.gitignore`) are not written. The vendor extensions the generator reads are listed in "Extensions". Differences from openapi-generator: - `useSpringBoot3` is `true` by default - generated files are marked with `@Generated(value = "API Genie")` - `@Generated` has no `date` unless `hideGenerationTimestamp` is `false` (since 0.12.0) - unknown options are errors, not ignored - since 0.12.0, Swagger 2.0 polymorphism becomes an interface that its shapes implement, with `@JsonSubTypes` for their `x-discriminator-value`, where openapi-generator writes a parent class that they extend - schemas whose names give the same class name (e.g. `app-permissions` and an inline `app_permissions`) get classes with numeric suffixes, e.g. `AppPermissions1` Since 0.12.0, the generator also covers: - callbacks, as `@Callback` annotations on the operations that register them, and webhooks, as an `ApiWebhooks` interface annotated with `@Webhooks` (both need `annotationLibrary: swagger2`, the default with SpringDoc; `apiFirst` leaves out `ApiWebhooks`). They document the requests the server sends. The generator writes no code that sends them. The SpringDoc versions in the generated `pom.xml` (2.6.0, or 1.6.14 for Spring Boot 2) don't read `@Webhooks` - `deepObject` query parameters of objects and maps, read by a generated argument resolver (`@DeepObjectParameter`) that answers 400 when a value doesn't convert to the type of its property or two keys conflict, and with `useBeanValidation` when the object isn't valid; keys the model doesn't have are ignored - streaming responses (`text/event-stream`, JSON Lines, JSON sequences) of arrays, returned as a `Flux` of their items; Spring MVC writes server-sent events and `application/x-ndjson` item by item, and `application/jsonl`, `application/x-jsonlines` and `application/json-seq` once the `Flux` completes - strings with a non-JSON `contentMediaType` and no `contentEncoding` as files and binary bodies, as with `format: binary` (`contentMediaTypeAsBinary`, on by default) - the flows of OAuth 2 schemes and `mutualTLS` schemes in the SpringDoc configuration - `writeOnly` properties, documented with `Schema.AccessMode.WRITE_ONLY` - tuples, `patternProperties`, `multipleOf` (a generated `MultipleOf` constraint) and conditional schemas (`@AssertTrue` methods), modelled as in [`apigenie-generator client java`](/docs/reference/generator/client-java); the `MultipleOf` constraint and the `@AssertTrue` methods need `useBeanValidation` Limitations: - `deepObject` parameters of other types are read as plain query parameters. - Streaming responses whose `schema` isn't an array are returned as plain bodies. A response whose first media type has only an `itemSchema` gets no body (a `Void` return type). - Server-sent events carry each item as their `data`, without `event` or `id`. - With `reactive`, WebFlux writes server-sent events and `application/x-ndjson`; the generator adds no encoder of `application/jsonl`, `application/x-jsonlines` or `application/json-seq`. - A JSON Lines or JSON sequence request body with an array `schema` is a `List` that no generated converter reads. With only an `itemSchema`, the method takes the type of the body's first media type, and has no body parameter when that media type has no `schema` either. - Strings with a `contentEncoding` stay `String`. - The SpringDoc configuration leaves out the device authorization flow of OAuth 2 schemes, which the swagger-core models it builds have no field for. ## Extensions | Extension | Effect | | --------- | ------ | | `x-class-extra-annotation` | annotations of the class of a schema, e.g. `['@Entity']` | | `x-implements` | interfaces the class of a schema implements | | `x-field-extra-annotation` | annotations of the field of a property, or of the method parameter of a parameter | | `x-extra-annotation` | annotations of the getter of a property | | `x-setter-extra-annotation` | annotations of the setter of a property | | `x-pattern-message`, `x-size-message`, `x-minimum-message`, `x-maximum-message` | `message` of the `@Pattern`, `@Size`, `@Min`/`@DecimalMin` and `@Max`/`@DecimalMax` annotations of a property or a parameter, on its schema, and since 0.12.0 on the parameter itself, as in Swagger 2.0 documents | | `x-jackson-json-include-policy` | `@JsonInclude` policy of a property, e.g. `non_empty` (`none` for no annotation) | | `x-jackson-json-setter-nulls` | `@JsonSetter(nulls = ...)` of a property, e.g. `skip` (`none` for no annotation) | | `x-enum-varnames` | names of the constants of an enum | | `x-enum-descriptions` | Javadoc of the constants of an enum | | `x-parent` | `true` makes a schema the superclass of the schemas extending it with `allOf`, without a discriminator | | `x-discriminator-value` | the discriminator value of a subclass in `@JsonSubTypes` (default: the name of its schema) | | `x-jackson-default-impl` | `defaultImpl` of the `@JsonTypeInfo` of a class with a discriminator | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents: the `defaultImpl` of `@JsonTypeInfo`, without `x-jackson-default-impl` | | `x-codegen-request-body-name` | on an operation or its request body: the name of the body parameter | | `x-apigenie.codegen.controller-name` | on an operation: the API class of the operation, instead of its tag or path | | `x-apigenie.codegen.action-name` | name of the method of an operation, instead of its `operationId` | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out, with `skipDisabled` | | `x-internal` | `true` on an operation leaves it out | | `x-operation-extra-annotation` | annotations of the method of an operation (not with `spring-http-interface`) | | `x-version-param` | `true` on a header or query parameter adds it to the `headers` or `params` of the `@RequestMapping` (not with `spring-http-interface`) | | `x-spring-paginated` | `true` replaces the `page`, `size` and `sort` parameters of an operation with a `Pageable`; `false` keeps them even with `autoXSpringPaginated` | | `x-spring-provide-args` | further arguments of the method of an operation, e.g. `['@RequestAttribute("tenant") String tenant']` (not with `spring-http-interface`) | The extensions can live in an overlay for this target instead of in the document, e.g. `spring.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Spring annotations version: 1.0.0 actions: - target: $.paths['/pets'].get update: x-spring-paginated: true - target: $.components.schemas.Pet update: x-class-extra-annotation: ['@com.acme.Audited'] ``` ```sh apigenie-generator server spring openapi.yaml --overlay spring.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_spring.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the project is generated. ### --package-name Base package of the generated code, e.g. `com.example`. API, model and configuration classes are generated in its `api`, `model` and `configuration` sub-packages, unless `apiPackage`, `modelPackage` or `configPackage` are set. ### --package-version Version of the generated project (`artifactVersion`). Defaults to the version of the API. ### -p, --property NAME=VALUE Sets a generator option (see below), e.g. `-p delegatePattern=true`. Options given on the command line take precedence over the configuration file. Mapping options take comma-separated lists, e.g. `-p typeMappings=DateTime=java.time.Instant,UUID=String`. Applies to OpenAPI documents only; using it with an AsyncAPI document is an error. ## Configuration Options can also be set in the configuration file, either directly or in an `additionalProperties` section, like in configuration files of openapi-generator. The `asyncapi` key holds the options of the generation from AsyncAPI documents (see [`apigenie-generator server spring` (AsyncAPI)](/docs/reference/generator/server-spring-asyncapi#configuration)): ```yaml version: '1.0' commands: generate: server_spring: basePackage: com.example delegatePattern: true typeMappings: DateTime: java.time.Instant ``` | Option | Description | | ------ | ----------- | | `library` | Library template: spring-boot (server), spring-cloud (Feign client) or spring-http-interface (HTTP interface client) | | `basePackage` | Base package for generated code | | `invokerPackage` | Alias of basePackage | | `apiPackage` | Package for generated API classes | | `modelPackage` | Package for generated models | | `configPackage` | Package for generated configuration classes | | `groupId` | groupId in the generated pom.xml | | `artifactId` | artifactId in the generated pom.xml | | `artifactVersion` | Artifact version in the generated pom.xml | | `artifactDescription` | Artifact description in the generated pom.xml | | `artifactUrl` | Artifact URL in the generated pom.xml | | `licenseName` | License name in the generated pom.xml | | `licenseUrl` | License URL in the generated pom.xml | | `developerName` | Developer name in the generated pom.xml | | `developerEmail` | Developer email in the generated pom.xml | | `developerOrganization` | Developer organization in the generated pom.xml | | `developerOrganizationUrl` | Developer organization URL in the generated pom.xml | | `scmConnection` | SCM connection in the generated pom.xml | | `scmDeveloperConnection` | SCM developer connection in the generated pom.xml | | `scmUrl` | SCM URL in the generated pom.xml | | `parentGroupId` | groupId of the parent pom | | `parentArtifactId` | artifactId of the parent pom | | `parentVersion` | Version of the parent pom | | `snapshotVersion` | Append -SNAPSHOT to the artifact version | | `title` | Server title, used in property names (defaults to info.title) | | `serverPort` | Server port (defaults to the port of the first server, or 8080) | | `useSpringBoot3` | Generate code for Spring Boot 3 (jakarta); false means Spring Boot 2 | | `useSpringBoot4` | Generate code for Spring Boot 4 | | `useJackson3` | Use Jackson 3 (tools.jackson) instead of Jackson 2; requires useSpringBoot4 | | `optionalAcceptNullable` | Use Optional.ofNullable in fluent setters of Optional properties | | `useJspecify` | Use JSpecify (org.jspecify.annotations.Nullable) for null checks | | `hideGenerationTimestamp` | Omit the generation date from @Generated annotations (default: `true` since 0.12.0, `false` before) | | `generationTimestamp` | Timestamp used in @Generated annotations when hideGenerationTimestamp is false | | `generatorVersion` | Generator version written into generated files | | `dateLibrary` | Date library: java8, java8-localdatetime, joda or legacy | | `documentationProvider` | springdoc, source or none | | `annotationLibrary` | swagger2 or none | | `useSwaggerUI` | Serve Swagger UI | | `interfaceOnly` | Generate only API interfaces, without controllers | | `delegatePattern` | Delegate request handling to XxxApiDelegate interfaces | | `skipDefaultInterface` | Don't generate default implementations of API methods | | `useTags` | Group operations by tag instead of the first path segment | | `requestMappingMode` | Where to put the class-level @RequestMapping: controller, api_interface or none | | `useResponseEntity` | Wrap return types in ResponseEntity | | `useOptional` | Use Optional for optional parameters | | `useSpringController` | Annotate API interfaces with @Controller / @RestController | | `returnSuccessCode` | Return the success code instead of 501 Not Implemented | | `unhandledException` | Declare 'throws Exception' on API methods | | `apiFirst` | Generate supporting files only | | `async` | Return CompletableFuture from API methods | | `reactive` | Generate reactive (WebFlux) code | | `responseWrapper` | Wrapper of return types: CompletableFuture, Callable, Future, ListenableFuture, DeferredResult or a fully qualified class name | | `includeHttpRequestContext` | Add the HTTP request (ServerWebExchange / HttpServletRequest) to API methods | | `singleContentTypes` | Use a single content type per operation | | `sortParamsByRequiredFlag` | Put required parameters before optional ones | | `apiNameSuffix` | Suffix of API class names | | `skipDeprecated` | Don't generate code for deprecated operations | | `skipDisabled` | Don't generate code for operations disabled with x-apigenie | | `autoXSpringPaginated` | Add x-spring-paginated to operations with 'page', 'size' and 'sort' query parameters | | `substituteGenericPagedModel` | Replace schemas of pages of items (a 'content' array and pagination metadata) with PagedModel<T> | | `generateSortValidation` | Validate the sort of Pageable parameters against the enum values of 'sort' parameters | | `generatePageableConstraintValidation` | Validate Pageable parameters against the limits of 'page' and 'size' parameters | | `virtualService` | Generate Virtualan annotations for virtual services | | `useSpringSecurityPreAuthorize` | Generate @PreAuthorize annotations from OAuth2/OpenID Connect scopes | | `springSecurityAuthorityPrefix` | Prefix of the authorities checked by @PreAuthorize annotations | | `implicitHeaders` | Describe header parameters with @Parameters instead of method parameters | | `implicitHeadersRegex` | Regular expression of header parameters described with @Parameters | | `useHttpServiceProxyFactoryInterfacesConfigurator` | Use a HttpServiceProxyFactory in HttpInterfacesAbstractConfigurator (spring-http-interface) | | `clientRegistrationId` | @ClientRegistrationId of API interfaces (spring-http-interface, Spring Boot 4) | | `useFeignClientUrl` | Use the url attribute of @FeignClient (spring-cloud) | | `useFeignClientContextId` | Use the contextId attribute of @FeignClient (spring-cloud) | | `useBeanValidation` | Use Bean Validation annotations | | `performBeanValidation` | Use Hibernate Validator annotations | | `useSpringBuiltInValidation` | Rely on Spring's built-in validation (no @Validated) | | `additionalNotNullAnnotations` | Add @NotNull to required path and body parameters | | `openApiNullable` | Use JsonNullable for nullable properties | | `serializableModel` | Make models implement Serializable | | `useOneOfInterfaces` | Represent oneOf schemas as interfaces | | `useDeductionForOneOfInterfaces` | Deduce oneOf subtypes from their properties | | `generatedConstructorWithRequiredArgs` | Generate constructors with required arguments | | `generateConstructorWithAllArgs` | Generate constructors with all arguments | | `generateBuilders` | Generate builders for models | | `sortModelPropertiesByRequiredFlag` | Put required properties first in constructors | | `enumPropertyNaming` | Naming of enum constants: MACRO_CASE, original, legacy, camelCase, PascalCase, snake_case or UPPERCASE | | `useEnumCaseInsensitive` | Match enum values ignoring case | | `withXml` | Add XML annotations to models | | `useSealed` | Use sealed classes and interfaces (Java 17+) | | `containerDefaultToNull` | Initialize containers with null instead of empty ones | | `legacyDiscriminatorBehavior` | Use the legacy discriminator behavior | | `disableDiscriminatorJsonIgnoreProperties` | Don't ignore discriminator properties during serialization | | `modelNamePrefix` | Prefix of model names | | `camelCaseDollarSign` | Keep the case of the first letter after a leading $ in names | | `useEnumValueInterface` | Make enums implement the ValuedEnum interface | | `generateJsonIncludeAnnotations` | Add @JsonInclude annotations to model properties | | `optionalNonNullPropertyJsonInclude` | @JsonInclude policy of optional, non-nullable properties: NON_NULL, NON_EMPTY, NON_DEFAULT or NONE | | `generateJsonSetterNullsAnnotations` | Add @JsonSetter(nulls = ...) annotations to optional, non-nullable properties | | `optionalNonNullPropertyJsonSetterNulls` | @JsonSetter(nulls = ...) mode of optional, non-nullable properties: SKIP or FAIL | | `modelNameSuffix` | Suffix of model names | | `additionalModelTypeAnnotations` | Annotations added to model classes, separated by semicolons | | `additionalEnumTypeAnnotations` | Annotations added to enum classes, separated by semicolons | | `additionalOneOfTypeAnnotations` | Annotations added to oneOf interfaces, separated by semicolons | | `typeInfoDefaultImpls` | Classes used as defaultImpl of @JsonTypeInfo, by schema name (Schema=Class,...) | | `typeMappings` | Mappings of OpenAPI types to Java types (type=JavaType,...) | | `importMappings` | Mappings of Java types to imports (Type=package.Type,...) | | `schemaMappings` | Mappings of schemas to existing classes (Schema=package.Class,...) | | `modelNameMappings` | Mappings of schema names to model names (Schema=Model,...) | | `nameMappings` | Mappings of property names to Java names (name=javaName,...) | | `parameterNameMappings` | Mappings of parameter names to Java names (name=javaName,...) | | `enumNameMappings` | Mappings of enum values to constant names (value=NAME,...) | | `contentMediaTypeAsBinary` | Map strings with a non-JSON contentMediaType to binary types, like format: binary (on by default) | | `useImplicitOneOfDiscriminator` | Dispatch oneOf schemas without a discriminator on a property whose value is constant in every member | | `jsonAccessForReadWriteOnly` | Read readOnly properties from JSON only and write writeOnly ones only (@JsonProperty access) | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Tier 1](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, with the goal of supporting every feature of the fixture. Its unsupported features are worked on first. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 45 supported, 0 not yet, 1 not checked | ✓ pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | ✓ 70 of 77 operations pass, 2 known failures (java) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 45 supported, 0 not yet, 1 not checked | runs before a release | runs before a release, 2 known failures | --- # apigenie-generator server vapor Source: https://apigenie.pl/docs/reference/generator/server-vapor Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Experimental](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Swift server package for Vapor 4 from an OpenAPI document. > **(experimental, outside the 1.0 compatibility promise)** Levels 2 and 3 of the conformance suite > are wired for the generated packages but haven't passed a run yet, so their types and methods can > still change. `server vapor` says so in its `--help` and on the first line it prints, on the > standard error. See the [experimental commands](/docs/reference/cli#experimental-commands). ## Usage ```sh apigenie-generator server vapor [...OPTIONS] INPUT_FILE ``` ## Description The generator writes a Swift package with one library target, depending on Vapor. Its code is that of the [`server hummingbird`](/docs/reference/generator/server-hummingbird) packages except `Server/Vapor.swift`, the platform and the dependencies in `Package.swift`, and schemas named like a Vapor type (see [Limitations](#limitations)). Code written against one moves to the other by changing the few lines that start the server. | File | Contents | | ---- | -------- | | `Package.swift` | tools version 6.0, macOS 13, the Vapor 4 dependency and a library product of the module | | `.swift-format` | the swift-format settings the generated code follows (`swift format lint`) | | `Sources/<Module>/Server/APIHandler.swift` | the `APIHandler` protocol, with an async method per operation, and `UnimplementedHandler` | | `Sources/<Module>/Server/Requests.swift` | the request struct of each operation: its parameters, its body and the credentials it was sent with | | `Sources/<Module>/Server/Routes.swift` | `APIRoutes`: an `APIRoute` per operation, which reads the request, checks it and calls the handler | | `Sources/<Module>/Server/Senders.swift` | `WebhookSender` and `CallbackSender`, for documents with webhooks or callbacks | | `Sources/<Module>/Server/Vapor.swift` | `APIRoutes.register(on:handler:)`, which registers the routes with a Vapor application | | `Sources/<Module>/Operations.swift` | per operation, the enum of its responses, the structs of their headers and the enums of bodies of several media types | | `Sources/<Module>/Models.swift` | the types of the component schemas the operations use, and of their inline schemas | | `Sources/<Module>/Runtime/*.swift` | requests and responses of the routes, JSON coding, parameter styles, streams, multipart bodies, validation, `Nullable`, `CalendarDate`, `Indirect`, `JSONValue`, and the transport of the senders | The module is named after the document's title followed by `Server` (`Carpet Express Shipping API` gives `CarpetExpressShippingAPIServer`; `APIServer` when the title gives no name), unless `--package-name` or `package` names it. A server implements `APIHandler` and registers it: ```swift import CarpetExpress import Vapor struct Shipments: APIHandler { func getShipment(_ request: GetShipmentRequest) async throws -> GetShipmentResponse { guard let stored = try await store.shipment(request.shipmentID) else { return .notFound(Problem(type: "about:blank", title: "No such shipment", status: 404)) } return .ok(body: stored.shipment, headers: GetShipmentOkHeaders(eTag: stored.eTag)) } // ... a method per operation } let app = try await Application.make(.detect()) APIRoutes.register(on: app, handler: Shipments()) try await app.execute() ``` ### Handler `APIHandler` has a method per operation, named after its `operationId`, taking the operation's request struct and returning its response enum, the same enum the [Swift client](/docs/reference/generator/client-swift) returns: ```swift func createShipment(_ request: CreateShipmentRequest) async throws -> CreateShipmentResponse public enum CreateShipmentResponse: Sendable { /// `201`: Shipment booked. case created(body: Shipment, headers: CreateShipmentCreatedHeaders) /// `400`: The request could not be parsed. case badRequest(Problem) // ... 202, 401, 403, 409, 422, 429 /// `5XX`: A carrier or Carpet Express itself is unavailable. case serverError(statusCode: Int, body: Problem, headers: CreateShipmentServerErrorHeaders) } ``` - The request struct has a property per path, query, header and cookie parameter, `body` (an optional when the body is), and `credentials`, the credentials of the security requirement the request met, by scheme. - A case of the response enum is written with its status (the status code of ranges and `default`), its headers and its body, as JSON, text, bytes, a form, multipart parts or a stream of the media type the case holds. - A method that throws `HandlerError.problem(status:title:detail:)` answers that status with [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) problem details; `HandlerError.notImplemented` answers 501, and any other error 500. - `UnimplementedHandler` answers every operation with 501: a starting point, and a server for tests of the routes. - Deprecated operations say so in their documentation, but aren't `@available(*, deprecated)`: the routes call every method. ### Routes Before the handler runs, the route of an operation: 1. checks the security requirements: the request needs the credentials of one alternative, or it gets `401`; 2. reads the path, query, header and cookie parameters in their style and `explode` mode (`simple`, `label` and `matrix` path parameters, `form`, `spaceDelimited`, `pipeDelimited` and `deepObject` query parameters; JSON for parameters described with `content`), and checks them against their schemas; 3. reads the body by its `Content-Type`: JSON, `application/x-www-form-urlencoded`, `multipart/form-data`, JSON Lines and JSON text sequences, text and bytes, including media type ranges such as `image/*`. A body of another media type gets `415`, a missing required body `400`. A request that breaks the document gets `400` with problem details whose `errors` list the JSON pointers of the values that break it, also of a parameter that can't be read as its schema's type (`/query/limit` for `?limit=abc`); pretty-printed here, and the order of the keys varies: ```json { "type": "about:blank", "title": "Bad Request", "status": 400, "detail": "/path/shipmentId: must match the pattern ^shp_[0-9A-Za-z]{24}$", "errors": [ { "pointer": "/path/shipmentId", "detail": "must match the pattern ^shp_[0-9A-Za-z]{24}$" } ] } ``` The routes are registered below the path of the first server of the operation or its path item, else of the document's first server (`/v2/shipments` for `https://api.carpetexpress.example/v2`). `APIRoutes.all(_:)` returns them, and `APIRoutes.register(_:on:)` registers them with other prefixes: ```swift let routes = APIRoutes.all(Shipments()).map { route in var moved = route moved.prefix = "/api" return moved } APIRoutes.register(routes, on: app.grouped(APIKeyCheck())) ``` `register` takes any `RoutesBuilder`, so routes registered on a group run its middleware. Request bodies are collected before the routes read them, up to `maxBodySize` (10 MB by default); a larger body gets `413` from Vapor. ### Streams A response of `text/event-stream`, `application/jsonl` or `application/json-seq` holds an `AsyncThrowingStream` of its items, typed by the media type's `itemSchema` (OpenAPI 3.2; `x-itemSchema` in 3.0 and 3.1 documents), and the route writes each item as it comes: ```swift let events = AsyncThrowingStream<ServerSentEvent<TrackingEvent>, any Error> { continuation in // yield the events as they happen } return .ok(.eventStream(events)) ``` JSON Lines and JSON text sequence request bodies are arrays of their items. ### Multipart bodies `multipart/form-data` bodies of object schemas are structs with a property per part. Binary parts (`format: binary`, or `contentMediaType` in 3.1 and 3.2) are `MultipartFile` values (data, file name and media type), arrays of them `[MultipartFile]`. Object parts, and parts whose encoding has a JSON `contentType`, are read as JSON; other parts as text, a part per item of arrays. ### Security The route of an operation gives the request the credentials of the first alternative of its security requirements whose schemes all have some; checking them is up to the handler: | Scheme | Credential in `request.credentials` | | ------ | ----------------------------------- | | `apiKey` in a header, the query or a cookie | the key | | `http` `basic` | `username:password` | | `http` `bearer`, `oauth2`, `openIdConnect` | the bearer token | | `mutualTLS` | an empty string: the server doesn't check client certificates, so the TLS layer in front of it must require them (the generator warns) | An operation with `security: []` gets no credentials; an empty alternative lets requests without credentials through. ### Webhooks and callbacks `WebhookSender` has a method per webhook of the document and `CallbackSender` one per callback of the operations. A method is named after the request's `operationId`, else its `x-apigenie.codegen.action-name`, else the webhook, or the operation and the callback (`createShipmentStatusChanged`). Each takes the URL the receiver gave, the request's body and its parameters, and returns the request's response enum: ```swift let sender = WebhookSender() let response = try await sender.onShipmentStatusChanged( to: subscription.url, body: event, carpetExpressSignature: signature ) ``` The senders send through an `HTTPTransport`, `URLSessionTransport` by default, and check request bodies against their schemas (`validatesRequests`). The credentials of the security requirements of webhooks and callbacks are up to the transport. ## Stability Experimental, since 0.12.0. ## What you depend on - Swift 6.0 or later, in the Swift 6 language mode (strict concurrency). - Swift Package Manager (`swift build`), which reads `Package.swift` (tools version 6.0). - [Vapor](https://github.com/vapor/vapor) 4.99 or later. - macOS 13 or later, or Linux. ## Features | Feature | Support | | ------- | ------- | | Authentication schemes | partial: the credentials of API keys, HTTP basic and bearer, OAuth 2 and OpenID Connect tokens reach the handler, which checks them | | Streaming | yes: server-sent events, JSON Lines and JSON text sequences are written as the items come | | Pagination | no | | File upload | yes: multipart bodies and binary bodies | | Enums | yes; values the document doesn't list get `400` | | Discriminators | yes, with `mapping` and `defaultMapping` | | Nullable | yes: `Nullable<T>?` tells missing, null and set values apart | | Errors | yes: a case per documented status, RFC 9457 problem details for invalid requests | | Retries | no: the senders send each request once; an `HTTPTransport` of your own can retry | | Webhooks and callbacks | yes: typed senders | ## Type mapping The types are those of the [Swift client](/docs/reference/generator/client-swift#type-mapping), except enums, which have no `unknown` case: a server rejects values the document doesn't list. Bodies are checked against their schemas as they are decoded. ## Extensions | Extension | Effect | | --------- | ------ | | `x-swift-name` | name of the type of a schema, or of the property of a property | | `x-enum-varnames`, `x-enumNames` | names of the enum cases | | `x-enum-descriptions` | documentation of the enum cases | | `x-apigenie.codegen.name` | name of the type of a component schema, when it has no `x-swift-name` | | `x-apigenie.codegen.action-name` | name of the method of an operation without an `operationId` (with the default `action_naming`) | | `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out | | `x-internal` | `true` on an operation, a webhook or a callback (or its path item) leaves it out, unless `internal_operations` is set | | `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents | | `x-itemSchema` | `itemSchema` of a media type in OpenAPI 3.0 and 3.1 documents | ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_vapor.overlay` in the configuration file. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning. ### --no-config Doesn't look for `apigenie.yaml` (or `.apigenie.yaml`) in the current directory and its parents up to the root of the repository. ### --json Prints one JSON document on the standard output (`formatVersion`, `command`, `exitStatus`, `messages`) instead of the messages. ### -o, --output Directory where the package is generated. ### --package-name Name of the Swift module, its library product and the package. Defaults to the document's title followed by `Server`. ### --package-version Ignored: Swift packages take their versions from Git tags. ### -p, --property NAME=VALUE Sets a generator option (see below), e.g. `-p internal_operations=true`. Options given on the command line take precedence over the configuration file. Lists are comma-separated (`-p include_tags=shipments,rates`). ## Configuration ```yaml version: '1.0' commands: generate: server_vapor: package: CarpetExpress exclude_tags: [internal] ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `package` | string | the document's title followed by `Server` | Name of the module, its library product and the package; also set by `--package-name`. | | `include_tags` | list of strings | | Generates only the operations with one of these tags. | | `exclude_tags` | list of strings | | Skips the operations with one of these tags. | | `skip_prune` | boolean | `false` | Keeps the component schemas that no generated operation uses. | | `internal_operations` | boolean | `false` | Also generates the operations, webhooks and callbacks marked `x-internal: true`. | | `initialisms` | list of strings | | Words written in one case in identifiers, besides `ID`, `URL`, `HTTP`, `JSON` and the other common initialisms. | | `action_naming` | list of `id`, `extension`, `url` | `id, extension, url` | Where method names come from, in order of preference. | ## Exit status 0 when the package was generated; 2 when the options, the configuration, an overlay or the input document can't be used (with `--strict`, also when an overlay action selects nothing). See [`apigenie-generator`](/docs/reference/generator). ## Limitations - What the conformance fixture doesn't cover is listed under [Verification](#verification); links are out of scope there. - The routes don't check credentials, only that a request has them: the handler decides whether they are valid. HTTP schemes other than `basic` and `bearer` get a warning, and the operations requiring them answer `401`. - Requests are checked as the Swift client's `validate()` checks bodies: patterns Swift's `Regex` can't compile, `unevaluatedProperties` other than `false`, and formats other than `email`, `uri`, `uuid`, `date`, `date-time`, `ipv4` and `ipv6` aren't checked, and such values reach the handler. `if`/`then`/`else` and `dependentSchemas` are checked only when their schemas use `required` and the `const` and `enum` of properties. - `format: decimal` numbers are decoded by `JSONDecoder`, which reads them through `Double` on macOS before 15. - Response bodies aren't checked against their schemas. - A `oneOf` without a discriminator decodes as its first variant that decodes, even when another one matches too. - Types of the standard library, Foundation, the runtime, the server and the Vapor types the adapter uses (`Data`, `Error`, `APIHandler`, `APIRoutes`, `ServerRequest`, `Request`, `Response`, `RoutesBuilder`, ...) are reserved: schemas with these names get types with `Model` after their names, e.g. `ResponseModel`. - The input must be an OpenAPI 3.0, 3.1 or 3.2 document or a Swagger 2.0 document (see [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle documents referencing other files with `apigenie bundle`. ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi). This target's support tier is [Experimental](/docs/reference/generator/conformance#tiers). It isn't run at every level yet. It is outside the [1.0 compatibility promise](/docs/reference/cli/compatibility): its options and the shape of its output can change, or it can go away, in a minor release. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | ✓ pass (Swift version 6.0.3 (swift-6.0.3-RELEASE)) | ✓ 70 of 77 operations pass, 2 known failures (swift) | | Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet | runs before a release | runs before a release, 2 known failures | --- # apigenie-generator client csharp (AsyncAPI) Source: https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a C# Kafka client library for the Kafka channels of an AsyncAPI document. ## Usage ```sh apigenie-generator client csharp [...OPTIONS] INPUT_FILE ``` ## Description `apigenie-generator client csharp` generates from OpenAPI documents (see [`apigenie-generator client csharp`](/docs/reference/generator/client-csharp)) and from AsyncAPI 3.x documents. It tells them apart by their `openapi` or `asyncapi` field. Documents that reference other files are bundled first. From an AsyncAPI document it generates a .NET 8 class library (`Microsoft.NET.Sdk`) on the Kafka client [Confluent.Kafka](https://github.com/confluentinc/confluent-kafka-dotnet) (Apache-2.0, pinned at 2.15.1). It also references `Microsoft.Extensions.Hosting.Abstractions` and `Microsoft.Extensions.Options.ConfigurationExtensions`. By default the client implements the counterpart of the application the document describes: it sends the messages of the application's `receive` operations, and receives the messages of its `send` operations. Set the `perspective` option to `application` to generate the application's side instead. The two sides talk to each other, and to the application of [`apigenie-generator server aspnet` (AsyncAPI)](/docs/reference/generator/server-aspnet-asyncapi). The generator writes the Kafka channels: - the channels of servers with the `kafka` or `kafka-secure` protocol; - in documents without servers, the channels with a Kafka binding. Channels of other protocols are skipped and reported as info. ```csharp // the application's side of the Carpet Express Event Platform builder.Services.AddCarpetExpressKafkaClient(builder.Configuration); public sealed class Shipping(CarpetExpressKafkaClient kafka) { public async Task DeliveredAsync(ShipmentDelivered message, CancellationToken cancellationToken) { await kafka.ShipmentEvents.SendShipmentDeliveredAsync(message, cancellationToken); } public async Task<Uri?> LabelAsync(RenderLabel request, CancellationToken cancellationToken) { // sends the request with a new correlation id and waits for its reply var reply = await kafka.LabelRenderRequests.RequestRenderLabelAsync(request, TimeSpan.FromSeconds(10), cancellationToken); return reply is LabelRendered rendered ? rendered.Payload.Url : null; } } ``` The project's root namespace (and assembly name) is `root_namespace`, else `--package-name`, else the document's title in PascalCase followed by `.Client`. The class names start with the namespace's stem: its last segment, or the segment before a last `Client`, `Clients` or `Sdk`. For example, `CarpetExpress.Client` gives `CarpetExpressKafkaClient`. | File | Contents | | ---- | -------- | | `Models/*.cs`, `Serialization/*.cs`, `Messages/*.cs` | the payload types, the JSON context and the message records, as [`apigenie-generator server aspnet` (AsyncAPI)](/docs/reference/generator/server-aspnet-asyncapi) writes them | | `Kafka/<Name>KafkaClient.cs` | the client: a producer per channel it sends to | | `Kafka/<Channel>Producer.cs` | the `Send…Async` and `Request…Async` methods of a channel | | `Kafka/*Handler.cs`, `Kafka/*Consumer.cs` | the handler interfaces and consumers of the received operations | | `Kafka/<Name>KafkaClientOptions.cs` | the options, with the topics and ids | | `Kafka/<Name>KafkaClientServiceCollectionExtensions.cs`, `Kafka/<Name>KafkaClientBuilder.cs` | `Add<Name>KafkaClient` and the registration of handlers | | `Infrastructure/*.cs` | the Kafka runtime (producer, consumer service, reply consumer, headers) and the validation of messages | | `<RootNamespace>.csproj`, `README.md` | the project | - **Sent operations.** The client has a producer per channel, e.g. `client.ShipmentEvents`. A producer's `Send<Message>Async` validates a message and completes once the brokers have it. It writes the constant headers (e.g. `ce_type`), the key and the topic from the bindings. - **Request/reply.** A request/reply operation gets `Request<Message>Async(message, cancellationToken)` and an overload with a timeout. - It sends the request with its correlation id, or with a new Guid when the request has none. - It returns the reply: the reply message, or an interface of the replies (`IRequestLabelRenderReply`) when there are several. - It throws `TimeoutException` when no reply comes within the timeout (by default `ReplyTimeout`), and `OperationCanceledException` when the token is cancelled. One consumer per client reads the replies of every request. It has no consumer group, and starts with the first request reading from a minute before, so no reply is missed. - **Received operations.** They have handler interfaces and consumers, as in [`apigenie-generator server aspnet` (AsyncAPI)](/docs/reference/generator/server-aspnet-asyncapi): - the dispatch by a payload property or a header, with `OnUnknownAsync` for other records; - validation; - commits once the handler returns, and retries after `RetryDelay` when it throws; - replies sent with the request's correlation id. Register a handler with the builder: its consumer runs as a hosted service of the host. ```csharp // the counterpart's side: consume the shipment events and answer label requests builder.Services.AddCarpetExpressKafkaClient(builder.Configuration) .AddPublishShipmentEventsHandler<ShipmentEventsHandler>() .AddRequestLabelRenderHandler<LabelRenderer>(); ``` `Add<Name>KafkaClient(configuration, configure)` does the following: - binds the options to the `AsyncApi:Kafka` section of `configuration` when it is given, then applies `configure`; - registers the client and its producers as singletons; - returns the builder. Without dependency injection, `new CarpetExpressKafkaClient(options)` sends and requests; dispose it when done. ### Settings The options are those of [`apigenie-generator server aspnet` (AsyncAPI)](/docs/reference/generator/server-aspnet-asyncapi#settings): `BootstrapServers`, `ClientId`, `ReplyTimeout`, `RetryDelay`, `Topics`, `Operations` (the group and client ids of received operations), `Consumer` and `Producer`. A client that sends requests also has `ReplyClientId`, the client id of its reply consumer. It defaults to the client id of the first request/reply operation's Kafka binding. Without a value in the binding, the default is `<namespace stem in kebab case>-<operation>`. A client of a document with Avro messages also has the schema registry settings (`SchemaRegistryUrl`, `SchemaRegistryUsername`, `SchemaRegistryPassword`) and `SchemaRegistry`, an `ISchemaRegistry` that replaces the Confluent-compatible registry at `SchemaRegistryUrl`: ```csharp builder.Services.AddCarpetExpressKafkaClient(builder.Configuration, options => options.SchemaRegistry = new ConfluentSchemaRegistry(registryUrl, "ingest", registryPassword)); ``` Security and Avro payloads work as in [`apigenie-generator server aspnet` (AsyncAPI)](/docs/reference/generator/server-aspnet-asyncapi#security): `Security` names the security scheme every consumer and producer of the client connects with, and the payloads of Avro messages are classes of their record schemas. Not supported, and reported as warnings: - payloads of non-JSON schema formats other than Avro, and request/reply operations with Avro messages; - reply addresses given by runtime expressions; - Kafka topics with parameters. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.disabled` | `true` on a channel or an operation leaves it out (with the operations of a channel left out) | | `x-enum-varnames`, `x-enum-names` | names of the members of an enum, in PascalCase | | `x-enum-descriptions`, `x-enumDescriptions` | documentation comments of the members of an enum | The extensions can live in an overlay for this target instead of in the document, e.g. `csharp.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: C# names version: 1.0.0 actions: - target: $.components.schemas.OrderStatus update: x-enum-varnames: [Created, Paid, Shipped] - target: $.operations.publishAudit update: x-apigenie: codegen: disabled: true ``` ```sh apigenie-generator client csharp asyncapi.yaml --overlay csharp.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.client_csharp.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. The overlays apply to the AsyncAPI document bundled with the files it references. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the project is generated. ### --package-name Root namespace of the generated code, e.g. `Acme.Events.Client`. Defaults to the title of the API in PascalCase, followed by `.Client`. ### --package-version Version of the project. Defaults to the version of the API when it is a .NET version, else 1.0.0. ### -p, --property Applies to OpenAPI documents only. Using it with an AsyncAPI document is an error. ## Configuration The options are read from the `asyncapi` section of the configuration of `apigenie-generator client csharp`. Its other keys configure the generation from OpenAPI documents. ```yaml version: '1.0' commands: generate: client_csharp: asyncapi: root_namespace: Acme.Events.Client validation: true perspective: counterpart ``` | Option | Description | | ------ | ----------- | | `root_namespace` | Root namespace and assembly name of the project (default: `--package-name`, or the title followed by `.Client`) | | `validation` | `true` (default): validate messages by their DataAnnotations before sending and after receiving them | | `perspective` | `counterpart` (default): the counterpart of the described application; `application`: the application itself | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0, `client csharp` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (.NET SDK 8.0.204) | ✓ 15 of 15 operations pass (.NET SDK 8.0.204) | | Release 0.12.0, `client csharp (application)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (.NET SDK 8.0.204) | ✓ 15 of 15 operations pass (.NET SDK 8.0.204) | | Development version, `client csharp` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | Development version, `client csharp (application)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator client elixir (AsyncAPI) Source: https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate an Elixir client library of the WebSocket and Kafka channels of an AsyncAPI document. ## Usage ```sh apigenie-generator client elixir [...OPTIONS] INPUT_FILE ``` ## Description `apigenie-generator client elixir` generates from OpenAPI documents (see [`apigenie-generator client elixir`](/docs/reference/generator/client-elixir)) and from AsyncAPI 3.x documents, telling them apart by their `openapi` or `asyncapi` field. Documents referencing other files are bundled first. From an AsyncAPI document it generates a Mix library (Elixir 1.18 or later) for the counterpart of the described application, by default: it sends what the application receives and receives what it sends. The WebSocket channels connect on [Mint.WebSocket](https://hexdocs.pm/mint_web_socket), the Kafka channels use [brod](https://github.com/kafka4beam/brod). Set the `perspective` option to `application` for the application's Kafka library; WebSocket channels are connected to in the counterpart perspective only. With Kafka channels the library depends on [snappyer](https://hex.pm/packages/snappyer), a NIF that needs a C++ compiler, so that brod reads Snappy-compressed records (the default of Go's franz-go producers); LZ4 and zstd records need `lz4b` or `ezstd` added by hand. The generator writes the channels of servers with the `ws`/`wss` and `kafka`/`kafka-secure` protocols, and channels with a WebSocket or Kafka binding in documents without servers. Channels of other protocols (MQTT, AMQP, HTTP) are skipped and reported as info. ```elixir {:ok, socket} = CarpetExpressEvents.WebSocket.TrackingStream.connect("shp_8Yb2Kk1qP0wZcT3uXr5sN7aD", url: "ws://localhost:4000", query: [include: ["location"]], headers: [accept_language: "de-DE"], credentials: %{"streamToken" => token}, handler: MyApp.Tracking ) {:ok, pickup} = CarpetExpressEvents.WebSocket.PickupDesk.connect(url: "ws://localhost:4000") {:ok, %CarpetExpressEvents.Models.PickupConfirmed{}} = CarpetExpressEvents.WebSocket.PickupDesk.request_pickup(pickup, request) ``` The library, for the application `carpet_express_events` (named by `app`, `--package-name` or the document's title): | File | Contents | | ---- | -------- | | `lib/<app>/models/*.ex` | the structs of the schemas the payloads use, decoded and encoded by `decode.ex` and `encode.ex` | | `lib/<app>/websocket/<channel>.ex` | per WebSocket channel, `connect`, and the functions sending its messages and requests | | `lib/<app>/websocket/<channel>/handler.ex` | the behaviour of the callbacks receiving what the server sends on the channel | | `lib/<app>/messages/*.ex` | per Kafka message, a struct (`payload`, `headers`, `key`) and the description of its record | | `lib/<app>/avro/*.ex` | the structs of the Avro records and the enums of the payloads, with their schemas | | `lib/<app>/kafka/security.ex` | the security schemes of the Kafka servers and brod's client configuration of each | | `lib/<app>/kafka.ex` | the supervisor of the Kafka processes and a function per topic | | `lib/<app>/kafka/<operation>.ex` | per sent operation, its send (and request) functions; per received operation, the behaviour of its callbacks | | `lib/<app>/kafka/<operation>_consumer.ex` | per received operation, its group subscriber | | `lib/<app>/runtime/` | the WebSocket connection (`ChannelSocket`) and the Kafka runtime | | `mix.exs`, `.formatter.exs`, `.credo.exs` | the project, a library without application | - **WebSocket channels, two framings.** `connect` (with the channel's address parameters first) opens a connection to the server of `:url` and joins the channel. With `framing: :phoenix`, the default, it speaks the Phoenix Channels protocol (version 2) of `apigenie-generator server phoenix`: the socket `/socket/websocket`, the channel's topic (the address segments joined by `:`), the ws binding's `:query` as the join payload, a heartbeat every 30 seconds. With `framing: :plain` it connects to the channel's address, the query in the URL, and the frames are the messages of the AsyncAPI document. `send_<message>` sends a message; for a request, the function named after it waits for the reply: the reply to its ref in the Phoenix framing, the next message with the request's correlation id in the plain one. What the server sends is decoded into its struct and given to the callbacks of the channel's `Handler` behaviour (the `:handler` option), or sent to the calling process. `:headers` are the headers of the channel's ws binding, sent with the handshake. - **WebSocket security.** `:credentials` maps the keys of the channel's security schemes to credentials, and `connect` sends those of the schemes the handshake carries: an API key as its query parameter, header or cookie, `{user, password}` as basic credentials, a bearer token (`oauth2`, `openIdConnect`, `http` bearer) as the `access_token` query parameter in the Phoenix framing and as the `Authorization` header in the plain one. The server accepts the credential of any one of the schemes. - **Kafka.** Add `{CarpetExpressEvents.Kafka, brokers: "localhost:9092"}` to your supervision tree. `send_<message>/1` checks a message's headers and returns once the brokers have the record; `request_<message>/2` waits for the reply on the reply topic, matched by the correlation id (generated when the request has none; `:timeout`, 30 seconds by default). Each received operation has a consumer group (`:brod_group_subscriber_v2`) handing its records to the behaviour's callbacks, as `server phoenix` does: told apart by a constant header (`ce_type`), payload property or decoding, with the optional `on_unknown/1` and `on_invalid/2`; a replier's callback returns its reply, sent with the request's correlation id. Group ids come from the `groupId` schemas of the Kafka operation bindings, else `<app in kebab case>-<operation>`, and the consumer modules' configuration overrides them (`config :app, <Consumer>, group_id: ..., offset_reset_policy: :earliest`). Client ids come from the `clientId` schemas the same way: the producers' brod client has the application's, `<app in kebab case>` by default, and each consumer of replies and group subscriber has a brod client with the operation's. The Kafka supervisor takes `:security`, the key of a SASL or client certificate scheme of the Kafka servers, whose brod configuration `<Root>.Kafka.Security` returns with the credentials of environment variables named after the scheme key (`KAFKA_SCRAM_USERNAME` and `KAFKA_SCRAM_PASSWORD`; `KAFKA_MTLS_CERT`, `KAFKA_MTLS_KEY` and `KAFKA_MTLS_CA`), as in [`apigenie-generator server phoenix`](/docs/reference/generator/server-phoenix-asyncapi#kafka-security). Avro payloads are structs of their records, encoded and decoded without dependencies, with the ids of their schemas from a Confluent-compatible registry (the `:schema_registry` option), as in [`apigenie-generator server phoenix`](/docs/reference/generator/server-phoenix-asyncapi#avro-payloads). Not supported, and reported as warnings: payloads of non-JSON schema formats other than Avro, Avro unions other than nullable types and decimals, request/reply operations with Avro messages, reply addresses given by runtime expressions, Kafka topics with parameters, WebSocket addresses whose segments mix text and parameters, and security schemes a WebSocket handshake can't carry. Channels of other protocols (MQTT, AMQP, HTTP) are out of scope. The models check the schemas' constraints, `if`/`then`/`else`, `dependentRequired`, `dependentSchemas` and `not` when they decode a payload. ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the library is generated. ### --package-name Name of the Mix application, converted to snake_case (`carpet-express-events` gives `carpet_express_events`, root module `CarpetExpressEvents`); defaults to the title of the API. Its kebab case is the base of default group ids. ### --package-version Version of the Mix project; 0.1.0 by default. ### -p, --property Applies to OpenAPI documents only; using it with an AsyncAPI document is an error. ## Configuration The options are read from the `asyncapi` section of the configuration of `apigenie-generator client elixir`; its other keys configure the generation from OpenAPI documents. ```yaml version: '1.0' commands: generate: client_elixir: asyncapi: app: carpet_express_events perspective: counterpart ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `app` | string | from `--package-name` or the title | Name of the Mix application (snake_case) | | `namespace` | string | the application in PascalCase | Root module of the generated modules | | `perspective` | `counterpart` \| `application` | `counterpart` | The counterpart of the described application, or the application itself | | `field_prefix` | string | `field_` | Prefix of struct fields whose property names give no valid name | | `module_overrides` | map | | Module names of payload schemas, e.g. `ShipmentId: ShipmentRef` | | `dev_deps` | boolean | `true` | credo and dialyxir as dependencies of the dev and test environments | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0, `client elixir` | ✓ snapshots of 3.0; 41 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 18 of 18 operations pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | | Release 0.12.0, `client elixir (application)` | ✓ snapshots of 3.0; 26 supported, 0 not yet, 4 not checked | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 18 of 18 operations pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | | Development version, `client elixir` | ✓ snapshots of 3.0; 41 supported, 0 not yet | runs before a release | runs before a release | | Development version, `client elixir (application)` | ✓ snapshots of 3.0; 26 supported, 0 not yet, 4 not checked | runs before a release | runs before a release | --- # apigenie-generator client go (AsyncAPI) Source: https://apigenie.pl/docs/reference/generator/client-go-asyncapi Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Go Kafka client package for the Kafka channels of an AsyncAPI document. ## Usage ```sh apigenie-generator client go [...OPTIONS] INPUT_FILE ``` ## Description `apigenie-generator client go` generates from OpenAPI documents (see [`apigenie-generator client go`](/docs/reference/generator/client-go)) and from AsyncAPI 3.x documents, telling them apart by their `openapi` or `asyncapi` field. Documents referencing other files are bundled first. From an AsyncAPI document it generates a Go module (Go 1.22) with one package, using the Kafka client [franz-go](https://github.com/twmb/franz-go) (`github.com/twmb/franz-go/pkg/kgo`, pinned at v1.18.1 in `go.mod`, with a complete `go.sum`). By default the client is the counterpart of the application the document describes: it sends the messages of the application's `receive` operations and receives those of its `send` operations. Set the `perspective` option to `application` to generate the described application's side instead. [`apigenie-generator server go`](/docs/reference/generator/server-go-asyncapi) generates the other side as an application with its own `main.go`. The generator writes the Kafka channels: the channels of servers with the `kafka` or `kafka-secure` protocol, and channels with a Kafka binding in documents without servers. Channels of other protocols are skipped and reported as info. With `perspective: application`, the client of the Carpet Express Event Platform sends the shipment events and requests labels: ```go client, err := events.NewClient(events.Options{ Brokers: []string{"localhost:9092"}, ClientID: "label-printer", }) if err != nil { log.Fatal(err) } defer client.Close() // a sent operation with several messages takes any of them err = client.SendPublishShipmentEvents(ctx, delivered) // request/reply: waits for the reply with the request's correlation id reply, err := client.RequestLabelRender(ctx, request) switch reply := reply.(type) { case events.LabelRendered: fmt.Println(reply.Payload.URL) case events.LabelRenderFailed: fmt.Println(reply.Payload.Title) } ``` In the default perspective, it receives them and renders the labels: ```go type labelFarm struct{} func (labelFarm) OnRenderLabel(ctx context.Context, message events.RenderLabel) (events.RequestLabelRenderReply, error) { var reply events.LabelRendered reply.Key = message.Key reply.Payload = render(message.Payload) return reply, nil // sent to TopicLabelRenderResults with the request's correlation id } func (labelFarm) OnUnknown(ctx context.Context, record *kgo.Record) error { return nil } // received operations are consumed in the background until Close err = client.ListenRequestLabelRender(labelFarm{}) err = client.ListenPublishShipmentEvents(shipmentTracker{}) ``` The package is named by `package_name`, `--package-name` or the document's title (letters and digits, lower case): | File | Contents | | ---- | -------- | | `types.gen.go` | the types of the schemas the payloads use: structs with `json` tags, enums, and unions as a struct whose `Value` holds one variant of a sealed interface; each with a `Validate` method | | `messages.gen.go` | a struct per message (`Key`, `Headers`, `Payload`), its headers struct and header constants, and the code writing, reading and validating records | | `kafka.gen.go` | the server hosts, topics, group and client ids, the handler and message interfaces, and `Client` | | `avro.gen.go` | the structs of the Avro records of the payloads, with their schemas and codecs | | `security.gen.go` | the security schemes of the servers and the franz-go options of each | | `runtime_*.gen.go` | the Kafka runtime (consumers, requesters, headers), validation, `Nullable[T]`, `Date` | | `go.mod`, `go.sum` | the module, requiring franz-go | - **The client.** `NewClient(options)` creates the producer and, for every operation with a reply, one consumer of its reply topic that all of that operation's requests share. `Close` stops the listeners, commits the offsets of the records they handled, leaves their consumer groups and closes the clients. `Options` takes the brokers, `ClientID` (replacing the generated `ProducerClientID`), `ClientOptions` (franz-go options added to every client, e.g. `kgo.AllowAutoTopicCreation` or those of [a security scheme](#security)), `GroupIDs` (consumer groups by operation id), `OnError`, `ReplyTimeout` and `SchemaRegistry` (the ids of [Avro schemas](#avro-payloads)). - **Sent operations.** `Send<Operation>(ctx, message)` validates the message, writes its key, its headers (constant headers such as the `ce_specversion` and `ce_type` of CloudEvents included) and its JSON payload to the operation's topic, and returns once the brokers have it. With several messages, it takes an interface (`PublishShipmentEventsMessage`) that each of them implements. - **Request/reply** with a reply channel: `Request<Operation>(ctx, message)` sets a new correlation id unless the message has one, sends the request and waits for the reply with that id until the context is done (`Options.ReplyTimeout`, 30 seconds by default, when the context has no deadline). It returns the reply message, or an interface of the reply messages (`RequestLabelRenderReply`) when there are several. An operation named after the verb isn't repeated: `requestLabelRender` gives `RequestLabelRender`. - **Received operations.** `Listen<Operation>(handler)` consumes the operation's topic in the background, in its consumer group, until `Close`. The handler interface (`PublishShipmentEventsHandler`) has an `On<Message>` method per message and `OnUnknown`. Several messages are told apart by a payload property or a header with a distinct constant value (e.g. `type` or `ce_type`); otherwise the first message whose payload decodes strictly and is valid is chosen. Records that aren't valid messages, and handler errors, go to `Options.OnError` (logged by default). An operation with a reply gets `On<Message>(ctx, message) (Reply, error)`: the reply is sent to the reply topic with the request's correlation id copied. Group and client ids come from the Kafka operation bindings as for [`apigenie-generator server go`](/docs/reference/generator/server-go-asyncapi#description). ### Security Each SASL or client certificate scheme of the Kafka servers is a constant of `security.gen.go` (`SecurityKafkaScram`), with its key as value, and a function returning the franz-go options of the scheme: `KafkaScramSecurity(username, password)` for SASL, `KafkaMtlsSecurity(certFile, keyFile, caFile)` for a client certificate. `SecurityFromEnvironment(scheme)` takes the credentials from environment variables named after the scheme key, e.g. `KAFKA_SCRAM_USERNAME` and `KAFKA_SCRAM_PASSWORD`; add what it returns to `Options.ClientOptions`: ```go security, err := events.SecurityFromEnvironment(events.SecurityKafkaScram) if err != nil { log.Fatal(err) } client, err := events.NewClient(events.Options{Brokers: brokers, ClientOptions: security}) ``` | Scheme | Options of franz-go | | ------ | ------------------- | | `scramSha256`, `scramSha512` | `kgo.SASL` with the SCRAM mechanism of `<KEY>_USERNAME` and `<KEY>_PASSWORD`, and `kgo.DialTLSConfig` on `kafka-secure` servers | | `plain`, `userPassword` | the same with SASL PLAIN | | `X509` | `kgo.DialTLSConfig` with the PEM files named by `<KEY>_CERT` (the client certificate), `<KEY>_KEY` (its private key) and `<KEY>_CA` (the CA certificates) | Other schemes (`gssapi`, `oauth2`, ...) are left out with a warning. ### Avro payloads A message whose `schemaFormat` is an Avro one (`application/vnd.apache.avro;version=1.9.0`, with or without `+json` or `+yaml`) carries a struct of its record schema as its payload, in `avro.gen.go`, with `json` tags of the field names. Enums are string types with a constant per symbol (`CarrierScanStatusAtHub`), fixed types byte arrays. The logical types `timestamp-millis`, `timestamp-micros` and `date` are `time.Time`, `time-millis` and `time-micros` `time.Duration`; a union with `null` is a pointer. A root schema that isn't a record, records with `decimal` fields and unions of other types are skipped with a warning. The message struct is `<Message>Message` when the record's name is the message's (`CarrierScanMessage`). The generated codec writes and reads the payloads in Avro's binary encoding, with the id of the writer's schema where the Kafka binding of the message says: before the payload (`schemaIdLocation: payload`, Confluent's wire format) or in the `apicurio.value.globalId` header (`schemaIdLocation: header`, `SchemaIDHeader`). `Send` methods get the id from `Options.SchemaRegistry`, by the subject of `schemaLookupStrategy` (`TopicIdStrategy`, `{topic}-value`, by default), once per schema; without one, from the Confluent-compatible registry at the `schemaRegistryUrl` of the Kafka binding of the first Kafka server that has one, which registers the schema with `POST /subjects/{subject}/versions`. `ConfluentSchemaRegistry` takes a URL and basic authentication: ```go registry := events.ConfluentSchemaRegistry{URL: "https://schemas.events.carpetexpress.example", Username: "ingest", Password: os.Getenv("REGISTRY_PASSWORD")} client, err := events.NewClient(events.Options{Brokers: brokers, SchemaRegistry: registry}) ``` Listeners decode records with the schema of the generated struct, so the writer's schema must be the same; a record that isn't a payload of it is rejected. Request/reply operations with Avro messages are skipped with a warning. Not supported, and reported as warnings: payloads of other non-JSON schema formats (the messages are skipped, and operations left without a message too), reply addresses given by runtime expressions, and Kafka topics with parameters. Since 0.12.0, `Validate` checks `not`, the schemas of draft-07 `dependencies` and `if`/`then`/`else` when their schemas use only `required` and the `const` and `enum` of properties. `contentEncoding: base64` strings are `[]byte`. `prefixItems` tuples whose positions are references or scalars of one type are slices of that type, checked position by position, as in [`server go`](/docs/reference/generator/server-go#types). ## Extensions | Extension | Effect | | --------- | ------ | | `x-go-name` | name of the type of a schema, or of the field of a property | | `x-go-type` | Go type of a schema, e.g. `decimal.Decimal`; with `x-go-type-import: {path: ...}` for its package | | `x-go-type-skip-optional-pointer` | the optional property isn't a pointer | | `x-go-json-ignore` | the field gets the tag `json:"-"` | | `x-omitempty` | `true` or `false` overrides the `omitempty` of the field | | `x-enum-varnames`, `x-enumNames` | names of the enum constants | | `x-enum-descriptions` | comments of the enum constants | | `x-apigenie.codegen.name` | name of the type of a component schema, when it has no `x-go-name` | | `x-apigenie.codegen.disabled` | `true` on a channel or an operation leaves it out (with the operations of a channel left out) | The extensions can live in an overlay for this target instead of in the document, e.g. `go.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Go types version: 1.0.0 actions: - target: $.components.schemas.Order update: x-go-name: PurchaseOrder - target: $.components.schemas.Order.properties.total update: x-go-type: decimal.Decimal x-go-type-import: path: github.com/shopspring/decimal ``` ```sh apigenie-generator client go asyncapi.yaml --overlay go.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.client_go.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. The overlays apply to the AsyncAPI document bundled with the files it references. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the module is generated. ### --package-name Name of the Go package, as letters and digits in lower case (`carpet-express-events` gives `carpetexpressevents`); defaults to the title of the API (`events` when it gives no valid name). Its kebab case is the base of default group and client ids. ### --package-version Ignored: Go modules have no version in `go.mod`. ### -p, --property Applies to OpenAPI documents only; using it with an AsyncAPI document is an error. ## Configuration The options are read from the `asyncapi` section of the configuration of `apigenie-generator client go`; its other keys configure the generation from OpenAPI documents. ```yaml version: '1.0' commands: generate: client_go: asyncapi: module_path: github.com/acme/events package_name: events initialisms: [SKU] perspective: counterpart ``` | Option | Description | | ------ | ----------- | | `module_path` | Module path of `go.mod` (default: `example.com/<package>`) | | `package_name` | Name of the package, a lower-case Go identifier (default: from `--package-name` or the title) | | `initialisms` | Words written in capitals in identifiers, besides the common ones (`ID`, `URL`, ...) | | `perspective` | `counterpart` (default): the counterpart of the described application; `application`: the described application, sending what it sends | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0, `client go` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (go version go1.22.5 linux/amd64) | ✓ 14 of 14 operations pass (go version go1.22.5 linux/amd64) | | Release 0.12.0, `client go (application)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (go version go1.22.5 linux/amd64) | ✓ 14 of 14 operations pass (go version go1.22.5 linux/amd64) | | Development version, `client go` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | Development version, `client go (application)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator client java (AsyncAPI) Source: https://apigenie.pl/docs/reference/generator/client-java-asyncapi Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Java Kafka client library for the Kafka channels of an AsyncAPI document. ## Usage ```sh apigenie-generator client java [...OPTIONS] INPUT_FILE ``` ## Description `apigenie-generator client java` generates from OpenAPI documents (see [`apigenie-generator client java`](/docs/reference/generator/client-java)) and from AsyncAPI 3.x documents, telling them apart by their `openapi` or `asyncapi` field. Documents referencing other files are bundled first. From an AsyncAPI document it generates a Maven project of a plain Java 21 library on the Apache Kafka client (`kafka-clients` 4.1.0), without Spring. Payloads are JSON (Jackson) and are validated with Bean Validation. By default the client is the counterpart of the application the document describes: it sends the messages of the application's `receive` operations and receives those of its `send` operations. Set the `perspective` option to `application` to generate the described application's side instead. [`apigenie-generator server spring`](/docs/reference/generator/server-spring-asyncapi) generates the other side as a Spring Boot application. The two share their records, dispatch and header rules, so they exchange the same records. The generator writes the Kafka channels: the channels of servers with the `kafka` or `kafka-secure` protocol, and channels with a Kafka binding in documents without servers. Channels of other protocols are skipped and reported as info. With `perspective: application`, the client of the Carpet Express Event Platform sends the shipment events and requests labels: ```java var options = new CarpetExpressEventsKafkaClientOptions() .bootstrapServers("localhost:9092") .replyTimeout(Duration.ofSeconds(10)); try (var client = new CarpetExpressEventsKafkaClient(options)) { client.sendShipmentDelivered(delivered).get(); // request/reply: completes with the reply carrying the request's correlation id switch (client.requestLabelRender(request).get()) { case LabelRendered rendered -> System.out.println(rendered.payload().url()); case LabelRenderFailed failed -> System.out.println(failed.payload().title()); } } ``` In the default perspective, it receives them and renders the labels: ```java class LabelFarm implements RequestLabelRenderHandler { @Override public RequestLabelRenderReply onRenderLabel(RenderLabel message) { // sent to the labelRenderResults topic with the request's correlation id return new LabelRendered(message.key(), render(message.payload()), null); } } KafkaSubscription subscription = client.listenRequestLabelRender(new LabelFarm()); subscription.assigned().get(); // once the consumer group assigned partitions ``` The artifact id is `--package-name`, or the document's title followed by `-client`; the base package is `base_package`, or the title's (e.g. `com.example.carpetexpresseventplatform.client`): | Package | Contents | | ------- | -------- | | `model` | the records, enums and sealed interfaces of the schemas the payloads use, with Jackson and Bean Validation annotations | | `messages` | a record per message (`key`, `payload`, `headers`), its headers record with the constant headers (`CE_TYPE`, ...), and a sealed interface per reply | | `kafka` | `<Name>KafkaClient`, `<Name>KafkaClientOptions`, a handler interface per received operation, and the runtime: `KafkaJson`, `KafkaSubscription`, `KafkaReplies` | - **The client.** `new <Name>KafkaClient(options)` creates a producer per sending and replying operation, with the operation's client id; `close()` closes the subscriptions, the reply consumer and the producers. The options default to the document's server, topics, client ids and group ids. They also take the reply client id and timeout (30 seconds by default), and producer and consumer properties that replace the client's. - **Security.** The options get a method per SASL or client certificate scheme of the Kafka servers, named after its key: `kafkaScramSecurity(username, password)` sets `security.protocol` (`SASL_SSL`, or `SASL_PLAINTEXT` on `kafka` servers), `sasl.mechanism` (`SCRAM-SHA-256`, `SCRAM-SHA-512` or `PLAIN`) and `sasl.jaas.config` of the producers and consumers; `kafkaMtlsSecurity(certificate, key, ca)` reads the three PEM files and sets `security.protocol` `SSL` with a PEM keystore and truststore. `securityFromEnvironment()` uses the first scheme of the default server whose environment variables are set, named after the scheme key: `KAFKA_SCRAM_USERNAME` and `KAFKA_SCRAM_PASSWORD`, or `KAFKA_MTLS_CERT`, `KAFKA_MTLS_KEY` and `KAFKA_MTLS_CA` (file paths); it throws `IllegalStateException` when none are. ```java var client = new CarpetExpressEventsKafkaClient( new CarpetExpressEventsKafkaClientOptions().securityFromEnvironment()); ``` - **Sent operations.** `send<Message>(message)` validates the message, writes its key, its headers (constant headers such as the `ce_specversion` and `ce_type` of CloudEvents included) and its JSON payload to the operation's topic. It returns a `CompletableFuture<RecordMetadata>`. - **Request/reply** with a reply channel: `<operation>(message)` and `<operation>(message, timeout)` set a new correlation id unless the message has one (in its header, at its payload pointer, or in `kafka_correlationId`) and send the request. They return a `CompletableFuture` of the reply, or of the sealed interface of the reply messages (`RequestLabelRenderReply`); the future fails with a `TimeoutException` when no reply arrives in time. One consumer, without a consumer group, receives the replies of all requests and matches them by correlation id. - **Received operations.** `listen<Operation>(handler)` consumes the operation's topic on a virtual thread, in its consumer group (new groups start at the first record), until the returned `KafkaSubscription` or the client is closed. It commits the offsets of the records it handled. - The handler interface (`PublishShipmentEventsHandler`) has an `on<Message>` method per message, a default `onUnknown` and a default `onError`. - Several messages are told apart by a header or payload property with a distinct constant value (e.g. `ce_type`). Otherwise the first message whose payload reads strictly and is valid is chosen. - Records that aren't valid messages, and exceptions of the handler, go to `onError`. - A reply returned by the handler is sent to the reply topic with the request's correlation id. - **Avro payloads.** A message whose `schemaFormat` is an Avro one carries the Avro class of its record schema as its payload: the schema is written to `src/main/avro/<full name>.avsc`, and the `avro-maven-plugin` generates the class when the project builds (a schema without a `namespace` gets `<base package>.avro`). `KafkaAvro` encodes payloads in Avro's binary encoding with the id of their schema before them (Confluent's wire format) or in the `apicurio.value.globalId` header, as the message's Kafka binding says, and decodes them with the schema of the class. Senders take the id from the options' `schemaRegistry(registry)`, by the subject of the binding's `schemaLookupStrategy`. By default, the schemas are registered with the Confluent-compatible registry at the `schemaRegistryUrl` of the default server's Kafka binding, without authentication. ```java var client = new CarpetExpressEventsKafkaClient(new CarpetExpressEventsKafkaClientOptions() .schemaRegistry(KafkaAvro.confluent("https://schemas.events.carpetexpress.example", "ingest", password))); ``` Not supported, and reported as warnings: payloads of non-JSON schema formats other than Avro (Protobuf, RAML) (the messages are skipped, and operations left without a message too), reply addresses given by runtime expressions, Kafka topics with parameters, and security schemes other than `plain`, `scramSha256`, `scramSha512`, `userPassword` and `X509`, such as `gssapi` (set their properties with `producerProperty` and `consumerProperty`). ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | name of the class of a schema | | `x-apigenie.codegen.disabled` | `true` on a channel or an operation leaves it out (with the operations of a channel left out) | The extensions can live in an overlay for this target instead of in the document, e.g. `java.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Java names version: 1.0.0 actions: - target: $.components.schemas.Order update: x-apigenie: codegen: name: PurchaseOrder ``` ```sh apigenie-generator client java asyncapi.yaml --overlay java.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.client_java.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. The overlays apply to the AsyncAPI document bundled with the files it references. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the Maven project is generated. ### --package-name The artifact id, by default the document's title followed by `-client`. Its base, without `-client`, is the base of default group and client ids. ### --package-version Version of the artifact; defaults to the version of the API. ### --library, -p, --property Apply to OpenAPI documents only; using them with an AsyncAPI document is an error. ## Configuration The options are read from the `asyncapi` section of the configuration of `apigenie-generator client java`; its other keys configure the generation from OpenAPI documents. ```yaml version: '1.0' commands: generate: client_java: asyncapi: base_package: com.acme.events group_id: com.acme perspective: counterpart ``` | Option | Description | | ------ | ----------- | | `base_package` | Package of the generated code (default: from the title, followed by `.client`) | | `group_id` | Maven `groupId` (default: the base package) | | `java_version` | Java release, from 21 (default: 21; the client needs virtual threads) | | `bean_validation` | Bean Validation annotations on the models, and validation of sent and received messages (default: `true`) | | `perspective` | `counterpart` (default): the counterpart of the described application; `application`: the described application, sending what it sends | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0, `client java` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | ✓ 14 of 14 operations pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | | Release 0.12.0, `client java (application)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | ✓ 14 of 14 operations pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | | Development version, `client java` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | Development version, `client java (application)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator client kafkajs Source: https://apigenie.pl/docs/reference/generator/client-kafkajs Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a TypeScript (Node.js) Kafka client of an AsyncAPI document, on KafkaJS. ## Usage ```sh apigenie-generator client kafkajs [...OPTIONS] INPUT_FILE ``` ## Description The input must be an AsyncAPI 3.x document. Documents referencing other files are bundled first. The generator handles the Kafka channels: channels of a server whose protocol is `kafka` or `kafka-secure`, or with a `kafka` binding when the document has no servers. Other channels are skipped with an info message. The generated code runs on Node.js with [KafkaJS](https://kafka.js.org) 2.2.4, its only dependency. An AsyncAPI document describes an application. By default the client is its counterpart: it sends the messages of `receive` operations and receives the messages of `send` operations. Set the `perspective` option to `application` to generate the application's side instead. ```ts import { KafkaClient } from "order-service-kafka-client"; const client = new KafkaClient({ brokers: ["localhost:9092"] }); const reply = await client.handleOrderCommands.sendPlaceOrderMessage({ payload: { type: "place", requestId: crypto.randomUUID(), items: [{ sku: "ABC-0001", quantity: 1 }] }, }); await client.listenPublishStockLevels({ onStockLevelMessage: (message) => console.log(message.payload.sku), }); await client.close(); ``` `KafkaClient` has `connect()` (the senders connect on first use otherwise), a sender property per sent operation, a `listen<Operation>(handler)` method per received operation, which resolves once its consumer joined its group, and `close()`. Every sent operation gets a sender property with a `send<Message>(message)` method per message. It validates the message, sets the constant headers (e.g. `ce_type`) and resolves once the brokers have it. A message is `{ key?, headers, payload }`, with the headers under their names on the wire (`ce_id`). The method of an operation with a `reply` sends the request with a new correlation id unless it has one, and resolves with the reply: the reply message, or `{ name, message }` when there are several. It rejects with `ReplyTimeoutError` when no reply arrives in time (`{ timeoutMs }`, `KafkaOptions.replyTimeoutMs`, 30 seconds by default). Every received operation gets a handler interface: `on<Message>(message, record)` for each of its messages and an optional `onUnknown(record)`. Records are matched to messages by their `ce_type` (or other constant) header, by a constant payload property, or, failing both, by the first message whose payload is valid. The handlers of an operation with a `reply` return the reply (or `undefined` for none), which is sent with the request's correlation id. Invalid records are reported to `KafkaOptions.onError` and skipped. A handler that throws is reported too and the record is retried (KafkaJS doesn't commit it). Payloads and headers are validated against their schemas by generated functions without dependencies; invalid messages throw `MessageValidationError`, whose `issues` point into `/headers` or `/payload`. `KafkaOptions` takes the `brokers`, the producer's `clientId`, `config` (KafkaJS options for every client: `ssl`, `sasl`, `retry`, `logLevel`, ...), `groupIds` replacing the generated consumer groups, `fromBeginning` (true by default), `onError` and `schemaRegistry`. The generated code creates no topics. `src/kafka.ts` lists the SASL and X.509 schemes of each server in `SECURITY`, with the environment variables of their credentials (`KAFKA_SCRAM_USERNAME`, ...), and `securityConfig(server)` turns them into the `ssl` and `sasl` options of `KafkaOptions.config`. Pass it as `new KafkaClient({ brokers: [SERVERS[server]], config: securityConfig(server) })`. It throws when the server has schemes and none of them has all its variables set. Strings with `contentEncoding: base64` are `Uint8Array`s in messages and base64 on the wire. Avro payloads (a `schemaFormat` of `application/vnd.apache.avro`) get interfaces for their records and unions of string literals for their enums, in `src/messages.ts`, and are encoded in Avro's binary encoding by `src/avro_runtime.ts`, without dependencies. Their schema id comes from `KafkaOptions.schemaRegistry`. It is either a Confluent-compatible registry, `{ url, username?, password?, timeoutMs? }`, where the schema is registered the first time it is sent (a request times out after `timeoutMs`, 30 seconds by default; a registry that refuses the schema or can't be reached in time rejects the send with an `Error` naming the subject), or a function `(subject, schema) => Promise<number>` returning the id. The message binding's `schemaIdLocation` puts the id before the payload (`payload`, Confluent's format, the default) or in the `apicurio.value.globalId` header (`header`), and its `schemaLookupStrategy` names the subject (`TopicIdStrategy`, the default, gives `<topic>-value`). Received records are decoded with the generated schema. Avro `int` and `long` are `number`s; a received record with a `long` outside JavaScript's safe integers is invalid and goes to `onError`. The package contains `src/types.ts` (payload types), `src/messages.ts` (message and header interfaces), `src/kafka.ts` (servers, topics, ids, senders, handlers and the `KafkaClient`), `src/codecs.ts` (validators and the descriptions of the messages the runtime works with), `src/runtime.ts`, `src/validation_runtime.ts`, `src/avro_runtime.ts` (with Avro payloads only) and `src/index.ts`, with `package.json` and `tsconfig.json`. Not supported, and reported as warnings: topics with parameters, replies at runtime-expression addresses, replies without correlation ids, and security schemes other than `plain`, `scramSha256`, `scramSha512`, `userPassword` and `X509` (such as `gssapi`). [`apigenie-generator server kafkajs`](/docs/reference/generator/server-kafkajs) generates the other side on the same runtime. The design is ADR-120. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | name of the type of a component schema | | `x-apigenie.codegen.disabled` | `true` on a channel or an operation leaves it out (with the operations of a channel left out) | The extensions can live in an overlay for this target instead of in the document, e.g. `kafkajs.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: TypeScript names version: 1.0.0 actions: - target: $.components.schemas.Order update: x-apigenie: codegen: name: PurchaseOrder - target: $.operations.publishAudit update: x-apigenie: codegen: disabled: true ``` ```sh apigenie-generator client kafkajs asyncapi.yaml --overlay kafkajs.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.client_kafkajs.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. The overlays apply to the AsyncAPI document bundled with the files it references. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the package is generated. ### --package-name Name of the generated package. Defaults to the title of the API followed by `-kafka-client`. It is also the base of the generated consumer group and client ids. ### --package-version Version of the generated package. Defaults to the version of the API. ## Configuration ```yaml version: '1.0' commands: generate: client_kafkajs: layout: package import_extension: .js perspective: counterpart validation: true ``` | Option | Description | | ------ | ----------- | | `layout` | `package` (default): an npm package with sources in `src/`; `sources`: the sources only | | `import_extension` | Extension of relative imports: `.js` (default, Node.js) or an empty string (bundlers) | | `perspective` | `counterpart` (default): the counterpart of the described application; `application`: the application itself | | `validation` | `true` (default): validate payloads against their schemas; `false`: check the headers only | Unknown options are errors. ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0, `client kafkajs` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | ✓ 14 of 14 operations pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | | Release 0.12.0, `client kafkajs (application)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | ✓ 14 of 14 operations pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | | Development version, `client kafkajs` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | Development version, `client kafkajs (application)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator client python (AsyncAPI) Source: https://apigenie.pl/docs/reference/generator/client-python-asyncapi Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Python asyncio Kafka client package for the Kafka channels of an AsyncAPI document. ## Usage ```sh apigenie-generator client python [...OPTIONS] INPUT_FILE ``` ## Description `apigenie-generator client python` generates from OpenAPI documents (see [`apigenie-generator client python`](/docs/reference/generator/client-python)) and from AsyncAPI 3.x documents, telling them apart by their `openapi` or `asyncapi` field. Documents referencing other files are bundled first. From an AsyncAPI document it generates a Python package (Python 3.10 or later) on [aiokafka](https://github.com/aio-libs/aiokafka), with [Pydantic](https://docs.pydantic.dev) 2 models of the payloads: the models of [`apigenie-generator server faststream`](/docs/reference/generator/server-faststream). By default the client is the counterpart of the application the document describes: it sends the messages of the application's `receive` operations and receives those of its `send` operations. Set the `perspective` option to `application` to generate the described application's side instead. The generator writes the Kafka channels: the channels of servers with the `kafka` or `kafka-secure` protocol, and channels with a Kafka binding in documents without servers. Channels of other protocols are skipped and reported as info. With `perspective: application`, the client of the Carpet Express Event Platform sends the shipment events and requests labels: ```python options = CarpetExpressEventsKafkaClientOptions(bootstrap_servers="localhost:9092") async with CarpetExpressEventsKafkaClient(options) as client: await client.send_shipment_delivered(delivered) # request/reply: returns the reply carrying the request's correlation id reply = await client.request_label_render(request, timeout=10.0) if isinstance(reply, messages.LabelRendered): print(reply.payload.url) ``` In the default perspective, it receives them and renders the labels: ```python class LabelFarm(RequestLabelRenderHandler): async def on_render_label(self, message: messages.RenderLabel) -> messages.RequestLabelRenderReply | None: # sent to the labelRenderResults topic with the request's correlation id return messages.LabelRendered(payload=render(message.payload), key=message.key) subscription = await client.listen_request_label_render(LabelFarm()) await subscription.assigned() # once the consumer group assigned partitions ``` The package is the snake case of `--package-name`, or of the document's title followed by `_client`; the distribution name is its kebab case: | File | Contents | | ---- | -------- | | `models.py`, `_models.py` | the Pydantic models of the payloads | | `messages.py` | a dataclass per message (`payload`, `headers`, `key`), its headers model with the constant headers (`CE_TYPE`, ...), and a type alias per reply union | | `client.py` | `<Name>KafkaClient`, `<Name>KafkaClientOptions` and a handler class per received operation | | `_kafka.py`, `_runtime.py` | the Kafka runtime (records, subscriptions, replies) and the support of headers and correlation ids | | `security.py` | with security schemes: a function per scheme returning its aiokafka settings, and `security_from_environment(scheme)` | | `avro.py`, `_avro.py` | with Avro payloads: the Pydantic models of the records, and their codec on fastavro with the schema registry | | `pyproject.toml` | the distribution, requiring aiokafka and Pydantic (and fastavro with Avro payloads) | - **The client.** It is an async context manager; `start()` starts a producer per sending and replying operation, with the operation's client id, and `close()` stops the subscriptions, the reply consumer and the producers. The options default to the document's server, topics, client ids and group ids. They also take the reply client id and timeout (30 seconds), the `security` scheme, the `schema_registry` of the Avro payloads it sends, and keyword arguments of the aiokafka producers and consumers that replace the client's. - **Sent operations.** `send_<message>(message)` writes the message's key, its headers (constant headers such as the `ce_specversion` and `ce_type` of CloudEvents included) and its JSON payload to the operation's topic, and returns once the broker acknowledged it. - **Request/reply** with a reply channel: `request_<operation>(message, *, timeout=None)` sets a new correlation id unless the message has one (in its header, at its payload pointer, or in `kafka_correlationId`), sends the request and returns the reply, or raises `TimeoutError`. With several reply messages, the reply is one of them. One consumer, without a consumer group, receives the replies of all requests and matches them by correlation id. An operation named after the verb isn't repeated: `requestLabelRender` gives `request_label_render`. - **Received operations.** `listen_<operation>(handler)` consumes the operation's topic in a task, in its consumer group (new groups start at the first record), until the returned subscription or the client is closed. It commits the offsets of the records it handled. - The handler class (`PublishShipmentEventsHandler`) has an abstract `on_<message>` method per message, an `on_unknown` and an `on_error`. - Several messages are told apart by a header or payload property with a distinct constant value (e.g. `ce_type`). Otherwise the first message whose payload validates without unknown properties is chosen. - Records that aren't valid messages, and exceptions of the handler, go to `on_error`. - A reply returned by the handler is sent to the reply topic with the request's correlation id. Messages are validated by their models when they are built and when they are received; headers models ignore the record's other headers. The package passes `mypy --strict`. ### Security `security.py` has a function per SASL (`scramSha512`, `scramSha256`, `plain`, `userPassword`) or client certificate (`X509`) scheme of the Kafka servers, returning its aiokafka settings (`security_protocol`, `sasl_mechanism`, `sasl_plain_username`, `ssl_context`, ...), with TLS on `kafka-secure` servers. The `security` option names the scheme the producers and consumers connect with (`security="kafkaScram"`); `security_from_environment(scheme)` reads its credentials from environment variables named after the scheme: `KAFKA_SCRAM_USERNAME` and `KAFKA_SCRAM_PASSWORD`, or the paths of the PEM files in `<KEY>_CERT`, `<KEY>_KEY` and `<KEY>_CA`. The settings in `producer_options` and `consumer_options` replace the scheme's. ### Avro payloads A message with an Avro payload (`schemaFormat: application/vnd.apache.avro;version=1.9.0`) carries a Pydantic model of its record (`avro.CarrierScan`), with enums of its enum types, written and read with [fastavro](https://fastavro.readthedocs.io). The client sends the schema id the `schema_registry` option gives, by default a `ConfluentSchemaRegistry` of the `schemaRegistryUrl` of the first server whose Kafka binding has one, which registers the schema under the subject of the message's `schemaLookupStrategy` (`TopicIdStrategy` by default). The id is in the payload (the Confluent framing) or in a header, as the message's Kafka binding says (`schemaIdLocation`); the schema in the document reads the received records. A root schema that isn't a record, records with `decimal` fields and unions other than `["null", T]` are skipped with a warning. Not supported, and reported as warnings: payloads of other non-JSON schema formats and Avro messages of request/reply operations (the messages are skipped, and operations left without a message too), reply addresses given by runtime expressions, and Kafka topics with parameters. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | name of the model class of a component schema | | `x-enum-varnames`, `x-enumNames` | names of the members of an enum | | `x-apigenie.codegen.disabled` | `true` on a channel or an operation leaves it out (with the operations of a channel left out) | The extensions can live in an overlay for this target instead of in the document, e.g. `python.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Python names version: 1.0.0 actions: - target: $.components.schemas.Order update: x-apigenie: codegen: name: PurchaseOrder - target: $.components.schemas.OrderStatus update: x-enum-varnames: [CREATED, PAID, SHIPPED] ``` ```sh apigenie-generator client python asyncapi.yaml --overlay python.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.client_python.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. The overlays apply to the AsyncAPI document bundled with the files it references. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the package is generated. ### --package-name Name of the distribution, by default the document's title followed by `-client`. Its kebab case is the base of default group and client ids, and its Pascal case the base of the class names. ### --package-version Version of the distribution; defaults to the version of the API. ## Configuration The options are read from the `asyncapi` section of the configuration of `apigenie-generator client python`; its other keys configure the generation from OpenAPI documents. ```yaml version: '1.0' commands: generate: client_python: asyncapi: perspective: counterpart enum_style: literal ``` | Option | Description | | ------ | ----------- | | `perspective` | `counterpart` (default): the counterpart of the described application; `application`: the described application, sending what it sends | | `enum_style`, `field_prefix`, `class_overrides` | Settings of the Pydantic models, as for [`apigenie-generator client python`](/docs/reference/generator/client-python#configuration) | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0, `client python` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (python 3.12.11 aiokafka 0.14.0 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | ✓ 13 of 13 operations pass (python 3.12.11 aiokafka 0.14.0 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | | Release 0.12.0, `client python (application)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (python 3.12.11 aiokafka 0.14.0 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | ✓ 13 of 13 operations pass (python 3.12.11 aiokafka 0.14.0 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | | Development version, `client python` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | Development version, `client python (application)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator client ws Source: https://apigenie.pl/docs/reference/generator/client-ws Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a TypeScript client of the WebSocket channels of an AsyncAPI document. ## Usage ```sh apigenie-generator client ws [...OPTIONS] INPUT_FILE ``` ## Description The input must be an AsyncAPI 3.x document. Documents referencing other files are bundled first. The generator creates one class per WebSocket channel, i.e. a channel with a `ws` binding, or a channel of a server whose protocol is `ws` or `wss` (every channel when the document has no servers). Other channels are skipped. The client uses the `WebSocket` class of browsers and of Node.js 22 or later, and has no dependencies. An AsyncAPI document describes an application. By default the client is its counterpart: it sends the messages of `receive` operations and receives the messages of `send` operations. Set the `perspective` option to `application` to generate the application instead. ```ts import { RoomClient } from "chat-api-client"; const room = new RoomClient(); room.onRoomEvent((event) => console.log(event.kind)); await room.connect({ params: { roomId: "general" }, query: { token } }); room.sendJoin({ type: "join", user }); ``` Each class has: - `connect(options)`: opens the connection. Options are the server (`server`, a key of the document's servers, or `baseUrl`), the values of server variables (`variables`), the values of the parameters of the channel address (`params`), the query parameters of the WebSocket binding (`query`), handshake headers (`headers`, see below), the credentials of the channel's security schemes (`credentials`, see below), subprotocols (`protocols`) and a `webSocketFactory`. - `send<Message>(payload)` for every message the client sends. - `on<Message>(handler)` for every message it receives, when the channel receives one message, or when its messages can be told apart by a property with a distinct constant value (e.g. `type: { const: join }`). `onMessage(handler)` receives every message of a channel receiving several. Handlers return a function removing them. - `request<Operation>(payload, { timeoutMs })` for every operation whose `reply` is on the same channel, when the request and reply messages have a correlation id in their payloads (e.g. `$message.payload#/requestId`): it sends the request and resolves with the reply carrying the same id, or rejects after `timeoutMs` (30 seconds by default) or when the connection closes. The reply also reaches its `on<Message>` handler. Operation `requestPickup` gives `requestPickup`, `bookPickup` gives `requestBookPickup`. - `onError`, `onClose`, `onUnknownMessage`, `close()` and `connected`. Payloads are encoded by the content type of the message: JSON for `application/json` and `*/*+json` (the default), text for `text/*`, binary data (`ArrayBuffer`) otherwise. Browsers can't send headers with the WebSocket handshake, so the `headers` option requires a `webSocketFactory` creating sockets that can, e.g. of the `ws` package. A channel takes the security schemes of its operations, or of its servers for an operation without any. `credentials` holds a credential per scheme key: a string, or a function returning one or a promise of one, called on every `connect`. The credentials of the first of the channel's schemes that has some are sent: | Scheme | Sent as | | ------ | ------- | | `httpApiKey` | the query parameter, header or cookie named by `name` and `in` | | `http` with scheme `basic` | the `Authorization` header, from `user:password` | | `http` with scheme `bearer`, `oauth2`, `openIdConnect` | the `Authorization` header with a `webSocketFactory`, the `access_token` query parameter without one | ```ts await client.connect({ params: { shipmentId }, credentials: { streamToken: () => fetchStreamToken() } }); ``` Headers, cookies and basic credentials need a `webSocketFactory`, as other handshake headers do. `SECURITY_SCHEMES` in `src/metadata.ts` describes the schemes, and the servers and channels list their scheme keys (`security`). Other scheme types, such as `userPassword`, `X509` or the SASL schemes, can't be sent with a WebSocket handshake: they are left out with a warning. The generated package contains `src/types.ts` (component schemas), `src/messages.ts` (payload types and type guards), `src/client.ts`, `src/metadata.ts` (servers and channels), `src/runtime.ts` and `src/index.ts`, with `package.json` and `tsconfig.json`. The reply messages of an operation's `reply` on the same channel are received messages like the others. Not supported, and reported as warnings: replies on another channel or at a runtime-expression address, WebSocket binding methods other than `GET`, and security schemes that a WebSocket handshake can't carry. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | on a channel: the base of its names (`LobbyClient`); on a message: the base of its types (`PostPayload`); on a component schema: the name of its type | | `x-apigenie.codegen.disabled` | `true` on a channel or an operation leaves it out (with the operations of a channel left out) | The extensions can live in an overlay for this target instead of in the document, e.g. `ws.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: WebSocket names version: 1.0.0 actions: - target: $.channels.room update: x-apigenie: codegen: name: Lobby - target: $.components.messages.ChatMessage update: x-apigenie: codegen: name: Post ``` ```sh apigenie-generator client ws asyncapi.yaml --overlay ws.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.client_ws.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. The overlays apply to the AsyncAPI document bundled with the files it references. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the package is generated. ### --package-name Name of the generated package. Defaults to the title of the API followed by `-client`. ### --package-version Version of the generated package. Defaults to the version of the API. ## Configuration ```yaml version: '1.0' commands: generate: client_ws: layout: package import_extension: .js perspective: counterpart ``` | Option | Description | | ------ | ----------- | | `layout` | `package` (default): an npm package with sources in `src/`; `sources`: the sources only | | `import_extension` | Extension of relative imports: `.js` (default, Node.js) or an empty string (bundlers) | | `perspective` | `counterpart` (default): the client of the described application; `application`: the application itself | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.0; 32 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8) | ✓ 3 of 3 operations pass (node) | | Development version | ✓ snapshots of 3.0; 32 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator server aspnet (AsyncAPI) Source: https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate an ASP.NET Core application of the Kafka channels of an AsyncAPI document. ## Usage ```sh apigenie-generator server aspnet [...OPTIONS] INPUT_FILE ``` ## Description `apigenie-generator server aspnet` generates from OpenAPI documents (see [`apigenie-generator server aspnet`](/docs/reference/generator/server-aspnet)) and from AsyncAPI 3.x documents, telling them apart by their `openapi` or `asyncapi` field. Documents referencing other files are bundled first. From an AsyncAPI document it generates an ASP.NET Core project (.NET 8, `Microsoft.NET.Sdk.Web`) using the Kafka client [Confluent.Kafka](https://github.com/confluentinc/confluent-kafka-dotnet) (Apache-2.0, pinned at 2.15.1 in the project file). The consumers are hosted services of the application, so the same project can also serve a REST API. By default the application is the one the document describes: it sends the messages of `send` operations and receives the messages of `receive` operations. Set the `perspective` option to `counterpart` to swap them. The generator writes the Kafka channels: the channels of servers with the `kafka` or `kafka-secure` protocol, and channels with a Kafka binding in documents without servers. Channels of other protocols are skipped and reported as info. ```csharp public sealed class LabelFarm : IRequestLabelRenderHandler { public Task<IRequestLabelRenderReply?> OnRenderLabelAsync(RenderLabel message, CancellationToken cancellationToken) { IRequestLabelRenderReply reply = new LabelRendered { Key = message.Key, Payload = Render(message.Payload) }; // sent to Topics.LabelRenderResults with the request's correlation id return Task.FromResult<IRequestLabelRenderReply?>(reply); } } var builder = WebApplication.CreateBuilder(args); builder.Services.AddCarpetExpressKafka(builder.Configuration); builder.Services.AddScoped<IRequestLabelRenderHandler, LabelFarm>(); var app = builder.Build(); app.MapPost("/shipments/{id}/delivered", async (string id, PublishShipmentEventsSender sender) => await sender.SendShipmentDeliveredAsync(Delivered(id))); app.Run(); ``` The project's root namespace (and assembly name) is `root_namespace`, else `--package-name` or the document's title in PascalCase; the names of the application's classes start with the latter (`CarpetExpress`): | File | Contents | | ---- | -------- | | `Models/*.cs` | the types of the schemas the payloads use, as `apigenie-generator client csharp` writes them: records with `[JsonPropertyName]` and DataAnnotations, enums, and unions as abstract records | | `Serialization/*.cs` | the JSON context of the source generator of System.Text.Json, and the converters of unions, which read the discriminator wherever it is | | `Messages/*.cs` | a record per message (`Key`, `Headers`, `Payload`), its headers record and header constants, with `ToRecord()` and `FromRecord()` | | `Kafka/*.cs` | the settings, the handler interfaces and consumers of the received operations, the senders of the sent operations, the reply interfaces, and `Add<Name>Kafka` | | `Infrastructure/*.cs` | the Kafka runtime (producer, consumer service, requester, headers) and the validation of messages | | `<RootNamespace>.csproj`, `README.md` | the project | | `Program.cs`, `appsettings.json`, `Handlers/*.cs` | starting points, written once and never overwritten | - **Messages.** Headers are the message's headers merged with those of its traits as AsyncAPI does (JSON Merge Patch: a later `required` list replaces an earlier one). Header values are text on Kafka, so headers are `string`, `long`, `double` or `bool` properties, nullable when optional, with DataAnnotations for their length, pattern, format, values and range. Headers with a constant value, e.g. the `ce_specversion` and `ce_type` of CloudEvents in binary mode, are constants (`ShipmentStatusChanged.CeType`), which senders write and receivers compare. Messages are validated as a whole before they are sent and after they are received. - **Received operations.** A handler interface per operation (`IPublishShipmentEventsHandler`) has an `On<Message>Async` method per message and, when there are several messages, `OnUnknownAsync`, which ignores records by default. Register an implementation with the dependency injection container: the operation's consumer, a `BackgroundService` in the operation's consumer group, resolves it in a scope of its own for every record. Several messages are told apart by a payload property or a header with a distinct constant value (e.g. `type` or `ce_type`); otherwise the first message whose payload reads strictly and is valid is chosen. Records matching no message go to `OnUnknownAsync`. - **Delivery.** A record is committed once its handler returns. When the handler throws, the consumer logs the error and handles the record again after `RetryDelay`, so the records of a failing partition wait. Records that can't be read or are invalid messages are logged as warnings and committed. Stopping the host (Ctrl+C, SIGTERM) cancels the consumers, which close and leave their groups. - **Sent operations.** A sender per operation (`PublishShipmentEventsSender`), registered as a singleton, has a `Send<Message>Async` method per message that validates the message and completes once the brokers have it. Senders, requesters and repliers share one producer. - **Request/reply** with a reply channel: the requester's `Request<Message>Async` returns the reply (one of the reply messages, `IRequestLabelRenderReply`), matched by the request's correlation id, which is generated when the request has none; `ReplyTimeout` bounds the wait. Each requester consumes the reply topic without a consumer group, from a minute before it started, so a reply isn't missed and every instance of the application sees every reply. A replier's handler returns the reply (`null` for none), which is sent to the reply topic with the request's correlation id copied (to a header, or a payload property, as the `correlationId` locations say). ### Settings The `AsyncApi:Kafka` section of the configuration holds the settings, with the document's values as defaults; `appsettings.json` lists them, and environment variables override them as usual in ASP.NET Core (`AsyncApi__Kafka__BootstrapServers=localhost:9092`): ```json { "AsyncApi": { "Kafka": { "BootstrapServers": "kafka-eu.events.carpetexpress.example:9093", "ClientId": "carpet-express", "Topics": { "ShipmentEvents": "carpetexpress.shipment-events.v2" }, "Operations": { "PublishShipmentEvents": { "GroupId": "carpet-express-publish-shipment-events", "ClientId": "carpet-express-publish-shipment-events" } }, "ReplyTimeout": "00:00:30", "RetryDelay": "00:00:01", "Consumer": { "security.protocol": "SASL_SSL" }, "Producer": { "security.protocol": "SASL_SSL" } } } } ``` `BootstrapServers` defaults to the host of the first Kafka server, its variables replaced by their defaults. Group and client ids come from the `groupId` and `clientId` schemas of the Kafka operation bindings, of the operation or its traits: their `const`, single `enum` value, `default` or first example. Without a value, `<package name in kebab case>-<operation>` is used, and the documentation of the setting names the binding's pattern. The partitions, replicas and topic configuration of channel bindings are documented on the topic settings; the generated code creates no topics. `Consumer` and `Producer` take further librdkafka properties. ### Security Each SASL or client certificate scheme of the Kafka servers is a constant of `<Name>KafkaSecurity`, with its key as value. Set `Security` to the key (`"Security": "kafkaScram"`, or `AsyncApi__Kafka__Security=kafkaScram`) to connect every consumer and producer with the scheme; without one, they connect without security. The credentials come from environment variables named after the scheme key, e.g. `KAFKA_SCRAM_USERNAME` and `KAFKA_SCRAM_PASSWORD`: | Scheme | Settings of Confluent.Kafka | | ------ | --------------------------- | | `scramSha256`, `scramSha512` | `SecurityProtocol` `SaslSsl` (`SaslPlaintext` on `kafka` servers), `SaslMechanism`, and `<KEY>_USERNAME` and `<KEY>_PASSWORD` as `SaslUsername` and `SaslPassword` | | `plain`, `userPassword` | the same with `SaslMechanism.Plain` | | `X509` | `SecurityProtocol` `Ssl`, and the PEM files named by `<KEY>_CERT` (the client certificate), `<KEY>_KEY` (its private key) and `<KEY>_CA` as `SslCertificateLocation`, `SslKeyLocation` and `SslCaLocation` | `<Name>KafkaSecurity.With<Scheme>(config, ...)` applies a scheme with credentials from elsewhere, e.g. a secret store, to a `ClientConfig`. Other schemes (`gssapi`, `oauth2`, ...) are left out with a warning. ### Avro payloads A message whose `schemaFormat` is an Avro one (`application/vnd.apache.avro;version=1.9.0`, with or without `+json` or `+yaml`) carries a class of its record schema as its payload, in `Avro/<full name>.cs`: an `ISpecificRecord` of Apache.Avro in the namespace of the schema (`<root namespace>.Avro` for a schema without one), with C# enums for the schema's enums. The logical types `date` and `timestamp-*` (`local-timestamp-*` too) are `DateTime`, `time-millis` and `time-micros` `TimeSpan`, and `uuid` `Guid`; a union with `null` is a nullable type, other unions `object?`. A root schema that isn't a record, and records with `decimal` fields, are skipped with a warning. The generated `KafkaAvro` codec encodes and decodes the payloads in Avro's binary encoding, with the id of the writer's schema where the Kafka binding of the message says: before the payload (`schemaIdLocation: payload`, Confluent's wire format) or in the `apicurio.value.globalId` header (`schemaIdLocation: header`). Senders get the id from a schema registry, by the subject of `schemaLookupStrategy` (`TopicIdStrategy`, `{topic}-value`, by default): - an `ISchemaRegistry` service, when the application registers one; - otherwise the Confluent-compatible registry at `SchemaRegistryUrl` (by default the `schemaRegistryUrl` of the Kafka binding of the first Kafka server that has one), with the basic authentication of `SchemaRegistryUsername` and `SchemaRegistryPassword`. It registers each schema once with `POST /subjects/{subject}/versions`. ```csharp builder.Services.AddSingleton<ISchemaRegistry>( new ConfluentSchemaRegistry("https://schemas.events.carpetexpress.example", "ingest", builder.Configuration["RegistryPassword"])); ``` Consumers decode records with the schema of the generated class, so the writer's schema must be the same; a record that isn't a payload of it is rejected. Request/reply operations with Avro messages are skipped with a warning. Not supported, and reported as warnings: payloads of other non-JSON schema formats (the messages are skipped, and operations left without a message too), reply addresses given by runtime expressions, and Kafka topics with parameters. With a correlation id in the payload at a place that isn't a string or uuid property of the payload record, the request must carry the id and the replier's handler must copy it. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.disabled` | `true` on a channel or an operation leaves it out (with the operations of a channel left out) | | `x-enum-varnames`, `x-enum-names` | names of the members of an enum, in PascalCase | | `x-enum-descriptions`, `x-enumDescriptions` | documentation comments of the members of an enum | The extensions can live in an overlay for this target instead of in the document, e.g. `aspnet.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: ASP.NET names version: 1.0.0 actions: - target: $.components.schemas.OrderStatus update: x-enum-varnames: [Created, Paid, Shipped] - target: $.operations.publishAudit update: x-apigenie: codegen: disabled: true ``` ```sh apigenie-generator server aspnet asyncapi.yaml --overlay aspnet.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_aspnet.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. The overlays apply to the AsyncAPI document bundled with the files it references. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the project is generated. ### --package-name Root namespace of the generated code and base of the names of the application's classes, in PascalCase (`carpet-express` gives `CarpetExpress`); defaults to the title of the API. Its kebab case is the base of default group and client ids. ### --package-version Version of the project; defaults to the version of the API when it is a .NET version, else 1.0.0. ### -p, --property Applies to OpenAPI documents only; using it with an AsyncAPI document is an error. ## Configuration The options are read from the `asyncapi` section of the configuration of `apigenie-generator server aspnet`; its other keys configure the generation from OpenAPI documents. ```yaml version: '1.0' commands: generate: server_aspnet: asyncapi: root_namespace: Acme.Events validation: true program: true perspective: application ``` | Option | Description | | ------ | ----------- | | `root_namespace` | Root namespace and assembly name of the project (default: from `--package-name` or the title) | | `validation` | `true` (default): validate messages by their DataAnnotations before sending and after receiving them | | `program` | `true` (default): write `Program.cs`, `appsettings.json` and the handler stubs when they don't exist | | `perspective` | `application` (default): the described application; `counterpart`: its counterpart, receiving what it sends | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0, `server aspnet` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (.NET SDK 8.0.204) | ✓ 7 of 7 operations pass (.NET SDK 8.0.204) | | Release 0.12.0, `server aspnet (counterpart)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (.NET SDK 8.0.204) | ✓ 7 of 7 operations pass (.NET SDK 8.0.204) | | Development version, `server aspnet` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | Development version, `server aspnet (counterpart)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator server faststream Source: https://apigenie.pl/docs/reference/generator/server-faststream Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Python [FastStream](https://faststream.ag2.ai) application of the Kafka, AMQP (RabbitMQ) and MQTT channels of an AsyncAPI document. ## Usage ```sh apigenie-generator server faststream [...OPTIONS] INPUT_FILE ``` ## Description The input must be an AsyncAPI 3.x document. Documents referencing other files are bundled first. The application is the one the document describes: it receives the messages of `receive` operations and sends those of `send` operations. - one broker per server: `KafkaBroker` for `kafka` and `kafka-secure` servers (aiokafka), `RabbitBroker` for `amqp` and `amqps` (AMQP 0.9.1) and `MQTTBroker` for `mqtt`, `mqtts` and `secure-mqtt` (MQTT 5 or 3.1.1). A broker connects to the URL in an environment variable named after its server (`PRODUCTION_KAFKA_URL`), or to the server's address with the default values of its variables - a subscriber per receive operation, `@broker.subscriber(...)`, which calls a handler you write - a publisher per send operation, `@broker.publisher(...)`, and an `async` function publishing through it with typed arguments - Pydantic v2 models of the payloads and headers ```python from warehouse_events import models from warehouse_events.publishers import publish_audit, request_quote await publish_audit(models.AuditEntry(action="login"), region="eu") quote = await request_quote(models.QuoteRequest(sku="B"), timeout=5) ``` Run the application with `faststream run <package>.app:app`. ### Channels and bindings | Document | Generated code | | -------- | -------------- | | Channel address, Kafka binding `topic` | the topic; with parameters a `pattern=` subscription and `Path()` parameters | | Channel parameters with `enum` | `Literal[...]` types of the `Path()` parameters and of the publish functions' arguments | | Channel parameters with a `location` in the payload (`$message.payload#/destinationCountry`) | optional arguments of the publish functions, read from the message when not given | | Kafka message binding `key` (a string schema) | a `key: str \| None` argument of the publish functions, sent as the record's key | | Kafka operation binding `groupId` (`const` or a single `enum` value), also from operation traits | `group_id=` of the subscriber | | AMQP binding `is: queue` | a `RabbitQueue` (name, `durable`, `exclusive`, `auto_delete`) the operations publish to and consume from | | AMQP binding `is: routingKey` with an exchange | a `RabbitExchange` in `brokers.py`; the address is the routing key, with parameters a topic pattern and `Path()` parameters. Subscribers bind a queue named after the operation | | AMQP `vhost` | `virtualhost=` of the broker | | AMQP operation binding `priority`, `expiration`, `deliveryMode: 2`, `mandatory`, `userId`, `timestamp` | the publisher's `priority`, `expiration` (in seconds), `persist`, `mandatory`, `user_id`; a timestamp per message | | AMQP message binding `contentEncoding` (`gzip`, `deflate`), `messageType` | published payloads compressed and sent with `content_encoding=` and `message_type=`; received ones decompressed by the subscriber's decoder. The messages of an operation must agree on them, or none is set (a warning) | | MQTT topic parameters (whole topic levels) | `Path()` parameters | | MQTT operation binding `qos`, `retain` | `qos=`, `retain=` | | MQTT message binding `responseTopic`, `correlationData` | a request with a reply address publishes with `reply_to=` (the MQTT 5 response topic) and `correlation_id=` (its correlation data) as well as the headers | | MQTT server binding `clientId`, `cleanSession`, `keepAlive`, `sessionExpiryInterval`, `lastWill` | the broker's `client_id`, `clean_session`, `keepalive`, `session_expiry_interval`, `will` | ### Messages A JSON payload becomes a Pydantic model, a `text/*` one `str` and any other content type `bytes`. The models reject the properties their schemas don't allow (`extra="forbid"` for `additionalProperties: false`) and check the keys and the sizes of maps (`propertyNames`, `patternProperties`, `minProperties`, `maxProperties`), and they carry the examples of the messages' payloads in `json_schema_extra`, for FastStream's AsyncAPI page. The docstring of each publish function lists its messages, with their titles and summaries. A payload referencing a schema of `components/schemas` is the model of that schema; other payloads and headers get a model named after their message (`OrderCreated`, `OrderCreatedHeaders`). The headers of message traits are merged into the message's own as AsyncAPI specifies (JSON Merge Patch: the message over its traits, later traits over earlier ones). Subscribers take the headers as typed `Header()` parameters and pass them to the handlers as keyword arguments; publish functions take a `headers` model. When several messages of a channel can be told apart by a property with a distinct constant value (`type: { const: created }`), the payload is a discriminated union and every message has a handler of its own (`consume_orders_order_created`); otherwise the handler of the operation gets the union. ### Avro payloads A message received from Kafka with an Avro payload (`schemaFormat: application/vnd.apache.avro;version=1.9.0`) is a Pydantic model of its record in `avro.py`, the same as `generate client python`'s, with enums of its enum types. The subscriber's decoder reads the record with [fastavro](https://fastavro.readthedocs.io): the Confluent framing (a magic byte and the schema id) in the payload, or the schema id in a header when the message's Kafka binding says so (`schemaIdLocation: header`). The schema in the document is the writer's schema: the registry isn't asked. A root schema that isn't a record, records with `decimal` fields and unions other than `["null", T]` are skipped with a warning. Avro messages sent by the application, or received from other brokers, or received together with other messages by the same operation, are skipped with a warning: FastStream's Kafka publishers send headers as text, which the binary schema id header isn't. ### Security `security.py` has a function per security scheme of the servers returning its FastStream security object, and a function per broker, `<broker>_security()`, that `brokers.py` passes as `security=`: | Scheme | Security object | | ------ | --------------- | | Kafka `scramSha512`, `scramSha256`, `plain` (and `userPassword`) | `SASLScram512`, `SASLScram256`, `SASLPlaintext` | | `X509` | `RabbitExternalAuth` on AMQP servers, `BaseSecurity` with a client certificate elsewhere | | AMQP and MQTT `userPassword`, `plain` | `SASLPlaintext` | | MQTT `openIdConnect`, `oauth2` | `SASLPlaintext` with the token as the password | The broker's function reads the scheme's key from an environment variable named after the server (`PRODUCTION_KAFKA_SECURITY=kafkaScram`) and its credentials from variables named after the scheme: `KAFKA_SCRAM_USERNAME` and `KAFKA_SCRAM_PASSWORD`, `<KEY>_CERT`, `<KEY>_KEY` and `<KEY>_CA` for certificates, `<KEY>_TOKEN` and an optional `<KEY>_USERNAME` for tokens. Without the variable, the broker connects without security. TLS servers (`kafka-secure`, `amqps`, `mqtts`, `secure-mqtt`) verify the server with the system's CA certificates. The README lists the variables of each broker and scheme. ### Request/reply - A send operation with a reply channel: its function publishes the request and returns the reply, waiting at most `timeout` seconds. A subscriber of the reply channel hands replies to the waiting requests by correlation id: the message's `correlationId` (a header, which the function fills in when the request has none, or a payload property), or FastStream's correlation id when the document declares none. FastStream's `broker.request()` isn't used: Kafka doesn't support it outside the test client, and RabbitMQ's waits on `amq.rabbitmq.reply-to` instead of the reply channel of the document. - A send operation with a reply address in a header (`$message.header#/replyTo`): its function takes a `reply_to` argument and sends it in that header. - A receive operation with a reply channel: the handler returns the reply, which is published to the reply channel with the request's correlation id header. - A receive operation with a reply address in a header: the handler returns the reply, which is published to the address in the request's header. ### Output ```text pyproject.toml faststream[cli,…], pydantic; `pip install -e .` README.md how to run, the environment variables, what isn't generated <package>/app.py the FastStream application <package>/brokers.py the brokers and AMQP exchanges <package>/subscribers.py <package>/publishers.py <package>/handlers.py the handlers you write <package>/models.py Pydantic models (shared with apigenie-generator client python) <package>/security.py the security objects of the brokers, with security schemes <package>/avro.py the Avro records, with Avro payloads (and _avro.py, fastavro) <package>/_models.py, _runtime.py, __init__.py, py.typed ``` `handlers.py` is written only when it doesn't exist: it holds your code. After regenerating, add the handlers of new operations to it; mypy reports the missing ones. ### Not generated Reported as info lines or warnings: - channels of WebSocket and HTTP servers, which FastStream has no broker for - messages with payloads in other non-JSON Schema formats, Avro messages the application sends (see "Avro payloads"), and operations left without messages - the security schemes FastStream has no security object for (`apiKey`, `httpApiKey`, `http`, `scramSha` on other protocols, ...). `symmetricEncryption` and `asymmetricEncryption` encrypt the messages, not the connection: an info line says that the handlers and publishers must do it - AMQP message bindings the messages of an operation disagree on, and content encodings other than `gzip` and `deflate` - servers no generated operation uses; a channel with several servers is served by its first one (choose others with the `servers` option) - reply addresses in payloads, AMQP `cc` and `bcc`, MQTT topic parameters inside a topic level The MQTT message binding's `payloadFormatIndicator` and `messageExpiryInterval` aren't applied: FastStream's MQTT publishers don't set them. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | on a component schema: the name of its model class; on an operation: the name of its function (in snake_case) | | `x-enum-varnames`, `x-enumNames` | names of the members of an enum | | `x-apigenie.codegen.disabled` | `true` on a channel or an operation leaves it out (with the operations of a channel left out) | The extensions can live in an overlay for this target instead of in the document, e.g. `faststream.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: FastStream names version: 1.0.0 actions: - target: $.operations.publishOrder update: x-apigenie: codegen: name: announce_order - target: $.components.schemas.OrderStatus update: x-enum-varnames: [CREATED, PAID, SHIPPED] ``` ```sh apigenie-generator server faststream asyncapi.yaml --overlay faststream.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_faststream.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. The overlays apply to the AsyncAPI document bundled with the files it references. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the package is generated. ### --package-name Name of the generated distribution; the Python package is its snake_case form. Defaults to the title of the API. ### --package-version Version of the generated package. Defaults to the version of the API. ## Configuration ```yaml version: '1.0' commands: generate: server_faststream: servers: [production-kafka, customs-broker] enum_style: enum field_prefix: field_ class_overrides: ShipmentId: ShipmentKey ``` | Option | Description | | ------ | ----------- | | `servers` | Keys of the servers to generate brokers for; all Kafka, AMQP and MQTT servers by default | | `enum_style` | `enum` (default): `class Status(str, Enum)` for enums of component schemas; `literal`: `Literal[...]` everywhere | | `field_prefix` | Prefix of field names that aren't valid identifiers or clash with Pydantic, e.g. `field_json` (default `field_`) | | `class_overrides` | Class names of component schemas, by schema name | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.0; 50 supported, 0 not yet | ✓ pass (python 3.12.11 faststream 0.7.7 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | ✓ 10 of 10 operations pass (python 3.12.11 faststream 0.7.7 pydantic 2.13.5 mypy 2.4.0, ruff 0.16.10) | | Development version | ✓ snapshots of 3.0; 50 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator server go (AsyncAPI) Source: https://apigenie.pl/docs/reference/generator/server-go-asyncapi Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Go Kafka application of the Kafka channels of an AsyncAPI document. ## Usage ```sh apigenie-generator server go [...OPTIONS] INPUT_FILE ``` ## Description `apigenie-generator server go` generates from OpenAPI documents (see [`apigenie-generator server go`](/docs/reference/generator/server-go)) and from AsyncAPI 3.x documents, telling them apart by their `openapi` or `asyncapi` field. Documents referencing other files are bundled first. From an AsyncAPI document it generates a Go module (Go 1.22) using the Kafka client [franz-go](https://github.com/twmb/franz-go) (`github.com/twmb/franz-go/pkg/kgo`, pinned at v1.18.1 in `go.mod`, with a complete `go.sum`). By default the application is the one the document describes: it sends the messages of `send` operations and receives the messages of `receive` operations. Set the `perspective` option to `counterpart` to swap them. The generator writes the Kafka channels: the channels of servers with the `kafka` or `kafka-secure` protocol, and channels with a Kafka binding in documents without servers. Channels of other protocols are skipped and reported as info. ```go type labelFarm struct{} func (labelFarm) OnRenderLabel(ctx context.Context, message events.RenderLabel) (events.RequestLabelRenderReply, error) { var reply events.LabelRendered reply.Key = message.Key reply.Payload = render(message.Payload) return reply, nil // sent to TopicLabelRenderResults with the request's correlation id } func (labelFarm) OnUnknown(ctx context.Context, record *kgo.Record) error { return nil } func main() { var handlers events.Handlers handlers.RequestLabelRender = labelFarm{} // ... app, err := events.NewApp(events.Options{Brokers: []string{"localhost:9092"}}, handlers) if err != nil { log.Fatal(err) } defer app.Close() err = app.PublishShipmentEvents().SendShipmentDelivered(ctx, delivered) // ... _ = app.Run(ctx) // consumes until ctx is done } ``` The module has one package at its root, named by `package_name`, `--package-name` or the document's title (letters and digits, lower case): | File | Contents | | ---- | -------- | | `types.gen.go` | the types of the schemas the payloads use: structs with `json` tags, enums, and unions as a struct whose `Value` holds one variant of a sealed interface (`switch v := event.Value.(type)`); each with a `Validate` method | | `messages.gen.go` | a struct per message (`Key`, `Headers`, `Payload`), its headers struct and header constants, and the code writing, reading and validating records | | `kafka.gen.go` | the server hosts, topics, group and client ids, the handler interfaces, `Handlers`, `App` and the senders | | `avro.gen.go` | the structs of the Avro records of the payloads, with their schemas and codecs | | `security.gen.go` | the security schemes of the servers and the franz-go options of each | | `runtime_*.gen.go` | the Kafka runtime (consumers, requesters, headers), validation, `Nullable[T]`, `Date` | | `go.mod`, `go.sum` | the module, requiring franz-go | | `cmd/<package>/main.go` | a starting point, written once and never overwritten | - **Messages.** Headers are the message's headers merged with those of its traits as AsyncAPI does (JSON Merge Patch: a later `required` list replaces an earlier one). Header values are text on Kafka, so headers are `string`, `int64`, `float64` or `bool` fields, pointers when optional. Headers with a constant value, e.g. the `ce_specversion` and `ce_type` of CloudEvents in binary mode, are constants (`ShipmentStatusChangedCeType`), which senders write and receivers compare. Messages are validated as a whole before they are sent and after they are received. - **Received operations.** `NewApp(options, handlers)` takes a handler per received operation (`PublishShipmentEventsHandler`) with an `On<Message>` method per message and `OnUnknown`. Several messages of a channel are told apart by a payload property or a header with a distinct constant value (e.g. `type` or `ce_type`); otherwise the first message whose payload decodes strictly and is valid is chosen. Records matching no message go to `OnUnknown`. `Run` consumes the operations' topics, each in its consumer group, until its context is done; `Close` commits the offsets of the handled records and leaves the groups. Records that aren't valid messages, and handler errors, go to `Options.OnError` (logged by default); the records are committed either way. - **Sent operations.** `app.PublishShipmentEvents()` returns the sender of the operation, with a `Send<Message>(ctx, message)` method per message that validates the message and returns once the brokers have it. - **Request/reply** with a reply channel: the requester's `Send<Message>` returns the reply (one of the reply messages, `RequestLabelRenderReply`), matched by the request's correlation id, which is generated when the request has none; `Options.ReplyTimeout` bounds the wait when the context has no deadline. A replier's handler returns the reply, which is sent to the reply topic with the request's correlation id copied (to a header, or a payload property, as the `correlationId` locations say). Group and client ids come from the `groupId` and `clientId` schemas of the Kafka operation bindings, of the operation or its traits: their `const`, single `enum` value, `default` or first example. Without a value, `<package name in kebab case>-<operation>` is used, and the doc comment of the constant names the binding's pattern. `Options.GroupIDs` replaces them by operation id. The partitions, replicas and topic configuration of channel bindings are documented on the topic constants; the generated code creates no topics. `main.go` connects to the brokers of the `-brokers` flag, else of the `KAFKA_BROKERS` environment variable (comma-separated), else `localhost:9092`, wires stub handlers that return `api.ErrNotImplemented`, and stops cleanly on SIGINT or SIGTERM. With the `-security` flag, else the `KAFKA_SECURITY` environment variable, it connects with that security scheme (see [Security](#security)). ### Security Each SASL or client certificate scheme of the Kafka servers is a constant of `security.gen.go` (`SecurityKafkaScram`), with its key as value, and a function returning the franz-go options of the scheme: `KafkaScramSecurity(username, password)` for SASL, `KafkaMtlsSecurity(certFile, keyFile, caFile)` for a client certificate. `SecurityFromEnvironment(scheme)` takes the credentials from environment variables named after the scheme key, e.g. `KAFKA_SCRAM_USERNAME` and `KAFKA_SCRAM_PASSWORD`; add what it returns to `Options.ClientOptions`: ```go security, err := events.SecurityFromEnvironment(events.SecurityKafkaScram) if err != nil { log.Fatal(err) } app, err := events.NewApp(events.Options{Brokers: brokers, ClientOptions: security}, handlers) ``` | Scheme | Options of franz-go | | ------ | ------------------- | | `scramSha256`, `scramSha512` | `kgo.SASL` with the SCRAM mechanism of `<KEY>_USERNAME` and `<KEY>_PASSWORD`, and `kgo.DialTLSConfig` on `kafka-secure` servers | | `plain`, `userPassword` | the same with SASL PLAIN | | `X509` | `kgo.DialTLSConfig` with the PEM files named by `<KEY>_CERT` (the client certificate), `<KEY>_KEY` (its private key) and `<KEY>_CA` (the CA certificates) | Other schemes (`gssapi`, `oauth2`, ...) are left out with a warning. ### Avro payloads A message whose `schemaFormat` is an Avro one (`application/vnd.apache.avro;version=1.9.0`, with or without `+json` or `+yaml`) carries a struct of its record schema as its payload, in `avro.gen.go`, with `json` tags of the field names. Enums are string types with a constant per symbol (`CarrierScanStatusAtHub`), fixed types byte arrays. The logical types `timestamp-millis`, `timestamp-micros` and `date` are `time.Time`, `time-millis` and `time-micros` `time.Duration`; a union with `null` is a pointer. A root schema that isn't a record, records with `decimal` fields and unions of other types are skipped with a warning. The message struct is `<Message>Message` when the record's name is the message's (`CarrierScanMessage`). The generated codec writes and reads the payloads in Avro's binary encoding, with the id of the writer's schema where the Kafka binding of the message says: before the payload (`schemaIdLocation: payload`, Confluent's wire format) or in the `apicurio.value.globalId` header (`schemaIdLocation: header`, `SchemaIDHeader`). Senders get the id from `Options.SchemaRegistry`, by the subject of `schemaLookupStrategy` (`TopicIdStrategy`, `{topic}-value`, by default), once per schema; without one, from the Confluent-compatible registry at the `schemaRegistryUrl` of the Kafka binding of the first Kafka server that has one, which registers the schema with `POST /subjects/{subject}/versions`. `ConfluentSchemaRegistry` takes a URL and basic authentication: ```go registry := events.ConfluentSchemaRegistry{URL: "https://schemas.events.carpetexpress.example", Username: "ingest", Password: os.Getenv("REGISTRY_PASSWORD")} app, err := events.NewApp(events.Options{Brokers: brokers, SchemaRegistry: registry}, handlers) ``` Receivers decode records with the schema of the generated struct, so the writer's schema must be the same; a record that isn't a payload of it is rejected. Request/reply operations with Avro messages are skipped with a warning. Not supported, and reported as warnings: payloads of other non-JSON schema formats (the messages are skipped, and operations left without a message too), reply addresses given by runtime expressions, and Kafka topics with parameters. Since 0.12.0, `Validate` checks `not`, the schemas of draft-07 `dependencies` and `if`/`then`/`else` when their schemas use only `required` and the `const` and `enum` of properties. `contentEncoding: base64` strings are `[]byte`. `prefixItems` tuples whose positions are references or scalars of one type are slices of that type, checked position by position, as in [`server go`](/docs/reference/generator/server-go#types). With a correlation id in the payload at a place that isn't a string field of the payload's structs, the request must carry the id and the replier's handler must copy it. ## Extensions | Extension | Effect | | --------- | ------ | | `x-go-name` | name of the type of a schema, or of the field of a property | | `x-go-type` | Go type of a schema, e.g. `decimal.Decimal`; with `x-go-type-import: {path: ...}` for its package | | `x-go-type-skip-optional-pointer` | the optional property isn't a pointer | | `x-go-json-ignore` | the field gets the tag `json:"-"` | | `x-omitempty` | `true` or `false` overrides the `omitempty` of the field | | `x-enum-varnames`, `x-enumNames` | names of the enum constants | | `x-enum-descriptions` | comments of the enum constants | | `x-apigenie.codegen.name` | name of the type of a component schema, when it has no `x-go-name` | | `x-apigenie.codegen.disabled` | `true` on a channel or an operation leaves it out (with the operations of a channel left out) | The extensions can live in an overlay for this target instead of in the document, e.g. `go.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Go types version: 1.0.0 actions: - target: $.components.schemas.Order update: x-go-name: PurchaseOrder - target: $.components.schemas.Order.properties.total update: x-go-type: decimal.Decimal x-go-type-import: path: github.com/shopspring/decimal ``` ```sh apigenie-generator server go asyncapi.yaml --overlay go.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_go.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. The overlays apply to the AsyncAPI document bundled with the files it references. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the module is generated. ### --package-name Name of the Go package, as letters and digits in lower case (`carpet-express-events` gives `carpetexpressevents`); defaults to the title of the API (`events` when it gives no valid name). Its kebab case is the base of default group and client ids. ### --package-version Ignored: Go modules have no version in `go.mod`. ### -p, --property Applies to OpenAPI documents only; using it with an AsyncAPI document is an error. ## Configuration The options are read from the `asyncapi` section of the configuration of `apigenie-generator server go`; its other keys configure the generation from OpenAPI documents. ```yaml version: '1.0' commands: generate: server_go: asyncapi: module_path: github.com/acme/events package_name: events initialisms: [SKU] main: true perspective: application ``` | Option | Description | | ------ | ----------- | | `module_path` | Module path of `go.mod` (default: `example.com/<package>`) | | `package_name` | Name of the package, a lower-case Go identifier (default: from `--package-name` or the title) | | `initialisms` | Words written in capitals in identifiers, besides the common ones (`ID`, `URL`, ...) | | `main` | `true` (default): write `cmd/<package>/main.go` when it doesn't exist | | `perspective` | `application` (default): the described application; `counterpart`: its counterpart, receiving what it sends | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0, `server go` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (go version go1.22.5 linux/amd64) | ✓ 7 of 7 operations pass (go version go1.22.5 linux/amd64) | | Release 0.12.0, `server go (counterpart)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (go version go1.22.5 linux/amd64) | ✓ 7 of 7 operations pass (go version go1.22.5 linux/amd64) | | Development version, `server go` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | Development version, `server go (counterpart)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator server kafkajs Source: https://apigenie.pl/docs/reference/generator/server-kafkajs Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a TypeScript (Node.js) Kafka application of an AsyncAPI document, on KafkaJS. ## Usage ```sh apigenie-generator server kafkajs [...OPTIONS] INPUT_FILE ``` ## Description The input must be an AsyncAPI 3.x document. Documents referencing other files are bundled first. The generator handles the Kafka channels: channels of a server whose protocol is `kafka` or `kafka-secure`, or with a `kafka` binding when the document has no servers. Other channels are skipped with an info message. The generated code runs on Node.js with [KafkaJS](https://kafka.js.org) 2.2.4, its only dependency. The application is the one the document describes: it sends the messages of `send` operations and receives those of `receive` operations. Set the `perspective` option to `counterpart` to generate the other side. ```ts import { KafkaApp } from "order-service-kafka-app"; const app = new KafkaApp({ brokers: ["localhost:9092"] }, { handleOrderCommands: { onPlaceOrderMessage: (message) => ({ payload: { requestId: message.payload.requestId, orderId: "o-1" } }), onCancelOrderMessage: () => undefined, }, }); await app.start(); await app.publishStockLevels.sendStockLevelMessage({ key: "ABC-0001", payload: { sku: "ABC-0001", quantity: 3 } }); await app.stop(); ``` `KafkaApp` takes the handlers of all received operations. `start()` connects the producer and the consumers and resolves once every consumer joined its group; `stop()` commits, leaves the groups and disconnects. Each sent operation has a sender property. Every sent operation gets a sender property with a `send<Message>(message)` method per message. It validates the message, sets the constant headers (e.g. `ce_type`) and resolves once the brokers have it. A message is `{ key?, headers, payload }`, with the headers under their names on the wire (`ce_id`). The method of an operation with a `reply` sends the request with a new correlation id unless it has one, and resolves with the reply: the reply message, or `{ name, message }` when there are several. It rejects with `ReplyTimeoutError` when no reply arrives in time (`{ timeoutMs }`, `KafkaOptions.replyTimeoutMs`, 30 seconds by default). Every received operation gets a handler interface: `on<Message>(message, record)` for each of its messages and an optional `onUnknown(record)`. Records are matched to messages by their `ce_type` (or other constant) header, by a constant payload property, or, failing both, by the first message whose payload is valid. The handlers of an operation with a `reply` return the reply (or `undefined` for none), which is sent with the request's correlation id. Invalid records are reported to `KafkaOptions.onError` and skipped. A handler that throws is reported too and the record is retried (KafkaJS doesn't commit it). Payloads and headers are validated against their schemas by generated functions without dependencies; invalid messages throw `MessageValidationError`, whose `issues` point into `/headers` or `/payload`. `KafkaOptions` takes the `brokers`, the producer's `clientId`, `config` (KafkaJS options for every client: `ssl`, `sasl`, `retry`, `logLevel`, ...), `groupIds` replacing the generated consumer groups, `fromBeginning` (true by default), `onError` and `schemaRegistry`. The generated code creates no topics. `src/kafka.ts` lists the SASL and X.509 schemes of each server in `SECURITY`, with the environment variables of their credentials (`KAFKA_SCRAM_USERNAME`, ...), and `securityConfig(server)` turns them into the `ssl` and `sasl` options of `KafkaOptions.config`. Pass it as `new KafkaApp({ brokers: [SERVERS[server]], config: securityConfig(server) }, handlers)`. It throws when the server has schemes and none of them has all its variables set. Strings with `contentEncoding: base64` are `Uint8Array`s in messages and base64 on the wire. Avro payloads (a `schemaFormat` of `application/vnd.apache.avro`) get interfaces for their records and unions of string literals for their enums, in `src/messages.ts`, and are encoded in Avro's binary encoding by `src/avro_runtime.ts`, without dependencies. Their schema id comes from `KafkaOptions.schemaRegistry`. It is either a Confluent-compatible registry, `{ url, username?, password?, timeoutMs? }`, where the schema is registered the first time it is sent (a request times out after `timeoutMs`, 30 seconds by default; a registry that refuses the schema or can't be reached in time rejects the send with an `Error` naming the subject), or a function `(subject, schema) => Promise<number>` returning the id. The message binding's `schemaIdLocation` puts the id before the payload (`payload`, Confluent's format, the default) or in the `apicurio.value.globalId` header (`header`), and its `schemaLookupStrategy` names the subject (`TopicIdStrategy`, the default, gives `<topic>-value`). Received records are decoded with the generated schema. Avro `int` and `long` are `number`s; a received record with a `long` outside JavaScript's safe integers is invalid and goes to `onError`. The package contains `src/types.ts` (payload types), `src/messages.ts` (message and header interfaces), `src/kafka.ts` (servers, topics, ids, senders, handlers and the `KafkaApp`), `src/codecs.ts` (validators and the descriptions of the messages the runtime works with), `src/runtime.ts`, `src/validation_runtime.ts`, `src/avro_runtime.ts` (with Avro payloads only) and `src/index.ts`, with `package.json` and `tsconfig.json`. Not supported, and reported as warnings: topics with parameters, replies at runtime-expression addresses, replies without correlation ids, and security schemes other than `plain`, `scramSha256`, `scramSha512`, `userPassword` and `X509` (such as `gssapi`). [`apigenie-generator client kafkajs`](/docs/reference/generator/client-kafkajs) generates the other side on the same runtime. The design is ADR-120. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | name of the type of a component schema | | `x-apigenie.codegen.disabled` | `true` on a channel or an operation leaves it out (with the operations of a channel left out) | The extensions can live in an overlay for this target instead of in the document, e.g. `kafkajs.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: TypeScript names version: 1.0.0 actions: - target: $.components.schemas.Order update: x-apigenie: codegen: name: PurchaseOrder - target: $.operations.publishAudit update: x-apigenie: codegen: disabled: true ``` ```sh apigenie-generator server kafkajs asyncapi.yaml --overlay kafkajs.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_kafkajs.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. The overlays apply to the AsyncAPI document bundled with the files it references. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the package is generated. ### --package-name Name of the generated package. Defaults to the title of the API followed by `-kafka-app`. It is also the base of the generated consumer group and client ids. ### --package-version Version of the generated package. Defaults to the version of the API. ## Configuration ```yaml version: '1.0' commands: generate: server_kafkajs: layout: package import_extension: .js perspective: application validation: true ``` | Option | Description | | ------ | ----------- | | `layout` | `package` (default): an npm package with sources in `src/`; `sources`: the sources only | | `import_extension` | Extension of relative imports: `.js` (default, Node.js) or an empty string (bundlers) | | `perspective` | `application` (default): the described application; `counterpart`: its counterpart | | `validation` | `true` (default): validate payloads against their schemas; `false`: check the headers only | Unknown options are errors. ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0, `server kafkajs` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | ✓ 7 of 7 operations pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | | Release 0.12.0, `server kafkajs (counterpart)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | ✓ 7 of 7 operations pass (Version 6.0.3, ESLint 10 + typescript-eslint 8, KafkaJS 2.2.4) | | Development version, `server kafkajs` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | | Development version, `server kafkajs (counterpart)` | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator server phoenix (AsyncAPI) Source: https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Phoenix application of the WebSocket and Kafka channels of an AsyncAPI document. ## Usage ```sh apigenie-generator server phoenix [...OPTIONS] INPUT_FILE ``` ## Description `apigenie-generator server phoenix` generates from OpenAPI documents (see [`apigenie-generator server phoenix`](/docs/reference/generator/server-phoenix)) and from AsyncAPI 3.x documents, telling them apart by their `openapi` or `asyncapi` field. Documents referencing other files are bundled first. From an AsyncAPI document it generates a Mix project (Elixir 1.18 or later): the WebSocket channels on [Phoenix](https://www.phoenixframework.org) 1.7 with Bandit, and the Kafka channels on [brod](https://github.com/kafka4beam/brod) and [Broadway](https://hexdocs.pm/broadway_kafka). By default the application is the one the document describes: it sends the messages of `send` operations and receives the messages of `receive` operations. Set the `perspective` option to `counterpart` to swap them; the counterpart has the Kafka channels only, since Phoenix serves WebSocket channels as the application. The project depends on [snappyer](https://hex.pm/packages/snappyer), a NIF that needs a C++ compiler, so that brod reads Snappy-compressed records (the default of Go's franz-go producers); LZ4 and zstd records need `lz4b` or `ezstd` added by hand. The generator writes the channels of servers with the `ws`/`wss` and `kafka`/`kafka-secure` protocols, and channels with a WebSocket or Kafka binding in documents without servers. Channels of other protocols (MQTT, AMQP, HTTP) are skipped and reported as info. ```elixir defmodule MyApp.PickupDesk do @behaviour CarpetExpressEventsWeb.Channels.PickupDesk.Handler alias CarpetExpressEvents.Models @impl true def request_pickup(%Models.PickupRequest{} = request, _session) do # the reply gets the request's requestId when it has none {:reply, %Models.PickupConfirmed{request_id: nil, pickup: book(request)}} end end defmodule MyApp.LabelFarm do @behaviour CarpetExpressEvents.Kafka.RequestLabelRender @impl true def render_label(message, _metadata) do # sent to carpetexpress.label-render.results with the request's correlation id {:reply, %CarpetExpressEvents.Messages.LabelRendered{key: message.key, payload: render(message.payload)}} end end ``` ```elixir # config/config.exs config :carpet_express_events, CarpetExpressEventsWeb.Channels.PickupDesk.Handler, impl: MyApp.PickupDesk ``` The project, for the application `carpet_express_events` (named by `app`, `--package-name` or the document's title): | File | Contents | | ---- | -------- | | `lib/<app>/models/*.ex` | the structs of the schemas the payloads use, decoded and encoded by `decode.ex` and `encode.ex` (as the OpenAPI models of `server phoenix`) | | `lib/<app>/messages/*.ex` | per Kafka message, a struct (`payload`, `headers`, `key`) and the description of its record | | `lib/<app>/avro/*.ex` | the structs of the Avro records and the enums of the payloads, with their schemas | | `lib/<app>/kafka/security.ex` | the security schemes of the Kafka servers and brod's client configuration of each | | `lib/<app>/kafka.ex` | the supervisor of the Kafka processes and a function per topic | | `lib/<app>/kafka/<operation>.ex` | per sent operation, its send (and request) functions; per received operation, the behaviour of its callbacks | | `lib/<app>/kafka/<operation>_consumer.ex` | per received operation, its Broadway pipeline | | `lib/<app>_web/user_socket.ex`, `channels/*.ex` | the socket of the Phoenix clients, a Phoenix channel per WebSocket channel and the behaviour of its callbacks (`channels/<channel>/handler.ex`) | | `lib/<app>_web/security.ex` | the behaviour checking the credentials of the WebSocket channels with security | | `lib/<app>_web/endpoint.ex` | the endpoint: the socket, then the plain WebSockets of the channels | | `lib/<app>/runtime/`, `lib/<app>_web/runtime/` | the runtime of the Kafka processes and of the channels | | `config/*.exs`, `mix.exs`, `.formatter.exs`, `.credo.exs` | the project; `config/runtime.exs` reads `PORT`, `KAFKA_BROKERS`, `KAFKA_SECURITY` and, when Avro payloads are sent, `KAFKA_SCHEMA_REGISTRY_URL` | - **WebSocket channels, two transports.** Each channel is a Phoenix channel: Phoenix clients join its topic on `/socket/websocket`, the address with its parameters as segments (`/tracking/{shipmentId}` is `tracking:<shipmentId>`), with the ws binding's query as the join payload. The same channel is served as a plain WebSocket at its address, where the frames are the messages as the AsyncAPI document describes them (the `prefix` of `<Root>Web.Runtime.PlainSocketPlug` mounts the addresses under a path). Both transports decode the address parameters and the query, call the optional `join/2` callback, decode received messages into their structs before the callbacks get them, and send what the channel module's `push_<message>/2` (one connection) and `broadcast_<message>` (every connection to the topic) functions send. A request's callback returns `{:reply, message}`: the reply of the Phoenix protocol, or a frame on a plain WebSocket, with the request's correlation id copied when it has none. - **Received Kafka operations.** A Broadway pipeline per operation reads its topic in its consumer group and hands each record to a callback of the operation's behaviour (`CarpetExpressEvents.Kafka.PublishShipmentEvents`), named after the message. Several messages of a channel are told apart by a header or a payload property with a distinct constant value (`ce_type`), otherwise by the first message whose payload and headers decode. Records matching no message go to the optional `on_unknown/1`, records that don't decode to the optional `on_invalid/2` (and fail). Batching: `batch_size` and `batch_timeout` from `x-apigenie-broadway` of the operation's (or channel's) Kafka binding, else the `broadway` option, else Broadway's 100 records and 1000 ms; the pipeline module's configuration overrides them, and the consumer group and offset reset policy too. - **Sent Kafka operations.** `send_<message>/1` checks the headers of a message, encodes it and returns once the brokers have the record, keyed by `key`. - **Request/reply on Kafka**, with a reply channel: `request_<message>/2` sends the request with its correlation id (generated when it has none) and waits for the reply (`:timeout`, 30 seconds by default), read by a consumer of the reply topic without consumer group; a replier's callback returns the reply, sent to the reply topic with the request's correlation id. Group ids come from the `groupId` schemas of the Kafka operation bindings (their `const`, single `enum` value, `default` or first example), else `<app in kebab case>-<operation>`. Client ids come from their `clientId` schemas the same way: the brod client of the producers has the application's, `<app in kebab case>` by default, and the Broadway pipelines and the consumers of replies the operation's, else `<app in kebab case>-<operation>`. The partitions, replicas and topic configuration of channel bindings are documented on the topic functions; the generated code creates no topics. Not supported, and reported as warnings: payloads of non-JSON schema formats other than Avro (the messages are skipped, and operations left without a message too), reply addresses given by runtime expressions, Kafka topics with parameters, WebSocket addresses whose segments mix text and parameters, and security schemes a WebSocket handshake can't carry (`userPassword`, `X509`, the SASL schemes). Channels of other protocols (MQTT, AMQP, HTTP) are out of scope. The models check the schemas' constraints, `if`/`then`/`else`, `dependentRequired`, `dependentSchemas` and `not` when they decode a payload. ### Kafka security Each SASL or client certificate scheme of the Kafka servers has a function of `<Root>.Kafka.Security`, named after the scheme key, returning brod's client configuration of the scheme: `kafka_scram(username, password)` for the SASL scheme `kafkaScram` (over TLS on `kafka-secure` servers), `kafka_mtls(cert_file, key_file, ca_file)` for the client certificate of `kafkaMtls`. `client_config(scheme)` takes the credentials from environment variables named after the scheme key, e.g. `KAFKA_SCRAM_USERNAME` and `KAFKA_SCRAM_PASSWORD`, or `KAFKA_MTLS_CERT`, `KAFKA_MTLS_KEY` and `KAFKA_MTLS_CA`. The Kafka supervisor connects with the scheme of its `:security` option, which `config/runtime.exs` reads from `KAFKA_SECURITY`; `:client_config` adds to brod's configuration. ```elixir config :carpet_express_events, :kafka, brokers: "kafka:9093", security: "kafkaScram" ``` ### WebSocket security A channel's security is the schemes of its operations, else of its servers, that a WebSocket handshake carries: API keys in the query, a header or a cookie (`httpApiKey`), basic credentials and bearer tokens (`http` with the `basic` or `bearer` scheme, `oauth2`, `openIdConnect`). A connection to a channel with security is accepted when the implementation of `<Root>Web.Security` accepts its credential of one of the schemes, and refused otherwise: the join of a Phoenix client with `{:error, %{reason: "unauthorized"}}`, the handshake of a plain WebSocket with 401 Unauthorized. `authenticate/2` returns `{:ok, principal}` to accept the connection, and `principal` becomes the session's `principal`; it returns `{:error, reason}` to refuse it. ```elixir defmodule MyApp.Security do @behaviour CarpetExpressEventsWeb.Security # each returns {:ok, merchant} or {:error, :invalid} @impl true def authenticate("streamToken", {:api_key, token}), do: MyApp.Tokens.verify(token) def authenticate("oauth2", {:bearer, token, scopes}), do: MyApp.OAuth.verify(token, scopes) end ``` ```elixir config :carpet_express_events, CarpetExpressEventsWeb.Security, impl: MyApp.Security ``` Without an implementation, connections to channels with security are refused. The headers schema of a channel's ws binding is decoded into `session.params.headers`. Phoenix clients send query parameters as the parameters of the socket or of the join, and only `x-` headers reach Phoenix channels (the endpoint's `connect_info: [:x_headers]`); plain WebSockets get every header. ### Avro payloads A message whose payload is an Avro schema (a `schemaFormat` of `application/vnd.apache.avro`) carries a struct of its record, `lib/<app>/avro/<record>.ex`, with its schema, its fields and their defaults; Avro enums are atoms. The record is written and read by `<Root>.Runtime.Kafka.AvroCodec`, a dependency-free encoder and decoder of the Avro binary encoding with the logical types `date`, `time-*`, `timestamp-*` and `local-timestamp-*` (as `Date`, `Time`, `DateTime` and `NaiveDateTime`). The id of the record's schema goes where the Kafka binding's `schemaIdLocation` says: in the `apicurio.value.globalId` header, or in the payload after a zero byte (the Confluent wire format). The sent schemas are registered in a Confluent-compatible registry, the `schemaRegistryUrl` of the Kafka server by default, under the subject of the binding's `schemaLookupStrategy` (`<topic>-value` by default), the first time each is sent; the `:schema_registry` option of the Kafka supervisor (`url`, `username`, `password`, or a `register` function replacing the requests) and `KAFKA_SCHEMA_REGISTRY_URL` change it. The registry is not asked when reading: the reader's schema is the generated one. Unions are supported when they make a type nullable (`["null", T]`); messages with other unions, with decimals or whose payload is not a record are skipped with a warning, as are request/reply operations with Avro messages. ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the project is generated. ### --package-name Name of the Mix application, converted to snake_case (`carpet-express-events` gives `carpet_express_events`, root module `CarpetExpressEvents`); defaults to the title of the API (`events` when it gives no name). Its kebab case is the base of default group ids. ### --package-version Version of the Mix project; 0.1.0 by default. ### -p, --property Applies to OpenAPI documents only; using it with an AsyncAPI document is an error. ## Configuration The options are read from the `asyncapi` section of the configuration of `apigenie-generator server phoenix`; its other keys configure the generation from OpenAPI documents. ```yaml version: '1.0' commands: generate: server_phoenix: asyncapi: app: carpet_express_events namespace: CarpetExpressEvents perspective: application broadway: { batch_size: 100, batch_timeout: 1000, concurrency: 10 } ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `app` | string | from `--package-name` or the title | Name of the Mix application (snake_case) | | `namespace` | string | the application in PascalCase | Root module of the generated modules; the web modules are in `<Root>Web` | | `perspective` | `application` \| `counterpart` | `application` | The described application, or its counterpart, receiving what it sends | | `field_prefix` | string | `field_` | Prefix of struct fields whose property names give no valid name | | `module_overrides` | map | | Module names of payload schemas, e.g. `ShipmentId: ShipmentRef` | | `dev_deps` | boolean | `true` | credo and dialyxir as dependencies of the dev and test environments | | `broadway` | map | | `batch_size`, `batch_timeout` (ms) and `concurrency` of the pipelines | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0, `server phoenix` | ✓ snapshots of 3.0; 41 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 11 of 11 operations pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | | Release 0.12.0, `server phoenix (counterpart)` | ✓ snapshots of 3.0; 30 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 11 of 11 operations pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | | Development version, `server phoenix` | ✓ snapshots of 3.0; 41 supported, 0 not yet | runs before a release | runs before a release | | Development version, `server phoenix (counterpart)` | ✓ snapshots of 3.0; 30 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator server spring (AsyncAPI) Source: https://apigenie.pl/docs/reference/generator/server-spring-asyncapi Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a Spring Boot application of the Kafka channels of an AsyncAPI document. ## Usage ```sh apigenie-generator server spring [...OPTIONS] INPUT_FILE ``` ## Description `apigenie-generator server spring` generates from OpenAPI documents (see [`apigenie-generator server spring`](/docs/reference/generator/server-spring)) and from AsyncAPI 3.x documents, telling them apart by their `openapi` or `asyncapi` field. Documents referencing other files are bundled first. From an AsyncAPI document it generates a Maven project of a Spring Boot 3 application using [Spring for Apache Kafka](https://spring.io/projects/spring-kafka). By default the application is the one the document describes: it sends the messages of `send` operations and receives the messages of `receive` operations. Set the `perspective` option to `counterpart` to swap them. The generator has one part per protocol. Today it generates the Kafka channels: the channels of servers with the `kafka` or `kafka-secure` protocol, and channels with a Kafka binding in documents without servers. Channels of other protocols are skipped and reported as info. ```java @Component class LabelFarm implements RequestLabelRenderHandler { @Override public RequestLabelRenderReply onRenderLabel(RenderLabel message) { LabelRenderResult result = render(message.payload()); return new LabelRendered(message.key(), result, new LabelRenderedHeaders(null)); } } @Service class Shipments { private final PublishShipmentEventsSender events; void delivered(String shipmentId, ShipmentDeliveredData data, ShipmentDeliveredHeaders headers) { events.sendShipmentDelivered(new ShipmentDelivered(shipmentId, data, headers)); } } ``` The generated code has: - **models** (package `model`): a record per object schema the messages use, with Jackson and Jakarta Bean Validation annotations (`@NotNull` for required properties, `@Valid`, `@Pattern`, `@Size`, `@Min`/`@Max`, `@DecimalMin`/`@DecimalMax`, `@Email`); an enum per enumeration; a sealed interface per `oneOf` of objects (`@JsonTypeInfo` by the `discriminator` property, or by deduction). `allOf` members are merged into one record. Schemas under `#/components/schemas` keep their name; inline schemas are named after their message (`PlaceOrderPayload`) or their owner and property (`LabelRenderRequestFormat`). - **messages** (package `messages`): a record per message with its Kafka `key`, its `payload` and its `headers`, and a headers record with the message's headers, the headers of its traits merged as AsyncAPI does (JSON Merge Patch: a later `required` list replaces an earlier one). Headers with a constant value, e.g. the `ce_specversion` and `ce_type` of CloudEvents in binary mode, are constants of the headers record (`ShipmentStatusChangedHeaders.CE_TYPE`), which senders write and listeners compare. The key is a `String` validated by the key schema of the Kafka message binding. - **Kafka** (package `kafka`): - for every received operation, a handler interface (`ConsumeOrdersHandler`) with an `on<Message>` method per message, which you implement as a Spring bean, and a listener (`ConsumeOrdersListener`) with a `@KafkaListener` method. Several messages of a channel are told apart by a payload property or a header with a distinct constant value (e.g. `type` or `ce_type`); otherwise the first message whose payload is valid is chosen. Records matching no message go to `onUnknown`, which ignores them by default. - for every sent operation, a sender (`PublishShipmentEventsSender`) with a `send<Message>(message)` method per message, over a `KafkaTemplate` using the operation's client id. - request/reply operations with a reply channel: the requester's sender uses a `ReplyingKafkaTemplate` listening on the reply channel's topic and returns `CompletableFuture<<Operation>Reply>`, a sealed interface of the reply messages. Replies are matched by the header of the request message's `correlationId`, generated when the request has none. A replier's handler returns the reply, which the listener sends to the reply topic with the request's correlation id copied (from a header or a payload property, as the `correlationId` locations say). - `KafkaJson`, converting payloads (JSON) and headers (UTF-8 text) and validating messages, and `KafkaTopicsConfiguration`, creating the topics of the channels from their Kafka bindings (partitions, replicas, `topicConfiguration`) when `asyncapi.kafka.create-topics` is `true`. - **project files**: `pom.xml` (parent `spring-boot-starter-parent`, `spring-boot-starter`, `spring-boot-starter-json`, `spring-boot-starter-validation` (with `bean_validation`), `spring-kafka`, and the test starters), the `@SpringBootApplication` class and `src/main/resources/application.yaml`. `application.yaml` points `spring.kafka.bootstrap-servers` to the first Kafka server (server variables replaced by their default) and configures String keys and byte array values. The `asyncapi.kafka` section holds every Kafka server, the topic of every channel and the group and client ids of every operation, which the generated code reads, so that they can be changed without regenerating: ```yaml asyncapi: kafka: create-topics: false servers: production-kafka: bootstrap-servers: kafka-eu.events.carpetexpress.example:9093 schema-registry-url: https://schemas.events.carpetexpress.example channels: shipment-events: topic: carpetexpress.shipment-events.v2 operations: consume-carrier-scans: group-id: tracking-ingest client-id: carpet-express-consume-carrier-scans ``` ### Security Each SASL or client certificate scheme of the Kafka servers gets a Spring profile named after its key in kebab case, e.g. `kafka-scram` for `kafkaScram`, as a document of `application.yaml`. Start the application with the profile (`--spring.profiles.active=kafka-scram`) to connect with the scheme; without one, it connects without security. The credentials come from environment variables named after the scheme key, e.g. `KAFKA_SCRAM_USERNAME` and `KAFKA_SCRAM_PASSWORD`: | Scheme | Profile settings | | ------ | ---------------- | | `scramSha256`, `scramSha512` | `spring.kafka.security.protocol` `SASL_SSL` (`SASL_PLAINTEXT` on `kafka` servers), `sasl.mechanism` and a `ScramLoginModule` `sasl.jaas.config` with `<KEY>_USERNAME` and `<KEY>_PASSWORD` | | `plain`, `userPassword` | the same with `PLAIN` and `PlainLoginModule` | | `X509` | `spring.kafka.security.protocol` `SSL` and an SSL bundle (`spring.kafka.ssl.bundle`) of the PEM files `<KEY>_CERT` (the client certificate), `<KEY>_KEY` (its private key) and `<KEY>_CA` | A scheme shared by servers with different protocols gets one profile, with the protocol of the first of them, and a warning names both servers. ```yaml --- spring: config: activate: on-profile: kafka-scram kafka: security: protocol: SASL_SSL properties: sasl.mechanism: SCRAM-SHA-512 sasl.jaas.config: org.apache.kafka.common.security.scram.ScramLoginModule required username="${KAFKA_SCRAM_USERNAME}" password="${KAFKA_SCRAM_PASSWORD}"; ``` Other scheme types, such as `gssapi`, are left out with a warning. ### Avro payloads A message whose `schemaFormat` is an Avro one (`application/vnd.apache.avro;version=1.9.0`, with or without `+json` or `+yaml`) carries the Avro class of its record schema as its payload. The schema is written to `src/main/avro/<full name>.avsc` and the `avro-maven-plugin` generates the class (strings as `String`) when the project builds. A schema without a `namespace` gets `<base package>.avro`; a root schema that isn't a record is skipped with a warning. The generated `KafkaAvro` bean encodes and decodes the payloads in Avro's binary encoding, with the id of the writer's schema where the Kafka binding of the message says: before the payload (`schemaIdLocation: payload`, Confluent's wire format) or in the `apicurio.value.globalId` header (`schemaIdLocation: header`). Senders get the id from a schema registry, by the subject of `schemaLookupStrategy` (`TopicIdStrategy`, `{topic}-value`, by default): - a `KafkaAvro.SchemaRegistry` bean, when the application defines one; - otherwise the Confluent-compatible registry at the `schema-registry-url` of the first Kafka server, with the basic authentication of `asyncapi.kafka.schema-registry.username` and `password`. It registers each schema once with `POST /subjects/{subject}/versions`. ```java @Bean KafkaAvro.SchemaRegistry schemaRegistry() { return KafkaAvro.confluent("https://schemas.events.carpetexpress.example", "ingest", System.getenv("REGISTRY_PASSWORD")); } ``` Listeners decode records with the schema of the generated class, so the writer's schema must be the same. A record that isn't a payload of it fails with an `IllegalArgumentException`, or goes to `onUnknown` when the channel has several messages. A correlation id at a payload pointer of an Avro message is left out with a warning. Group and client ids come from the `groupId` and `clientId` schemas of the Kafka operation bindings, of the operation or its traits: their `const`, single `enum` value, `default` or first example. Without a value, `<artifact id>-<operation>` is used, with a comment naming the binding's pattern. Constraints Bean Validation can't express are line comments of the record or component: draft-07 `dependencies`, `if`/`then`/`else`, `not`, tuples (`items` arrays, mapped to `List` with `@Size`), `patternProperties`, `const` values, and `anyOf`/`oneOf` branches constraining the properties of an object. Not supported, and reported as warnings: payloads of non-JSON schema formats other than Avro (Protobuf, RAML) (the messages are skipped, and operations left without a message too), reply addresses given by runtime expressions, Kafka topics with parameters, and security schemes other than `plain`, `scramSha256`, `scramSha512`, `userPassword` and `X509` (such as `gssapi`). With a correlation id in the payload, the replier's reply must carry the property (the listener overwrites it with the request's), and a requester matches replies by the `kafka_correlationId` header, which the replier must copy. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | name of the class of a schema | | `x-apigenie.codegen.disabled` | `true` on a channel or an operation leaves it out (with the operations of a channel left out) | The extensions can live in an overlay for this target instead of in the document, e.g. `spring.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: Java names version: 1.0.0 actions: - target: $.components.schemas.Order update: x-apigenie: codegen: name: PurchaseOrder ``` ```sh apigenie-generator server spring asyncapi.yaml --overlay spring.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_spring.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. The overlays apply to the AsyncAPI document bundled with the files it references. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the project is generated. ### --package-name Maven artifact id of the project. Defaults to the title of the API in kebab case. The base package defaults to `com.example.` followed by the artifact id in lower case without other characters than letters and digits (prefixed with `app` when it starts with a digit or is a Java keyword). ### --package-version Version of the project. Defaults to the version of the API. ### -p, --property Applies to OpenAPI documents only; using it with an AsyncAPI document is an error. ## Configuration The options are read from the `asyncapi` section of the configuration of `apigenie-generator server spring`; its other keys configure the generation from OpenAPI documents. ```yaml version: '1.0' commands: generate: server_spring: asyncapi: base_package: com.acme.events group_id: com.acme java_version: 21 spring_boot_version: 3.3.13 bean_validation: true perspective: application ``` | Option | Description | | ------ | ----------- | | `base_package` | Package of the generated code (default: `com.example.<artifact id>`); models are in `.model`, messages in `.messages`, the Kafka code in `.kafka` | | `group_id` | Maven group id (default: the base package) | | `java_version` | Java release, 17 (default) or later | | `spring_boot_version` | Version of the Spring Boot 3 parent (default `3.3.13`) | | `bean_validation` | `true` (default): Bean Validation annotations, and validation of sent and received messages; `false`: none | | `perspective` | `application` (default): the described application; `counterpart`: its counterpart, receiving what it sends | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.0; 31 supported, 0 not yet | ✓ pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | ✓ 5 of 5 operations pass (openjdk version "21.0.13" 2026-10-20 LTS, Apache Maven 3.10.0) | | Development version | ✓ snapshots of 3.0; 31 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator server ws Source: https://apigenie.pl/docs/reference/generator/server-ws Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate a TypeScript (Node.js) server of the WebSocket channels of an AsyncAPI document. ## Usage ```sh apigenie-generator server ws [...OPTIONS] INPUT_FILE ``` ## Description The input must be an AsyncAPI 3.x document. Documents referencing other files are bundled first. The server serves the WebSocket channels of the document (see [`apigenie-generator client ws`](/docs/reference/generator/client-ws)) at their addresses, using the [ws](https://github.com/websockets/ws) package. By default it implements the application the document describes: it sends the messages of `send` operations and receives the messages of `receive` operations. Set the `perspective` option to `counterpart` to swap them. ```ts import { createServer } from "chat-api-server"; const server = createServer({ room: { onConnect(session) { console.log(`joined ${session.params.roomId}`); }, onJoin(session, payload) { session.sendRoomEvent({ kind: "joined", user: payload.user }); }, }, }); await server.listen(8080); ``` For every channel, the generated code has: - a session class (`RoomSession`): a connection of a client, with the values of the address parameters (`params`), the query parameters converted to the types of the WebSocket binding (`query`), the handshake `headers`, the headers of the WebSocket binding typed by its schema (`bindingHeaders`), what the authenticator returned (`principal`, see below), `send<Message>(payload)` methods and `close()`. The reply messages of an operation whose `reply` is on the same channel get `send<Message>` methods too, and, when the request and reply messages have a correlation id in their payloads, `replyTo<Operation>(request, reply)` sends the reply with the request's correlation id copied into it (e.g. `session.replyToRequestPickup(request, confirmation)`). - a handler interface (`RoomHandler`) with `onConnect`, `on<Message>` for every message the server receives (when the channel receives one message, or when its messages can be told apart by a property with a distinct constant value), `onMessage` for every message of a channel receiving several, `onUnknownMessage`, `onClose` and `onError` The handlers of a session are called one at a time, in the order of the events; a handler returning a promise delays the next one until it settles. Errors thrown by handlers are passed to `onError`. `createServer(handlers, options)` serves the channels with handlers. Connections to other addresses are rejected with status 404, and handshakes without a header that the headers schema of the channel's WebSocket binding requires with status 400. Options are an existing HTTP server to attach to (`server`), a path prefix of all addresses (`basePath`), the authenticators of the security schemes (`authenticate`) and `onAuthenticationError(error, request)`, called when an authenticator throws or an authenticated connection can't be accepted (by default, `console.error`). The result has `listen(port, host)`, `close()`, `address()` and `httpServer`. ### Security A channel takes the security schemes of its operations, or of its servers for an operation without any. When a channel has some, the `authenticate` option is required: an `Authenticators` object with a function per scheme, called with the credential that the handshake carries and a context with the scheme key, the scheme, its scopes, the HTTP request and the address parameters. The connection is accepted when the authenticator of one of the channel's schemes returns a value other than `false`, `null` or `undefined`; that value becomes `session.principal`. Otherwise the handshake is refused with status 401. When the authenticator throws or rejects, the handshake is refused with status 500 and the error goes to `onAuthenticationError`. ```ts const server = createServer(handlers, { authenticate: { streamToken: (token) => tokens.verify(token), // the merchant, or undefined oauth2: async (token, { scopes }) => introspect(token, scopes), }, }); ``` The credential is read from the handshake by the type of the scheme: | Scheme | Credential | | ------ | ---------- | | `httpApiKey` | the query parameter, header or cookie named by `name` and `in` | | `http` with scheme `basic` | `user:password` of the `Authorization` header | | `http` with scheme `bearer`, `oauth2`, `openIdConnect` | the bearer token of the `Authorization` header, or of the `access_token` query parameter | The authenticator checks the scopes; the server doesn't. Other scheme types, such as `userPassword`, `X509` or the SASL schemes, can't be sent with a WebSocket handshake: they are left out with a warning. The generated package contains `src/types.ts`, `src/messages.ts`, `src/server.ts`, `src/metadata.ts`, `src/runtime.ts` and `src/index.ts`, with `package.json` (depending on `ws`) and `tsconfig.json`. Not supported, and reported as warnings: replies on another channel or at a runtime-expression address, channels without an address, and channels sharing an address with another channel (only the first one is served), and security schemes that a WebSocket handshake can't carry. ## Extensions | Extension | Effect | | --------- | ------ | | `x-apigenie.codegen.name` | on a channel: the base of its names (`LobbyHandler`); on a message: the base of its types (`PostPayload`); on a component schema: the name of its type | | `x-apigenie.codegen.disabled` | `true` on a channel or an operation leaves it out (with the operations of a channel left out) | The extensions can live in an overlay for this target instead of in the document, e.g. `ws.overlay.yaml`: ```yaml overlay: 1.0.0 info: title: WebSocket names version: 1.0.0 actions: - target: $.channels.room update: x-apigenie: codegen: name: Lobby - target: $.components.messages.ChatMessage update: x-apigenie: codegen: name: Post ``` ```sh apigenie-generator server ws asyncapi.yaml --overlay ws.overlay.yaml -o out ``` ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --overlay OVERLAY Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those listed under `commands.generate.server_ws.overlay` in the configuration file (with paths relative to it). Warnings and errors about a value an overlay set point to the overlay. The overlays apply to the AsyncAPI document bundled with the files it references. ### --strict Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated) instead of a warning (`OVERLAY:LINE:COL: action #N (TARGET) selects no nodes.`). ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the package is generated. ### --package-name Name of the generated package. Defaults to the title of the API followed by `-server`. ### --package-version Version of the generated package. Defaults to the version of the API. ## Configuration ```yaml version: '1.0' commands: generate: server_ws: layout: package import_extension: .js perspective: application ``` | Option | Description | | ------ | ----------- | | `layout` | `package` (default): an npm package with sources in `src/`; `sources`: the sources only | | `import_extension` | Extension of relative imports: `.js` (default, Node.js) or an empty string (bundlers) | | `perspective` | `application` (default): the described application; `counterpart`: its client | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express AsyncAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#asyncapi). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of 3.0; 30 supported, 0 not yet | ✓ pass (Version 6.0.3, ESLint 10 + typescript-eslint 8) | ✓ 4 of 4 operations pass (node) | | Development version | ✓ snapshots of 3.0; 30 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator client elixir (Protobuf) Source: https://apigenie.pl/docs/reference/generator/client-elixir-protobuf Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate an Elixir gRPC client on [elixir-grpc](https://hexdocs.pm/grpc) from a `.proto` file and the files it imports. ## Usage ```sh apigenie-generator client elixir [...OPTIONS] INPUT_FILE.proto ``` ## Description `client elixir` generates a gRPC client when its input is a `.proto` file (an OpenAPI document gives a Req client, see [client elixir](/docs/reference/generator/client-elixir)). The input is the file declaring the services; the files it imports are looked up in the directories of `--proto-path`, then next to it, and `google/protobuf`, `google/api` and `google/rpc` imports need no files. Only proto3 files are read. The generator writes a Mix project (Elixir 1.18 or later) depending on `grpc` 1.0 with Mint, and `protobuf` 0.17. Its code passes `mix format --check-formatted`, `mix compile --warnings-as-errors`, `mix credo --strict` and `mix dialyzer`. No protoc is needed: the modules of the messages, services and stubs are those protoc-gen-elixir would write, named the same way (see [server elixir-grpc](/docs/reference/generator/server-elixir-grpc)). | File | Contents | | ---- | -------- | | `lib/proto/<path>.pb.ex` | per `.proto` file, a module per message, map entry and enum, and the `<Service>.Service` and `<Service>.Stub` modules of each service | | `lib/<app>.ex` | the root module: `connect/2`, the types of options and results | | `lib/<app>/<service>.ex` | a module per service, with a function per method | | `lib/<app>/validation.ex` | `<Root>.Validation`, the checks of the required fields, when a request has some (since 0.12.0) | | `mix.exs`, `.formatter.exs`, `.gitignore`, `README.md` | the project | ```elixir {:ok, channel} = CarpetExpressClient.connect("localhost:50051") {:ok, shipment} = CarpetExpressClient.ShipmentService.get_shipment( channel, %Carpetexpress.V1.GetShipmentRequest{id: "sh_1"}, timeout: 5_000, metadata: %{"x-tenant" => "acme"} ) ``` ### Functions A method is a function named as GRPC.Stub names it (`GetShipment` is `get_shipment/3`): | Method | Arguments | Returns | | ------ | --------- | ------- | | unary | channel, request, options | `{:ok, response}` or `{:error, %GRPC.RPCError{}}` | | server streaming | channel, request, options | `{:ok, stream}`: an `Enumerable` of `{:ok, message}` and `{:error, %GRPC.RPCError{}}` items; `{:error, %GRPC.RPCError{}}` for a request without a required field | | client streaming | channel, `Enumerable` of requests, options | `{:ok, response}` or `{:error, %GRPC.RPCError{}}`; raises `GRPC.RPCError` for a request without a required field | | bidirectional streaming | channel, `Enumerable` of requests, options | like server streaming; the requests are sent from a task while the responses arrive, and the responses end early after a request without a required field | The options are those of GRPC.Stub: `:timeout` (milliseconds; 10 seconds for unary calls) or `:deadline` (a `DateTime`), `:metadata` (a map of headers) and `:compressor`. `connect/2` passes its options to `GRPC.Stub.connect/2` with the Mint adapter unless `:adapter` names another one. The Stub modules remain available for calls the functions don't cover, e.g. interleaving the requests and responses of a bidirectional stream. Deprecated methods are `@deprecated`. ### Required fields Since 0.12.0, the client checks a request before it sends it. A request without a field marked `(google.api.field_behavior) = REQUIRED` isn't sent: the function returns `{:error, %GRPC.RPCError{}}` with the INVALID_ARGUMENT status and a message naming the path of the first missing field, e.g. `shipment.sender is required`. The rules of a missing field are those of [server elixir-grpc](/docs/reference/generator/server-elixir-grpc#required-fields). The requests of a client or bidirectional stream are checked one by one as they are sent, so the requests before a failing one have already been sent. The call is then cancelled: - a client stream raises the `GRPC.RPCError` in the calling process; - the responses of a bidirectional stream end early, and the sending task logs the error. The checks are in `<Root>.Validation`: `validate/1` returns `:ok` or `{:error, reason}`, `check/1` returns `:ok` or `{:error, %GRPC.RPCError{}}`, and `validate!/1` returns the message or raises the error. A message without required fields is valid. A service named `Validation` becomes `<Root>.Validation2` when the module is generated. ### Limitations - `extend` blocks aren't generated; a warning names the file. ## Options ### -I, --proto-path DIR Directory searched for the imported files, like protoc's `--proto_path`. Can be repeated. Given with an OpenAPI input, it is an error. ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the project is generated. ### --package-name Name of the Mix application, converted to snake_case (`carpet-express-client` gives `carpet_express_client` and the root module `CarpetExpressClient`). Defaults to the name of the output directory. ### --package-version Version of the Mix project; `0.1.0` by default. ### -p, --property NAME=VALUE Sets a generator option (see below), e.g. `-p package_prefix=acme.proto`. Options given on the command line take precedence over the configuration file. ## Configuration The options are in the `protobuf` section of `client_elixir`; the others concern OpenAPI input. ```yaml version: '1.0' commands: generate: client_elixir: protobuf: app: carpet_express_client dev_deps: false ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `app` | string | name of the output directory | Name of the Mix application (snake_case, the directory under `lib/`); also set by `--package-name`. | | `namespace` | string | the application in PascalCase | Root module of the client's modules, e.g. `CarpetExpressClient`. | | `package_prefix` | string | | Prepended to the package in the names of the modules of messages, enums and services, like protoc-gen-elixir's `package_prefix`. | | `dev_deps` | boolean | `true` | Lists credo and dialyxir as dependencies of `mix.exs` (`only: :dev`). | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express Protobuf fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#protobuf). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of proto3; 42 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 24 of 24 operations pass (elixir) | | Development version | ✓ snapshots of proto3; 42 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator server elixir-grpc Source: https://apigenie.pl/docs/reference/generator/server-elixir-grpc Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate an Elixir gRPC server on [elixir-grpc](https://hexdocs.pm/grpc_server) from a `.proto` file and the files it imports. ## Usage ```sh apigenie-generator server elixir-grpc [...OPTIONS] INPUT_FILE ``` ## Description The input is the `.proto` file declaring the services. The files it imports are looked up in the directories of `--proto-path`, then next to it; `google/protobuf`, `google/api` and `google/rpc` imports need no files. Only proto3 files are read. The generator writes a Mix project (Elixir 1.18 or later) depending on `grpc_server` 1.0 and `protobuf` 0.17. Its code passes `mix format --check-formatted`, `mix compile --warnings-as-errors`, `mix credo --strict` and `mix dialyzer`. No protoc is needed: the modules of the messages are those protoc-gen-elixir would write. | File | Contents | | ---- | -------- | | `lib/proto/<path>.pb.ex` | per `.proto` file, a module per message, map entry and enum (`use Protobuf`), and a `<Service>.Service` module per service (`use GRPC.Service`) | | `lib/<app>/<service>.ex` | a behaviour per service, with a callback per method | | `lib/<app>/<service>/server.ex` | the `GRPC.Server` of the service, calling the configured implementation | | `lib/<app>/validation.ex` | `<Root>.Validation`, the checks of the required fields, when a request has some (since 0.12.0) | | `lib/<app>/endpoint.ex`, `application.ex` | the endpoint running the servers, and the application starting it | | `config/config.exs`, `config/runtime.exs` | the port (50051, or `PORT`) | | `mix.exs`, `.formatter.exs`, `.gitignore`, `README.md` | the project | ```sh mix deps.get mix run --no-halt ``` ### Messages Modules are named as protoc-gen-elixir names them: the package camelized segment by segment, then the message (`carpetexpress.v1.Shipment.Parcel` is `Carpetexpress.V1.Shipment.Parcel`). The `(elixirpb.file).module_prefix` option of a file, or the `package_prefix` option of the generator, change the prefix. Fields are declared with `field` and the options protoc-gen-elixir writes (`repeated`, `proto3_optional`, `json_name`, `map`, `enum`, `oneof`, `packed`, `deprecated`), oneofs with `oneof`. Comments become `@moduledoc` and `#` comments. Well-known types are the modules of the `protobuf` package (`Google.Protobuf.Timestamp`, ...), the types of `google/api`, `google/rpc` and `google/type` those of `googleapis`. ### Services A service is a behaviour, `<Root>.<Service>`, with a callback per method named as GRPC.Server names it (`GetShipment` is `get_shipment/2`). Implement it and configure the implementation: ```elixir config :carpet_express, CarpetExpress.ShipmentService, impl: MyApp.ShipmentService ``` ```elixir defmodule MyApp.ShipmentService do @behaviour CarpetExpress.ShipmentService @impl true def get_shipment(request, _stream), do: MyApp.Shipments.fetch!(request.id) @impl true def import_shipments(requests, _stream) do imported = requests |> Enum.map(&MyApp.Shipments.book/1) |> length() %Carpetexpress.V1.ImportShipmentsResponse{imported: imported} end # ... end ``` A callback receives the request, or an `Enumerable` of the requests of a client or bidirectional stream, and the `GRPC.Server.Stream` of the call. It returns the response, or an `Enumerable` of the responses of a server or bidirectional stream, which the server sends one by one. Raising `GRPC.RPCError` answers with its status. Methods without an implementation answer UNIMPLEMENTED. ### Required fields Since 0.12.0, the server checks the fields marked `(google.api.field_behavior) = REQUIRED`, which protobuf-elixir doesn't know. A request without a required field is answered with INVALID_ARGUMENT, the status [AIP-203](https://google.aip.dev/203) asks for, and a message naming the path of the first missing field, e.g. `shipment.sender is required`. The implementation isn't called. A field is missing when it holds its default value, because protobuf-elixir can't tell an unset field from one set to its default: - a string or bytes field: `nil` or `""`; - a number: `nil` or `0` (`0.0` for `float` and `double`); - a bool: anything but `true`; - an enum: `nil`, `0` or its zero value; - a message field or a proto3 `optional` field: `nil` (so an `optional` field set to `""` or `0` counts as set); - a repeated field: `[]`, and a map: `%{}`; - a member of a `oneof`: when the `oneof` holds another member, or none. The required fields of the messages in a request's fields are checked too, in lists and map values as well. A message with a `google.protobuf.FieldMask` field is a partial update ([AIP-134](https://google.aip.dev/134)): only its own required fields are checked, not those of the messages in its fields. The requests of a client or bidirectional stream are checked one by one as the implementation reads them, so it may already have handled the earlier ones when a missing field ends the call. `<Root>.Validation.validate/1` returns `:ok` or `{:error, reason}`, `check/1` returns `:ok` or `{:error, %GRPC.RPCError{}}`, and `validate!/1` returns the message or raises the `GRPC.RPCError`. A message without required fields is valid. They are there for the implementation's own use too, e.g. on the messages it builds. A service named `Validation` becomes `<Root>.Validation2` when the module is generated. ### Limitations - `extend` blocks (custom options, proto2-style extensions) aren't generated; a warning names the file. - HTTP/JSON transcoding (`google.api.http`) isn't turned on. ## Options ### -I, --proto-path DIR Directory searched for the imported files, like protoc's `--proto_path`. Can be repeated. ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the project is generated. ### --package-name Name of the Mix application, converted to snake_case (`carpet-express` gives `carpet_express` and the root module `CarpetExpress`). Defaults to the name of the output directory. ### --package-version Version of the Mix project; `0.1.0` by default. ### -p, --property NAME=VALUE Sets a generator option (see below), e.g. `-p dev_deps=false`. Options given on the command line take precedence over the configuration file. ## Configuration ```yaml version: '1.0' commands: generate: server_elixir_grpc: app: carpet_express package_prefix: carpet_express.proto ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `app` | string | name of the output directory | Name of the Mix application (snake_case, the directory under `lib/`); also set by `--package-name`. | | `namespace` | string | the application in PascalCase | Root module of the modules of the application (behaviours, servers, endpoint), e.g. `CarpetExpress`. | | `package_prefix` | string | | Prepended to the package in the names of the modules of messages, enums and services, like protoc-gen-elixir's `package_prefix`. | | `dev_deps` | boolean | `true` | Lists credo and dialyxir as dependencies of `mix.exs` (`only: :dev`). | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express Protobuf fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#protobuf). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of proto3; 42 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 31 of 31 operations pass (elixir) | | Development version | ✓ snapshots of proto3; 42 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-generator server absinthe Source: https://apigenie.pl/docs/reference/generator/server-absinthe Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md). Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [client swift](https://apigenie.pl/docs/reference/generator/client-swift.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md). [Tier 2](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification) Generate an [Absinthe](https://hexdocs.pm/absinthe) server from a GraphQL schema (SDL). ## Usage ```sh apigenie-generator server absinthe [...OPTIONS] INPUT_FILE ``` The input is a GraphQL schema: a `.graphql`, `.graphqls` or `.gql` file. It must be valid and self-contained, and have a query type. ## Description The generator writes a Mix project (Elixir 1.18 or later) that depends on Absinthe 1.12, Absinthe.Plug, Plug, Bandit and Jason, and on WebSock 0.5 when the schema has a subscription type. The code passes `mix format --check-formatted`, `mix compile --warnings-as-errors` and `mix credo --strict`, and `mix run --no-halt` serves it. | File | Contents | | ---- | -------- | | `priv/graphql/schema.graphql` | the schema, as written | | `lib/<app>/schema.ex` | the schema module: `import_sdl` of the schema, and `hydrate/2` attaching resolvers, type resolution and scalars | | `lib/<app>/schema/directives.ex` | the custom directives of the schema, declared in a prototype schema | | `lib/<app>/resolvers/<type>.ex` | a behaviour per object type with root fields or fields with arguments, with a callback per field | | `lib/<app>/resolvers.ex` | the lookup of the configured implementations | | `lib/<app>/type_resolver.ex` | the object types of the values of interfaces and unions | | `lib/<app>/scalars.ex` | the parsing and serialization of the custom scalars | | `lib/<app>/loader.ex` | the Dataloader source, with the `dataloader` option | | `lib/<app>/router.ex` | the Plug router: the GraphQL endpoint, and GraphiQL in the dev environment | | `lib/<app>/socket.ex` | the WebSocket handler of subscriptions, when the schema has a subscription type (since 0.12.0) | | `lib/<app>/pub_sub.ex` | the pubsub of subscriptions, with `publish/2`, when the schema has a subscription type (since 0.12.0) | | `lib/<app>/application.ex` | the application, starting Bandit, and the pubsub first when the schema has a subscription type | ### The schema `<Root>.Schema` imports the schema from `priv/graphql/schema.graphql` with `import_sdl`, and recompiles when the file changes. Absinthe keeps everything the schema says: - descriptions of types, fields, arguments, enum values and input fields; - deprecations of fields, arguments, input fields and enum values; - default values, interfaces implementing interfaces, and `@oneOf` input types, which it enforces; - type extensions. Two things need code next to the SDL: - **Custom directives** need a prototype schema. Absinthe applies only the directives its prototype schema declares, so `<Root>.Schema.Directives` declares the directives of the schema, along with the enums their arguments use. - **Custom scalars** need parse and serialize functions, which `hydrate/2` attaches. ### Resolvers and implementations Root fields, and fields with arguments, are resolved by the module of their type: `<Root>.Resolvers.Query`, `<Root>.Resolvers.Mutation`, `<Root>.Resolvers.Warehouse`... Each one is a behaviour with a callback per field: - a root field's callback receives the arguments (a map with atom keys, as Absinthe gives them) and the resolution; - a nested field's callback receives the parent value first. ```elixir @callback track_shipment(args :: track_shipment_args(), resolution :: Absinthe.Resolution.t()) :: Resolvers.result() ``` Implement the behaviours and configure the implementations in `config/config.exs`. Regenerating never overwrites them: ```elixir config :carpet_express, CarpetExpress.Resolvers.Query, impl: MyApp.Query ``` A callback returns `{:ok, value}` or `{:error, reason}`. Fields without an implementation answer an error ("Query.trackShipment is not implemented"). The other fields read their value from the parent value with Absinthe's default resolution: the key that is the snake_case name of the field, in a map or a struct. ### Interfaces and unions `<Root>.TypeResolver` resolves the object type of a value of an interface or a union: - a map with a `__typename` key resolves to the type it names; - other values go to the `resolve_type(type, value, resolution)` callback of the implementation configured for `<Root>.TypeResolver`. ### Scalars `<Root>.Scalars` has a `parse_<scalar>/1` and a `serialize_<scalar>/1` function per custom scalar. Until an implementation of its `parse/2` and `serialize/2` callbacks is configured, they pass string, number and boolean literals and values through as they are. ### Router and GraphiQL `<Root>.Router` parses JSON, form and multipart bodies (`Absinthe.Plug.Parser`) and forwards the endpoint's path (`/graphql`) to `Absinthe.Plug`, which takes queries and mutations by POST and GET. When the application's `:graphiql` setting is true, as `config/dev.exs` sets it, the router also serves GraphiQL at `/graphiql`. Bandit listens on `127.0.0.1:4000` in development and on all interfaces in production; the `PORT` environment variable sets the port. ### Subscriptions Since 0.12.0, the server serves subscriptions over a WebSocket at the GraphQL endpoint (`path`, `/graphql` by default), with the graphql-transport-ws protocol of the [graphql-ws](https://github.com/enisdenjo/graphql-ws) library. The router upgrades a request at that path (with or without a trailing slash) whose `Upgrade` header is `websocket` and whose `Sec-WebSocket-Protocol` lists `graphql-transport-ws`. A request for the legacy subscriptions-transport-ws protocol (subprotocol `graphql-ws`) isn't upgraded. `<Root>.Socket` then handles the connection. The client has 3 seconds to send `connection_init`, which the server answers with `connection_ack`. Each `subscribe` message runs its document: - a subscription sends a `next` message per published value until the client sends `complete`; - a query or a mutation sends one `next` and a `complete`; - a document that doesn't parse or validate, or whose resolver raises, sends an `error` message; the connection and its other subscriptions go on. A raise sends "Internal server error", and the server logs the exception. A resolver's `{:error, reason}` is in the `errors` of the `next` message. The server answers `ping` with `pong`, and closes the connection with the protocol's codes: | Close code | When | | ---------- | ---- | | 4400 | a message that isn't JSON with a `type`, a binary frame, a type the server doesn't take from a client, a `subscribe` without a string `id` and `payload.query`, or whose `variables` isn't an object or `operationName` isn't a string | | 4401 | `subscribe` before `connection_init` | | 4408 | no `connection_init` within 3 seconds | | 4409 | a `subscribe` reusing the `id` of a running subscription | | 4429 | a second `connection_init` | Values reach the subscriptions of a field through `<Root>.PubSub.publish/2`, e.g. from the implementation of a mutation: ```elixir CarpetExpress.PubSub.publish(:shipment_status_changed, shipment) ``` The callback of the field in `<Root>.Resolvers.Subscription` then runs for each subscription, with the published value as `resolution.source`; its result is the payload of the `next` message. Without an implementation, each value sends a `next` message whose `errors` hold "Subscription.shipmentStatusChanged is not implemented". ### Dataloader With `dataloader: true`, `context/1` puts a Dataloader in the context of the resolvers (`resolution.context.loader`), with a `Dataloader.KV` source named `<Root>.Loader`. Its batches go to the `fetch(batch_key, ids)` callback of the implementation configured for `<Root>.Loader`. ### Limitations - Subscriptions are served on one node: values published on one node don't reach the subscriptions of the others. - Every subscription of a field gets every value published to the field, whatever its arguments: the SDL has no place for the topics that Absinthe's `config` would give a field. - GraphiQL runs queries and mutations; it isn't set up for subscriptions. - Absinthe's introspection doesn't expose the `specifiedByURL` of scalars, although the schema keeps `@specifiedBy`. - Absinthe can't import extensions of a root type that the schema definition gives another name (`schema { query: Root }` with `extend type Root`). The generator reports this as an error. - The arguments of custom directives can only have built-in scalar and enum types. ## Options ### -c, --config Path to the configuration file to use. See the "Configuration" section for more information. ### --no-config Doesn't look for `apigenie.yaml` (or `.apigenie.yaml`) in the current directory and its parents. ### --check Writes nothing: compares what the generator would write with the output directory, prints the files that would be created or changed, and exits with 1 when there are any (since 0.12.0). See [Check that generated code is up to date](/docs/reference/generator#check-that-generated-code-is-up-to-date). ### -o, --output Directory where the project is generated. ### --package-name Name of the Mix application, converted to snake_case. `carpet-express` gives the application `carpet_express` and the root module `CarpetExpress`. Defaults to the name of the output directory. ### --package-version Version of the Mix project; `0.1.0` by default. ### -p, --property NAME=VALUE Sets a generator option (see below), e.g. `-p dataloader=true`. Options given on the command line take precedence over the configuration file. ## Configuration ```yaml version: '1.0' commands: generate: server_absinthe: app: carpet_express path: /api/graphql dataloader: true ``` | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | | `app` | string | name of the output directory | Name of the Mix application (snake_case, the directory under `lib/`); also set by `--package-name`. | | `namespace` | string | the application in PascalCase | Root module of the generated modules, e.g. `CarpetExpress`. | | `path` | string | `/graphql` | Path of the GraphQL endpoint. | | `graphiql_path` | string | `/graphiql` | Path of GraphiQL, served in the dev environment. | | `dataloader` | boolean | `false` | Adds a Dataloader to the context of the resolvers. | | `dev_deps` | boolean | `true` | Lists credo as a dependency of `mix.exs` (`only: [:dev, :test]`). | ## Verification The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express GraphQL fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#graphql). This target's support tier is [Tier 2](/docs/reference/generator/conformance#tiers). It goes through all three levels before every release, like Tier 1. It doesn't aim to support every feature: a feature of the fixture can stay unsupported, with the reason its manifest gives. | Results | Level 1 | Level 2 | Level 3 | | --- | --- | --- | --- | | Release 0.12.0 | ✓ snapshots of graphql; 22 supported, 0 not yet | ✓ pass (Erlang/OTP 29 [erts-17.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit:ns]; Mix 1.20.4 (compiled with Erlang/OTP 29)) | ✓ 39 of 39 operations pass (elixir) | | Development version | ✓ snapshots of graphql; 22 supported, 0 not yet | runs before a release | runs before a release | --- # apigenie-server Source: https://apigenie.pl/docs/reference/server See also: [Responses](https://apigenie.pl/docs/reference/server/responses.md), [Scenarios and extensions](https://apigenie.pl/docs/reference/server/scenarios.md), [Scripts](https://apigenie.pl/docs/reference/server/scripts.md), [Document store](https://apigenie.pl/docs/reference/server/store.md), [Several services](https://apigenie.pl/docs/reference/server/services.md), [Validation and security](https://apigenie.pl/docs/reference/server/validation.md), [Contract testing (validating proxy)](https://apigenie.pl/docs/reference/server/contract-testing.md), [Session recording and replay](https://apigenie.pl/docs/reference/server/recording.md), [AsyncAPI](https://apigenie.pl/docs/reference/server/asyncapi.md), [Protobuf / gRPC](https://apigenie.pl/docs/reference/server/grpc.md), [GraphQL](https://apigenie.pl/docs/reference/server/graphql.md), [Configuration](https://apigenie.pl/docs/reference/server/configuration.md), [Dashboard and admin API](https://apigenie.pl/docs/reference/server/dashboard.md), [TLS](https://apigenie.pl/docs/reference/server/tls.md). `apigenie-server` serves an OpenAPI 3.0, 3.1 or 3.2 document (or a Swagger 2.0 one, see [Swagger 2.0 documents](#swagger-20-documents)) as a mock API, the channels of an AsyncAPI 3.x document over WebSocket, HTTP and MQTT, the gRPC services of a `.proto` file, or a GraphQL schema as a GraphQL endpoint with subscriptions. It answers with the document's examples, with stubs, or with data generated from its schemas, validates requests, responses and messages, logs every exchange, and can make the network slow or unreliable on purpose. In front of a real server (`--proxy-to`) it becomes a validating proxy that contract-tests the server's traffic against the OpenAPI or Swagger document, the GraphQL schema, the AsyncAPI document (WebSocket, MQTT and HTTP channels) or the `.proto` file, with coverage and JSON or JUnit reports. It is installed next to `apigenie` by every package (archives, `.deb`, `.rpm`, npm, Homebrew) and has a Docker image of its own. ## Topics - [Responses](/docs/reference/server/responses): Routing, the status, body and headers of an answer, the `Prefer` header, and latency, drops and bandwidth limits. - [Validation and security](/docs/reference/server/validation): What is checked in requests and responses, the security schemes, and XML bodies. - [Contract testing (validating proxy)](/docs/reference/server/contract-testing): `--proxy-to`: the checks on a real server's traffic, coverage, and the JSON and JUnit reports. - [Scenarios and extensions](/docs/reference/server/scenarios): Named sets of rules, from the configuration, `x-apigenie-mock` in the document or the admin API. - [AsyncAPI](/docs/reference/server/asyncapi): The channels of an AsyncAPI document over WebSocket, HTTP and MQTT, and the contract testing of each protocol. - [Protobuf / gRPC](/docs/reference/server/grpc): The gRPC services of a `.proto` file: stubs, metadata, proxy and record, and contract testing. - [GraphQL](/docs/reference/server/graphql): A GraphQL endpoint from a schema: generated data, the store, examples, scenarios, subscriptions and the proxy. - [Scripts](/docs/reference/server/scripts): JavaScript that computes answers and reads the log and the store. - [Session recording and replay](/docs/reference/server/recording): `--record` and `--replay`: a run as files, replayed as a mock or in a test suite. - [Several services](/docs/reference/server/services): One server for several documents. - [Document store](/docs/reference/server/store): The data behind the answers, and CRUD resources. - [Configuration](/docs/reference/server/configuration): `apigenie-server.yaml` and the `commands.mock` section of `apigenie.yaml`, with every key. - [Dashboard and admin API](/docs/reference/server/dashboard): The page at `/__apigenie/ui` and the endpoints behind it. - [TLS](/docs/reference/server/tls): HTTPS with `--tls-cert`, and client certificates. ## Usage ```sh apigenie-server [OPTIONS] SPEC... apigenie-server session export DIR --har FILE ``` ```sh apigenie-server openapi.yaml curl http://127.0.0.1:4010/pets ``` The first line the server writes says where it listens: ```text Listening on http://127.0.0.1:4010/v1 (spec: openapi.yaml, 12 operations) Admin API: http://127.0.0.1:4010/__apigenie Dashboard: http://127.0.0.1:4010/__apigenie/ui ``` The [dashboard](/docs/reference/server/dashboard#dashboard) shows the traffic as it happens, the operations and what answers them, the scenarios, the contract report, the data and, for an AsyncAPI document, the channels and their clients, in the browser. A GraphQL schema (`.graphql`, `.graphqls`, `.gql`) is served at `/graphql`: ```sh apigenie-server schema.graphql curl -X POST http://127.0.0.1:4010/graphql -H 'Content-Type: application/json' \ -d '{"query": "{ books { title author { name } } }"}' ``` ```text Listening on http://127.0.0.1:4010/graphql (spec: schema.graphql, 12 operations) GraphiQL: http://127.0.0.1:4010/graphql Subscriptions: ws://127.0.0.1:4010/graphql Admin API: http://127.0.0.1:4010/__apigenie Dashboard: http://127.0.0.1:4010/__apigenie/ui ``` In front of a real server it checks the traffic against the document instead of mocking it ([contract testing](/docs/reference/server/contract-testing)): ```sh apigenie-server openapi.yaml --proxy-to http://localhost:8080 ``` ```text Listening on http://127.0.0.1:4010/v1 (spec: openapi.yaml, 12 operations) Proxy: http://localhost:8080 (requests: log, responses: log, unknown routes: forward, mode: always) Admin API: http://127.0.0.1:4010/__apigenie Dashboard: http://127.0.0.1:4010/__apigenie/ui ``` With `--log-format json` it is a JSON object (`{"event":"listening","url":...,"port":...}`), and every request after it is logged as one JSON object per line, which suits tools and tests. Several documents are served together on one port, each below a prefix of its own ([several services](/docs/reference/server/services)): ```sh apigenie-server pets.yaml orders.yaml events.asyncapi.yaml ``` ```text Listening on http://127.0.0.1:4010 (3 services) pets http://127.0.0.1:4010/pets/v1 (spec: pets.yaml, 12 operations) orders http://127.0.0.1:4010/orders (spec: orders.yaml, 5 operations) events http://127.0.0.1:4010/events (spec: events.asyncapi.yaml, 3 channels) Admin API: http://127.0.0.1:4010/__apigenie Dashboard: http://127.0.0.1:4010/__apigenie/ui ``` ## Options | Option | Default | Description | | --- | --- | --- | | `--host HOST` | `127.0.0.1` | The address to listen on; `0.0.0.0` or `::` for every interface. Also `APIGENIE_SERVER_HOST`. | | `--port`, `-p PORT` | `4010` | The port; `0` picks a free one. Also `APIGENIE_SERVER_PORT`. | | `--base-path PATH` | the servers' paths | Serve the operations under this prefix instead of the paths of the document's `servers`. | | `--config`, `-c FILE` | see below | The configuration file. | | `--no-config` | | Don't look for a configuration file. | | `--watch`, `-w` | | Reload when the document or the configuration changes. A broken version is reported and the previous one stays. | | `--seed N` | random | Seed of generated data and simulated failures: the same seed repeats a run. | | `--dynamic`, `-d` / `--static` | `--static` | Generate every response from its schema, or answer with examples first. | | `--strict` | | Answer 500 when a response the mock makes doesn't match the document. With `--proxy-to`: answer requests that don't match the document or schema without the upstream (422 for OpenAPI, GraphQL errors for GraphQL) and replace upstream responses that don't (502); AsyncAPI: messages that don't match aren't forwarded, the client gets a problem message instead; gRPC: requests and upstream messages are checked before they are forwarded, and a call that breaks the contract ends with INVALID_ARGUMENT or INTERNAL. | | `--log-format FORMAT` | `stylish` | `stylish` or `json`. | | `--log-level LEVEL` | `info` | `debug`, `info`, `warn` or `error`. | | `--log-file FILE` | | Also write the log to a file, as JSON lines. | | `--log-bodies`, `--log-headers` | | Log request and response bodies, request headers. | | `--quiet`, `-q` | | Only the first line on the standard output. | | `--latency MS` | | Delay every response: a number of milliseconds, or `MIN-MAX`. | | `--jitter MS` | | A random extra delay of up to this many milliseconds. | | `--drop-rate RATE` | | The share of responses (0 to 1) whose connection is reset. | | `--cors on\|off` | `on` | Answer CORS preflights and add CORS headers. | | `--admin on\|off` | `on` | The admin API under `/__apigenie`, and the [dashboard](/docs/reference/server/dashboard#dashboard) at `/__apigenie/ui`. | | `--scenario NAME` | | Switch on a scenario of the configuration or the document; can be repeated. | | `--script FILE` | | A JavaScript module with hooks (see below); can be repeated. | | `--crud` | | Serve the collection resources of an OpenAPI document (`/things` and `/things/{id}`) from the [document store](/docs/reference/server/store#crud-resources): what a `POST` creates, a `GET` lists. The same as `db.crud: auto`. | | `--db-file FILE` | | Keep the [document store](/docs/reference/server/store) in this JSON file: loaded at the start, written when the server stops. Also `APIGENIE_SERVER_DB_FILE`. | | `--asyncapi-server NAME` | every server | AsyncAPI: serve this server of the document only. | | `--mqtt-port PORT` | `1883`, `8883` with `--tls-cert` | AsyncAPI: the port of the MQTT broker; `0` picks a free one. Also `APIGENIE_SERVER_MQTT_PORT`. | | `--proto-path`, `-I DIR` | the file's directory | gRPC: where imports are looked up, like protoc's `--proto_path`; can be repeated. Also `APIGENIE_SERVER_PROTO_PATH` (separated by `:`, `;` on Windows). | | `--stubs FILE\|DIR` | | A YAML or JSON stub file, or a directory of them; can be repeated. gRPC: stubs (see [Stubs](/docs/reference/server/grpc#stubs)). OpenAPI: the exchanges `--record-dir` wrote (see [Record and replay](/docs/reference/server/contract-testing)). Also `APIGENIE_SERVER_STUBS`. | | `--proxy-to TARGET` | | OpenAPI: the real server (`http[s]://host[:port][/prefix]` or `HOST:PORT`) that gets every request, both checked against the document (see [Contract testing](/docs/reference/server/contract-testing)). GraphQL: the real server's endpoint (`https://host/graphql`), requests and answers checked against the schema (see [GraphQL contract testing](/docs/reference/server/graphql#contract-testing-of-a-graphql-api)). AsyncAPI: the real WebSocket and HTTP server (`ws[s]://host[:port][/prefix]` or `http[s]://...`) and the real MQTT broker (`mqtt[s]://host[:port]`), one or both (repeat the option), the messages of both sides checked against the document (see [WebSocket contract testing](/docs/reference/server/asyncapi#contract-testing-of-a-websocket-api), [MQTT contract testing](/docs/reference/server/asyncapi#contract-testing-of-mqtt-channels) and [HTTP channels](/docs/reference/server/asyncapi#contract-testing-of-http-channels)). gRPC: an upstream server for the calls no stub answers, `HOST:PORT` for cleartext HTTP/2 or `https://host[:port]` for HTTP/2 over TLS, its answers checked against the `.proto` file (see [gRPC contract testing](/docs/reference/server/grpc#contract-testing-of-a-grpc-api)). `https://`, `wss://` and `mqtts://` upstreams are verified (see [TLS](/docs/reference/server/tls)). Also `APIGENIE_SERVER_PROXY_TO` (one target). | | `--tls-cert FILE` | | Serve HTTPS, WSS, gRPC and MQTT over TLS with this PEM certificate chain (the server's certificate first); needs `--tls-key`. See [TLS](/docs/reference/server/tls). Also `APIGENIE_SERVER_TLS_CERT`. | | `--tls-key FILE` | | The unencrypted PEM private key of `--tls-cert`. Also `APIGENIE_SERVER_TLS_KEY`. | | `--tls-client-ca FILE` | | Require a client certificate issued by the authorities of this PEM file on every HTTPS, WSS, gRPC and MQTTS connection (mTLS); the subject goes into the log and the contract report. Needs `--tls-cert`. See [Client certificates](/docs/reference/server/tls#client-certificates-mtls). Also `APIGENIE_SERVER_TLS_CLIENT_CA`. | | `--ca-cert FILE` | the system's roots | A PEM file of certificate authorities trusted for `https://`, `wss://` and `mqtts://` upstreams, besides the system's; can be repeated. Also `APIGENIE_SERVER_CA_CERT` (separated by `:`, `;` on Windows). | | `--insecure` | | Don't verify the certificates of `https://`, `wss://` and `mqtts://` upstreams; the traffic stays encrypted. Also `APIGENIE_SERVER_INSECURE=1`. | | `--client-cert FILE` | | A PEM client certificate (chain) presented to `https://`, `wss://`, `mqtts://` and gRPC TLS upstreams that ask for one (mTLS); needs `--client-key`. Also `APIGENIE_SERVER_CLIENT_CERT`. | | `--client-key FILE` | | The unencrypted PEM private key of `--client-cert`. Also `APIGENIE_SERVER_CLIENT_KEY`. | | `--proxy-mode always\|fallback` | OpenAPI and GraphQL `always`, gRPC `fallback` | `always`: the upstream gets every request. `fallback`: OpenAPI: every request still goes to the server, and the mock answers when the server can't be reached, doesn't answer in time, or answers 404 or 501 for an operation of the document (see [Fallback mode](/docs/reference/server/contract-testing)); GraphQL: the mock's examples, scenarios and scripts answer first; gRPC: stubs answer first. An AsyncAPI document's proxy relays every message. | | `--record-dir DIR` | | OpenAPI: write the exchanges the server answered as stub files, replayed with `--stubs`. gRPC: write the proxied calls as stub files. GraphQL: write the proxied answers as examples. Needs `--proxy-to`. Also `APIGENIE_SERVER_RECORD_DIR`. | | `--record-har FILE` | | OpenAPI: write every exchange through the proxy (the server's answers and the mock's own) as a HAR 1.2 file when the server stops. Needs `--proxy-to`. Also `APIGENIE_SERVER_RECORD_HAR`. | | `--record DIR` | | Record the session: every service's exchanges and messages in the order they happened, each as a file, and `session.yaml`; an exchange's test is its `X-Apigenie-Test` header (see [Session recording](/docs/reference/server/recording#session-recording)). Every document, with or without `--proxy-to`. The directory must be new or empty. Also `APIGENIE_SERVER_RECORD`. | | `--record-redact HEADER\|/POINTER` | | What `--record` hides besides `Authorization`, `Cookie`, `Set-Cookie`, `Proxy-Authorization` and `X-Api-Key`: a header name, or a JSON pointer (`/password`) to a value of JSON bodies and messages; can be repeated. | | `--replay DIR` | | Answer from the session `--record` wrote: each request gets the next unused recorded exchange of its test (`X-Apigenie-Test`) that matches it, on every protocol (see [Session replay](/docs/reference/server/recording#session-replay)). When the server stops, exit status 5 if a recorded exchange was never replayed or a request matched none. Also `APIGENIE_SERVER_REPLAY`. | | `--replay-ignore HEADER\|/POINTER` | | What `--replay` doesn't compare besides dates, `readOnly` fields and volatile headers: a header name, or a JSON pointer (`/id`, `/items/*/id`) into JSON bodies and messages; can be repeated. | | `--replay-missing fail\|generate\|passthrough` | `fail` | What a request no recorded exchange matches gets: a 502 problem naming the closest recording and how the request differs (`fail`), the mock's own answer (`generate`), or the answer of `--proxy-to` (`passthrough`). | | `--replay-update` | | With `--replay-missing passthrough`: record the run and, when the server stops, replace the `--replay` session with it. | | `--proxy-unknown forward\|reject` | `forward` | OpenAPI proxy: forward requests for no operation of the document (reported), or answer them with 404 or 405. | | `--report FILE` | | Write the contract report (coverage and violations) as JSON when the server stops. Also `APIGENIE_SERVER_REPORT`. | | `--report-junit FILE` | | Write the contract report as JUnit XML when the server stops. Also `APIGENIE_SERVER_REPORT_JUNIT`. | | `--fail-on none\|errors\|warnings` | `none` | Exit with 5 when the server stops after violations of that severity. | | `--min-coverage PERCENT` | | Exit with 5 when the server stops with less of the document covered (a GraphQL schema: its fields; an AsyncAPI document: its operations' messages; a `.proto` file: its methods; [several services](/docs/reference/server/services): their combined coverage). | | `--credits`, `--license [LIBRARY]`, `--license-list` | | Like `apigenie credits` and `apigenie license`. | | `--help`, `-h` / `--version`, `-v` | | Show the help (with the exit statuses and the per-request directives), or the version. | ## Exit status | Code | Meaning | | --- | --- | | 0 | Stopped with Ctrl+C (or `POST /__apigenie/shutdown`) | | 2 | Bad options, configuration, scripts or stub files, or an unexpected error | | 3 | The document can't be served (missing, unreadable, not OpenAPI 3, Swagger 2.0 or AsyncAPI 3, no channels the mock serves, a `.proto` file with errors, missing imports or no services) | | 4 | The address can't be used (the port is taken, ...) | | 5 | The contract report failed when the server stopped (`--fail-on`, `--min-coverage`), or the replay did (`--replay`: a recorded exchange was never replayed, or a request matched none) | | 130 | Stopped at once with a second Ctrl+C | ## Swagger 2.0 documents A Swagger 2.0 document (`swagger: "2.0"`) is served, proxied and contract-tested like the OpenAPI 3.2 document `apigenie convert --to openapi32` would make of it. The conversion happens in memory each time the document is read (at startup and on reloads); no file is written. Body and form parameters become request bodies, `produces` and `consumes` become media types, `host`, `basePath` and `schemes` become the servers, and `definitions`, `parameters`, `responses` and `securityDefinitions` move into `components`. Locations stay those of the Swagger file: warnings about the document give its lines, the problems of `x-apigenie-mock` extensions its lines and JSON pointers, and the contract report's `pointer` of each operation is a pointer into it. What the conversion can only approximate (a `collectionFormat` without counterpart, form parameters next to a body parameter, ...) is told once at startup, on the standard error, as an `info:` line with the file's line, column and JSON pointer: ```text info: pets.yaml:7:71: /paths/~1pets/get/parameters/0/collectionFormat: collectionFormat tsv has no counterpart and becomes style form (csv) ``` `GET /__apigenie/spec` returns the converted document, which is what is served. The document is converted alone: one that references other files can't be served (exit status 3) until `apigenie bundle` has put them into it. ## Docker ```sh docker run --rm -p 4010:4010 -v "$PWD:/mnt/data" mykulyak/apigenie-server openapi.yaml ``` It serves GraphQL schemas the same way (`mykulyak/apigenie-server schema.graphql`). The image listens on every interface of the container (`APIGENIE_SERVER_HOST=0.0.0.0`) and exposes port 4010, and 1883 for the MQTT broker (`-p 1883:1883`). It has the CA certificates of Alpine Linux, so `https://` upstreams are verified; mount a certificate and its key to serve HTTPS (`-v "$PWD/certs:/certs" ... --tls-cert /certs/server.pem --tls-key /certs/server.key`). ## npm ```sh npx --package @mykulyak/api-genie apigenie-server openapi.yaml ``` ## Deprecated names `apigenie-server` was called `apigenie-mock` before. The `apigenie-mock` command was removed in 1.0: run `apigenie-server` instead. These old names keep working until 1.1, with a one-line notice on standard error: - `APIGENIE_MOCK_*` variables: read when the `APIGENIE_SERVER_*` variable of the same name is unset. - `mykulyak/apigenie-mock`: its `latest` tag only prints the new image name and exits with 2; the older tags still hold the old server. What did not change: the `apigenie-mock.yaml` configuration file (still read, after `apigenie-server.yaml`), the `commands.mock` section of a shared configuration, the `x-apigenie-mock` extensions, the `X-Apigenie-Mock-*` headers and the `/__apigenie` admin API. ## Limits - TLS: no session resumption, no revocation checks (OCSP, CRLs) of server or client certificates (see [Client certificates](/docs/reference/server/tls#client-certificates-mtls)). The OpenAPI and GraphQL proxies speak HTTP/1.1 to the server, a connection per request; the AsyncAPI one connects to WebSocket servers without extensions. The AsyncAPI proxy relays WebSocket messages up to 16 MiB; of MQTT 5 it relays the message properties, not those of CONNECT, SUBSCRIBE or DISCONNECT, nor subscription options and identifiers, and the broker publishes wills without their delay. Request and response bodies are buffered (16 MiB by default), so streams such as server-sent events don't fit. A HAR file is kept in memory until the server stops. OpenAPI stubs match exact paths and queries, not templates. - gRPC: native gRPC over HTTP/2 (cleartext, or TLS with `--tls-cert`) only; gRPC-Web, the Connect protocol and REST transcoding (`google.api.http`) aren't served, and messages can't be compressed. Reflection doesn't include custom options. - Several services: one MQTT broker for all of them, so an `mqtt://` upstream goes with one document; one HAR file. Services can't be added or removed without a restart. - Session recording: exchanges are numbered in the order they completed; a gRPC call keeps at most 100 messages per side, a session at most 10 000 exchanges; a `.proto` document's hash covers the file, not its imports; MQTT messages keep neither QoS nor retain nor MQTT 5 properties; `session export` leaves WebSocket and MQTT messages out of the HAR file. - The document store is the OpenAPI document's and the scripts'; the GraphQL mock keeps its own [store](/docs/reference/server/graphql#the-store), and AsyncAPI and gRPC mocks see the documents only through scripts. CRUD resources are a path and its items' path: nested collections (`/users/{id}/orders`) are collections of their own, not filtered by the parent's id, and `readOnly` properties are filled in at the top level only. - AsyncAPI: Kafka, AMQP and other protocols aren't served; Avro and Protobuf payloads are sent from their examples only, and not validated. The MQTT broker keeps no sessions between connections and sends at most QoS 1. - XML bodies: no DTDs (and so no entities but the five predefined ones), UTF-8 and UTF-16 only; mixed content and `xsi:type` aren't mapped, and `nodeType: none` is honoured on arrays only. - Callbacks, webhooks and links are not mocked. OpenAPI 3.2 streams described by `itemSchema` (server-sent events, JSON Lines) are answered with an empty body. - GraphQL: no federation (`_entities`, `_service`), `@defer` and `@stream`, persisted queries or file uploads. Scenarios don't apply to subscriptions over WebSocket or server-sent events. The proxy doesn't forward subscriptions, and its schema check leaves out what only recent servers introspect (`@specifiedBy` URLs, `@oneOf`, repeatable directives, deprecated arguments) and the directives applied in the schema. --- # Responses Source: https://apigenie.pl/docs/reference/server/responses Part of the reference of [apigenie-server](https://apigenie.pl/docs/reference/server.md). Its other pages: [Scenarios and extensions](https://apigenie.pl/docs/reference/server/scenarios.md), [Scripts](https://apigenie.pl/docs/reference/server/scripts.md), [Document store](https://apigenie.pl/docs/reference/server/store.md), [Several services](https://apigenie.pl/docs/reference/server/services.md), [Validation and security](https://apigenie.pl/docs/reference/server/validation.md), [Contract testing (validating proxy)](https://apigenie.pl/docs/reference/server/contract-testing.md), [Session recording and replay](https://apigenie.pl/docs/reference/server/recording.md), [AsyncAPI](https://apigenie.pl/docs/reference/server/asyncapi.md), [Protobuf / gRPC](https://apigenie.pl/docs/reference/server/grpc.md), [GraphQL](https://apigenie.pl/docs/reference/server/graphql.md), [Configuration](https://apigenie.pl/docs/reference/server/configuration.md), [Dashboard and admin API](https://apigenie.pl/docs/reference/server/dashboard.md), [TLS](https://apigenie.pl/docs/reference/server/tls.md). How the mock answers a request: where the paths are served, which status, body and headers it picks, how a request asks for a particular answer, and how the network is made slow or unreliable on purpose. [How the mock picks a response](/docs/concepts/how-the-mock-picks-a-response) walks through these rules with a document to try them on. - **Routing.** Paths are served under the path of the document's first server (`/v1` for `https://api.example.com/v1`) and as they are. Literal paths win over templated ones (`/pets/mine` over `/pets/{id}`). An unknown path is answered with 404, an unknown method with 405 and an `Allow` header, both as [problem details](https://www.rfc-editor.org/rfc/rfc9457). OpenAPI 3.2's `query` method and the methods of `additionalOperations` (`COPY`, ...) are routed like the others. - **Status.** The lowest 2xx response, else `2XX`, else the lowest declared, else `default`. - **Body.** Content negotiation follows `Accept` (406 when nothing fits). Without an `Accept`, or with `*/*`, the response takes the media type of the request's body when it has it: a SOAP 1.2 request (`application/soap+xml`) to an operation answering both SOAP versions gets a SOAP 1.2 envelope. In the default static mode the media type's `example`, its first named example, or the schema's example answer; what has none is generated from the schema. Generated values respect types, the formats of the OpenAPI format registry (`uuid`, `date-time`, `int8`, `decimal`, `http-date`, ...; see [Formats](/docs/reference/cli/formats)), patterns, lengths, ranges, `enum`, `const`, `allOf`, `oneOf`, `readOnly` and `writeOnly`. A value for `application/xml`, `text/xml` or a `+xml` type is written as XML (see [XML bodies](/docs/reference/server/validation#xml-bodies)); a string example is sent as it is. - **Headers.** Response headers are filled in from their examples or schemas. `X-Apigenie-Mock-Operation` and `X-Apigenie-Mock-Source` (`example:cat`, `generated`, `scenario:outage`, `stub:getPet-1`) say where a response came from. - **Stubs.** `--stubs DIR` (or `stubs:` in the configuration) answers with recorded exchanges (see [Record and replay](/docs/reference/server/contract-testing)) before the document's examples: a request's `Prefer` and the rules of scenarios and overrides still come first. ## Choosing a response per request The `Prefer` header (or query parameters, which are removed before validation) asks for a particular answer: | `Prefer` | Query | Effect | | --- | --- | --- | | `code=404` | `__code=404` | That status (500 when the operation doesn't declare it). | | `example=cat` | `__example=cat` | That named example. | | `dynamic=true` | `__dynamic=true` | A generated body. | | `delay=1500` | `__delay=1500` | Answer after 1.5 seconds. | | `drop=reset` | | Reset the connection (`close`, `timeout` and `truncate` too). | | `scenario=outage` | | Apply that scenario to this request. | ## Network simulation Latency (fixed, uniform, normal or log-normal), jitter, dropped connections (reset, closed without an answer, never answered, or truncated bodies) and bandwidth limits apply to every response, an operation's, a scenario's or one request's. --- # Scenarios and extensions Source: https://apigenie.pl/docs/reference/server/scenarios Part of the reference of [apigenie-server](https://apigenie.pl/docs/reference/server.md). Its other pages: [Responses](https://apigenie.pl/docs/reference/server/responses.md), [Scripts](https://apigenie.pl/docs/reference/server/scripts.md), [Document store](https://apigenie.pl/docs/reference/server/store.md), [Several services](https://apigenie.pl/docs/reference/server/services.md), [Validation and security](https://apigenie.pl/docs/reference/server/validation.md), [Contract testing (validating proxy)](https://apigenie.pl/docs/reference/server/contract-testing.md), [Session recording and replay](https://apigenie.pl/docs/reference/server/recording.md), [AsyncAPI](https://apigenie.pl/docs/reference/server/asyncapi.md), [Protobuf / gRPC](https://apigenie.pl/docs/reference/server/grpc.md), [GraphQL](https://apigenie.pl/docs/reference/server/graphql.md), [Configuration](https://apigenie.pl/docs/reference/server/configuration.md), [Dashboard and admin API](https://apigenie.pl/docs/reference/server/dashboard.md), [TLS](https://apigenie.pl/docs/reference/server/tls.md). A scenario is a named set of rules switched on and off together. A rule matches requests (by `operationId`, `method`, `path`, `tag`, headers or query) and sets the status, an example, a literal body, headers, the network simulation, or a probability. Scenarios come from the configuration, from `x-apigenie-mock` in the document, or from the admin API. ```yaml paths: /orders: get: x-apigenie-mock: delay: 200 headers: {X-Region: eu} scenarios: empty: {body: []} broken: {status: 500, drop: {probability: 0.5, mode: reset}} ``` A schema can name the [faker](/docs/reference/cli/faker) provider that generates its values with `x-apigenie-mock-faker` or `x-faker`: a name (`person.firstName`, `internet.email`, `location.city`...), `{"number.int": [1, 10]}` with arguments by position, `{"string.alpha": {length: 6}}` with arguments by name, or `{provider: number.int, args: [1, 10], options: {...}}`. Arguments are numbers, strings and booleans. Names of older faker.js versions (`name.firstName`, `address.city`, `datatype.uuid`) work too. An unknown name, or arguments the provider doesn't take, are answered with 500 and faker's message. Records (`person.profile`, `location.address`, `finance.card`...) are objects, or their JSON text for a string schema. ```yaml properties: owner: {type: string, x-faker: person.fullName} age: {type: integer, x-faker: {number.int: [18, 90]}} code: {type: string, x-faker: {string.alpha: {length: 6, casing: upper}}} customer: {type: object, x-faker: {person.profile: {country: PL}}} ``` With `generation.smart_names`, plain string properties called like `email`, `first_name`, `city`, `zip_code` or `phone` get such values without an extension. `generation.null_probability` sets how often a schema with OAS 3.0 `nullable: true` is answered with `null`. `x-apigenie-mock` on an operation (or its path item) accepts `status`, `example`, `dynamic`, `body`, `body_file`, `headers`, `latency`, `jitter`, `drop`, `bandwidth`, `delay`, `probability`, `validate_request`, `scenarios` and `resource` (see [CRUD resources](/docs/reference/server/store#crud-resources)); on a response, `delay`, `latency`, `jitter` and `headers`. --- # Scripts Source: https://apigenie.pl/docs/reference/server/scripts Part of the reference of [apigenie-server](https://apigenie.pl/docs/reference/server.md). Its other pages: [Responses](https://apigenie.pl/docs/reference/server/responses.md), [Scenarios and extensions](https://apigenie.pl/docs/reference/server/scenarios.md), [Document store](https://apigenie.pl/docs/reference/server/store.md), [Several services](https://apigenie.pl/docs/reference/server/services.md), [Validation and security](https://apigenie.pl/docs/reference/server/validation.md), [Contract testing (validating proxy)](https://apigenie.pl/docs/reference/server/contract-testing.md), [Session recording and replay](https://apigenie.pl/docs/reference/server/recording.md), [AsyncAPI](https://apigenie.pl/docs/reference/server/asyncapi.md), [Protobuf / gRPC](https://apigenie.pl/docs/reference/server/grpc.md), [GraphQL](https://apigenie.pl/docs/reference/server/graphql.md), [Configuration](https://apigenie.pl/docs/reference/server/configuration.md), [Dashboard and admin API](https://apigenie.pl/docs/reference/server/dashboard.md), [TLS](https://apigenie.pl/docs/reference/server/tls.md). A script is an ES module whose default export has any of five hooks: ```js import { limit } from './settings.mjs'; export default { // before the document's operations: a response answers the request onRequest(req, ctx) { if (req.path === '/pets/13') { return ctx.response(404, { title: 'No such pet' }); } }, // the response about to be sent: change it in place onResponse(req, res, ctx) { if (req.operationId === 'listPets') { res.body = res.body.slice(0, limit); res.headers['x-total-count'] = '3'; res.delay = 250; } }, // AsyncAPI messages, in and out: change msg.payload, or return false to drop the message onMessage(msg, ctx) { if (msg.direction === 'out') msg.payload.sentAt = ctx.now(); }, // GraphQL operations (each subscription event too): a result answers, its data completed onGraphQL(operation, ctx) { if (operation.name === 'GetUser') { return { data: { user: { id: operation.variables.id, name: ctx.fake('person.fullName') } } }; } }, // after the scripts were loaded, at the start and after each reload onReload(ctx) {}, }; ``` - `req` has `method`, `path`, `query` (an object; repeated parameters are arrays), `headers` (lower-case names), `body` (parsed JSON, or the text), `rawBody`, `operationId` and `route` (in `onResponse`), `remote` and `connectionId`. - `res` has `status`, `headers`, `body`, `source`, and `delay` (milliseconds) and `drop` (`reset`, `close`, `timeout`, `truncate`) to set. A response returned by `onRequest` has the same fields. - `msg` has `direction` (`in` or `out`), `channel`, `operation`, `message`, `contentType` and `payload`. - `operation` has `name`, `type` (`query`, `mutation`, `subscription`), `query`, `variables` and `rootFields` (`["Query.user"]`). The result's data is cut to the selection set and completed with generated values, like an example's. - `ctx` has `state` (`get`, `set`, `delete` and `keys` of JSON values kept between requests, the admin API's `/state`), `db` (collections of documents, see [Document store](/docs/reference/server/store)), `log(level, ...values)`, `random()` (seeded by `--seed`), `now()`, `response(status, body, headers)`, `fake(name, ...arguments)` (the faker providers of `x-faker`, with arguments by position and a last object by name: `fake('string.alpha', {length: 4})`) and `scenarios` (`activate`, `deactivate`, `active`). Scripts run in a sandbox: the language only, modules next to the script, no file system, network or timers. Each call has `scripting.timeout_ms` (1000) and `scripting.memory_limit_mb` (64); a hook that throws or runs out of time is logged, and answered with 500 when `scripting.fail_mode` is `error`. `--watch` reloads changed scripts, and a broken script keeps the previous version. --- # Document store Source: https://apigenie.pl/docs/reference/server/store Part of the reference of [apigenie-server](https://apigenie.pl/docs/reference/server.md). Its other pages: [Responses](https://apigenie.pl/docs/reference/server/responses.md), [Scenarios and extensions](https://apigenie.pl/docs/reference/server/scenarios.md), [Scripts](https://apigenie.pl/docs/reference/server/scripts.md), [Several services](https://apigenie.pl/docs/reference/server/services.md), [Validation and security](https://apigenie.pl/docs/reference/server/validation.md), [Contract testing (validating proxy)](https://apigenie.pl/docs/reference/server/contract-testing.md), [Session recording and replay](https://apigenie.pl/docs/reference/server/recording.md), [AsyncAPI](https://apigenie.pl/docs/reference/server/asyncapi.md), [Protobuf / gRPC](https://apigenie.pl/docs/reference/server/grpc.md), [GraphQL](https://apigenie.pl/docs/reference/server/graphql.md), [Configuration](https://apigenie.pl/docs/reference/server/configuration.md), [Dashboard and admin API](https://apigenie.pl/docs/reference/server/dashboard.md), [TLS](https://apigenie.pl/docs/reference/server/tls.md). Scripts keep documents in collections: `ctx.db.<collection>`, made the first time a script names it. Writes are kept in memory for the run (see `--db-file`), shared by every script and shown by the admin API's `/__apigenie/db`. ```js export default { onRequest(req, ctx) { if (req.method === 'POST' && req.path === '/notes') { return { status: 201, body: ctx.db.notes.insert(req.body) }; } if (req.path === '/notes') { return { body: ctx.db.notes.find({ tags: { $contains: 'home' } }, { sort: '-id', limit: 10 }) }; } }, }; ``` | Method | Returns | | --- | --- | | `insert(document)` | The document as stored, with its id. | | `get(id)` | The document, or `undefined`. `"3"` finds `3`. | | `find(where, {limit, offset, sort})` | An array of documents. | | `count(where)` | A number. | | `all()` | Every document, in the order they were inserted. | | `update(id, patch)` | The document after a [JSON merge patch](https://www.rfc-editor.org/rfc/rfc7396) (`null` removes a property), or `undefined` for an unknown id. The id stays. | | `replace(id, document)` | The new document with the old id, or `undefined`. | | `delete(id)` | `true` when there was such a document. | | `clear()` | How many documents went. | `ctx.db.collections()` lists the collections and `ctx.db.reset()` (`reset('notes')` for one) puts them back to their seeds. - **Queries.** `where` is an object of fields and values, all of which must match: `{status: 'open'}`, `{'address.city': 'Kraków'}` (a path), or operators: `$eq`, `$ne`, `$in` (an array of values), `$gt`, `$gte`, `$lt`, `$lte` (numbers and strings), `$contains` (a substring, or an item of an array): `{weight: {$gte: 5, $lt: 20}}`. Numbers and strings are never equal. `sort` is `'field'`, `'-field'` (descending), `'a,-b'`, an array of them or `[{field, descending}]`; missing values sort last. Anything fancier is a JavaScript filter on a limited result. - **Ids.** A document keeps its own `id` (a string or an integer), else gets the next one: 1, 2, 3... (`"1"`, `"2"`... for a resource whose id is a string, a UUID made from the run's `--seed` for `format: uuid`). An id in use is refused, and the script's call throws. - **Schemas.** The collection of a [resource](#crud-resources) is bound to its schema: a new document gets the `readOnly` properties it lacks (generated, like `createdAt`), and every write is checked. A document that doesn't match is kept and reported in the log, or refused (422 for a request, a throw for a script) when `validation.response` is `enforce` (`--strict`). - **Seeds.** `db.seed` names a file of documents (a JSON or YAML array) per collection, or a directory of them (`seed/shipments.json` seeds `shipments`). A resource's collection without one is seeded from its list operation's example, else with `db.generate` (3) documents generated with the run's seed. `ctx.db.reset()` and `POST /__apigenie/db/reset` go back to the seeds, not to nothing. A seed that doesn't match the schema is kept and reported at the start; a file that can't be read stops the server with exit status 2. - **Tests.** A request with an `X-Apigenie-Test: <id>` header reads and writes a namespace of its own, which starts as a copy of the seeds: parallel test runs don't see each other's documents. The admin API's `/db` endpoints take the same header (or `?test=<id>`). - **Snapshots.** `PUT /__apigenie/db/snapshots/{name}` copies the documents of every collection, `POST /__apigenie/db/snapshots/{name}/restore` puts them back. - **Persistence.** In memory by default, so a restart is a clean slate. With `--db-file` (or `db.file`), the store is read from that JSON file at the start (a file that can't be read is reported, and the store starts empty) and written there when the server stops or on `POST /__apigenie/db/save`. The file holds `formatVersion` 1, the collections' seeds, the documents of each namespace and the snapshots. Seed files don't replace what the file holds. - **Log.** Every write is a `db` event: the collection, `insert 3`, `update 3`, `delete 3`, `clear 2 documents`, `reset`, `restore <name>`, `seed 3 documents from file`, who wrote (`script:mock.mjs`, `admin`) and the test's namespace (`test`). `onMessage` and `onGraphQL` use the default namespace. - **After a reload.** The documents stay; collections are bound again, new ones seeded, and documents that no longer match their schema are reported. - **Several services.** Each [service](/docs/reference/server/services) has a store of its own, which its scripts' `ctx.db` and its resources use; `db.seed` seeds every service's collections, and the admin API's `/db` endpoints take `?service=` when several could be meant. `--db-file` (and `db.file`) keep the store of a server of one document; with several services it exits with status 2. - **Limits.** A collection keeps up to `db.max_documents` (10,000) documents per namespace. The store is not a database: no transactions, relations or durability promises. ## CRUD resources With `db.crud: auto` (or `--crud`), a path and the path of its items, such as `/shipments` and `/shipments/{id}`, make a resource whose collection (`shipments`) its operations read and write; no script is needed. Without it (`db.crud: explicit`, the default), only the paths an `x-apigenie-mock: {resource: ...}` extension names are resources; `db.crud: off` serves none. | Operation | Answer | | --- | --- | | `GET /shipments` | The documents, paged and filtered by the operation's query parameters. | | `POST /shipments` | The document stored, with its id and `readOnly` properties; 201 when the operation declares it. | | `GET /shipments/{id}` | The document, or 404. | | `PUT /shipments/{id}` | The document replaced (the id and `readOnly` properties stay), or 404. | | `PATCH /shipments/{id}` | The document after a JSON merge patch, or 404. | | `DELETE /shipments/{id}` | 204 when the operation declares it, else the document that went; 404 for an unknown id. | - **The schema** is the list response's items, or the items of its object's array property (an envelope such as `{data: [...], total: 3}`: one array property, or the one called `data`, `items`, `results` or like the collection), else the item response's or the request body's. The id is the schema's `id` property, else the path parameter when it is a property; integers count, strings with `format: uuid` are UUIDs. Answers leave `writeOnly` properties out. - **Lists** page by the list operation's parameters: `offset` and `limit`, `page` (from 1) and `per_page` (`page_size`, `pageSize`, `size`, `limit`), or `cursor` (`after`, `page_token`) and a size, the size's `default` when not given (20 without one). An envelope gets the page in its array property, and `total` (`totalCount`, `total_count`...), `hasMore`, `nextCursor`, `page`, `offset` and `limit` filled in when it declares them; its other members are generated. Other query parameters named like a property of the documents filter by it (`?status=open`), and `sort` (`order_by`) sorts: `-createdAt`, `status:desc,id`. - **What comes first.** Requests are validated before the store sees them (422 under `validation.request: enforce`). A request's `Prefer` (or `__` parameters), a scenario's or an override's rule, an extension that sets the status, an example or a body, and stubs answer instead of the store. The store's answers are validated like any other, and say `X-Apigenie-Mock-Source: db`. - **The extension**, on a path item or an operation of either path: `resource: shipments` (the collection's name), `resource: false` (not a resource, also with `db.crud: auto`) or `resource: {name: parcels, id: code, schema: Parcel, list: entries}` (the id property, the schema under `components/schemas` or as a `#/` reference, the envelope's array property). - **Proxies.** A document served with `--proxy-to` has no resources: the server's state is the upstream's. ```yaml paths: /shipments: x-apigenie-mock: {resource: {name: shipments, schema: Shipment}} get: ... /shipments/{id}: get: ... ``` --- # Several services Source: https://apigenie.pl/docs/reference/server/services Part of the reference of [apigenie-server](https://apigenie.pl/docs/reference/server.md). Its other pages: [Responses](https://apigenie.pl/docs/reference/server/responses.md), [Scenarios and extensions](https://apigenie.pl/docs/reference/server/scenarios.md), [Scripts](https://apigenie.pl/docs/reference/server/scripts.md), [Document store](https://apigenie.pl/docs/reference/server/store.md), [Validation and security](https://apigenie.pl/docs/reference/server/validation.md), [Contract testing (validating proxy)](https://apigenie.pl/docs/reference/server/contract-testing.md), [Session recording and replay](https://apigenie.pl/docs/reference/server/recording.md), [AsyncAPI](https://apigenie.pl/docs/reference/server/asyncapi.md), [Protobuf / gRPC](https://apigenie.pl/docs/reference/server/grpc.md), [GraphQL](https://apigenie.pl/docs/reference/server/graphql.md), [Configuration](https://apigenie.pl/docs/reference/server/configuration.md), [Dashboard and admin API](https://apigenie.pl/docs/reference/server/dashboard.md), [TLS](https://apigenie.pl/docs/reference/server/tls.md). One `apigenie-server` serves several documents at once: an application's backends, a gateway's services, the HTTP and the messaging side of a system. Each document is a **service** with a name and a **mount**, where its clients reach it. Several `SPEC`s on the command line are services named after their files (`pets.openapi.yaml` is `pets`) and mounted at `/<name>`; a `.proto` file gets a port of its own. A single `SPEC` is served as before, without a prefix. The configuration's `services` list says more: ```yaml version: "1.0" server: {port: 4010} validation: {request: enforce} # the services' defaults services: - name: pets spec: pets.yaml # mounted at /pets - name: orders spec: orders.yaml mount: /shop/orders proxy: {target: "http://localhost:8080", mode: fallback, record_har: session.har} scenarios: outage: {rules: [{status: 503}]} - name: events spec: events.asyncapi.yaml mount: {host: events.localhost} - name: greeter spec: greeter.proto mount: {port: 50051} ``` - **What a service sets**: `name` and `spec` (required), `mount`, and the settings of its document: `proxy`, `stubs`, `scenarios`, `overrides`, `validation`, `security`, `operations`, `responses`, `generation`, `headers`, `asyncapi`, `graphql` and `grpc`. These keys at the top of the file are every service's defaults; a service's `stubs`, `scenarios`, `overrides` and `proxy` replace the defaults rather than adding to them. `server`, `cors`, `simulation`, `tls`, `admin`, `log`, `contract`, `scripts`, `db`, `request_overrides` and `asyncapi.mqtt_port` are the server's. - **Mounts.** A path prefix (`/shop/orders`, default `/<name>`) on the server's port: the service gets the requests below it, without the prefix, so its own base path and routes are unchanged. `{host: events.localhost}` takes the requests whose `Host` header names that host (any port), and may add a `prefix`. `{port: N}` is a listener of the service's own (`0` picks a free one), which a `.proto` file's service needs: gRPC clients can't add a prefix. Requests the server's port gets go to the services by host first, then to the one with the longest prefix (prefixes end at a `/`); the others get 404 `no-service`, which lists the mounts. Two services can't share a name, nor can one's mount hide another's (`/shop` and `/shop/orders`), nor can a mount cover the admin API. - **Proxies** forward the path without the mount's prefix, after their own (`--proxy-to`'s path). `--proxy-to`, `--stubs`, `--record-dir` and `--record-har` name one document's upstream and recordings, so with several services they are refused: set them per service. - **WebSocket**: an AsyncAPI service's channels and a GraphQL service's subscriptions share the server's port, below the service's mount (`ws://127.0.0.1:4010/events/v1/rooms/1`). - **MQTT**: one broker for every service (`--mqtt-port`). Topics are served as the documents name them, unless the MQTT channels of two services can match the same topic (`doors/+/open` in both, or `status` and `#`): then the topics of each of those services start with its name (`front/doors/7/open`). The startup line shows the prefix (`MQTT topics under front/`). An `mqtt://` upstream goes with one document. - **The log** names the service of each event (`"service": "orders"` in JSON, `[orders]` in the stylish log); event paths are within the service, without its prefix. Ids are unique across the services. - **The admin API** (`/__apigenie`) covers every service: `GET /__apigenie/services` lists them with their mounts and URLs, the items of `/routes` (full paths), `/scenarios`, `/overrides`, `/log` and the status's `documents` name their service, and `?service=NAME` narrows any endpoint to one service. An endpoint of one service's resources (a scenario of two services, `PUT /overrides`, `/state`, `/db`, `/spec`) needs it when more than one service could be meant, and answers 400 `admin-service-required` otherwise; a service's own endpoints (the gRPC ones, `/contract/violations`) answer 404 without it. `PUT /simulation`, `POST /seed` and `POST /reload` apply to every service unless one is named. - **The contract report** (`--report`, `GET /__apigenie/contract`) has a section per service in `sections`, each a whole report of its document with its `name` and `mount`, and a `summary` that counts them together: requests, violations and `coverage.combined`, the units of every service added up (OpenAPI branches, GraphQL fields, gRPC methods, AsyncAPI messages). `--fail-on` and `--min-coverage` apply to that summary: a violation of any service fails the run, and the combined coverage must reach the threshold (the reason names the service with the lowest). The JUnit report has a suite per service. - **The HAR file** of the proxies is one per server: every service that records names the same file, and each entry's `_apigenie.service` names its service; URLs keep the mount's prefix. - **Reloads** (`--watch`): a service reloads when its document, stubs or scripts change; a change of the configuration reloads every service. Adding or removing a service needs a restart. --- # Validation and security Source: https://apigenie.pl/docs/reference/server/validation Part of the reference of [apigenie-server](https://apigenie.pl/docs/reference/server.md). Its other pages: [Responses](https://apigenie.pl/docs/reference/server/responses.md), [Scenarios and extensions](https://apigenie.pl/docs/reference/server/scenarios.md), [Scripts](https://apigenie.pl/docs/reference/server/scripts.md), [Document store](https://apigenie.pl/docs/reference/server/store.md), [Several services](https://apigenie.pl/docs/reference/server/services.md), [Contract testing (validating proxy)](https://apigenie.pl/docs/reference/server/contract-testing.md), [Session recording and replay](https://apigenie.pl/docs/reference/server/recording.md), [AsyncAPI](https://apigenie.pl/docs/reference/server/asyncapi.md), [Protobuf / gRPC](https://apigenie.pl/docs/reference/server/grpc.md), [GraphQL](https://apigenie.pl/docs/reference/server/graphql.md), [Configuration](https://apigenie.pl/docs/reference/server/configuration.md), [Dashboard and admin API](https://apigenie.pl/docs/reference/server/dashboard.md), [TLS](https://apigenie.pl/docs/reference/server/tls.md). Requests are checked against their operation: path, query, header and cookie parameters in every style, and JSON, XML, form and multipart bodies. A request that doesn't match is answered with 422 and the problems, a body that can't be parsed (JSON, XML, multipart) with 400, an unknown media type with 415. Security requirements are checked for presence (API keys, HTTP basic and bearer, OAuth2 and OpenID Connect tokens; 401 with `WWW-Authenticate`), and against configured credentials in `enforce` mode (403). Responses the mock makes are checked too: problems are logged and counted in `X-Apigenie-Mock-Violations`, or answered with 500 under `--strict`. Schemas' `format` values are checked as the [OpenAPI format registry](/docs/reference/cli/formats) defines them, for the JSON types each format applies to (`int8` ranges, `http-date`, `decimal`, `language`, ...); `validation.formats: false` turns these checks off. Formats of your own, declared in [`openapi.custom_formats`](/docs/reference/cli/configuration#openapicustom_formats) of the configuration file, are accepted as they are, and an entry there naming a registry format replaces that format's type and its check. ## XML bodies Bodies of `application/xml`, `text/xml` and `+xml` media types are parsed as XML 1.0 with namespaces, mapped to a JSON value as the schema's `xml` objects describe it, and checked against the schema like JSON bodies; the mock, the validating proxy and `apigenie test` do the same, and the mock and `apigenie test --generate` write XML the same way in reverse. For this schema ```yaml Order: type: object xml: {name: order, namespace: "urn:orders", prefix: o} properties: id: {type: integer, xml: {nodeType: attribute}} # OpenAPI 3.0/3.1: attribute: true customer: {$ref: "#/components/schemas/Customer"} # Customer has xml: {name: Buyer} note: {type: string, xml: {nodeType: cdata}} tags: {type: array, items: {type: string, xml: {name: tag}}} lines: type: array xml: {name: Lines, nodeType: element} # 3.0/3.1: wrapped: true items: {$ref: "#/components/schemas/Line"} # Line has xml: {name: Line} ``` the body is ```xml <o:order xmlns:o="urn:orders" id="7"> <Buyer><name>Ann</name></Buyer> <![CDATA[Leave at the <door>]]> <tag>a</tag><tag>b</tag> <Lines><Line sku="x"><quantity>2</quantity></Line></Lines> </o:order> ``` - The root element is named by the schema's `xml.name`, else by the component a `$ref` points to; another name is a `xml-root` violation. A schema without either names no root. - A property is a child element named by its `xml.name` (its own, or that of the schema it references), else by the property name. `nodeType: attribute` makes it an attribute, `text` and `cdata` the element's character data. - An array's items repeat in the parent element, named by the items' `xml.name` or the property name; with `nodeType: element` (`wrapped: true`) they sit in a wrapper element. - A declared `xml.namespace` must match; without one, elements are matched by local name in any namespace. An element with a property's local name in another namespace isn't that property: it is kept as `{namespace}name`, so the property is missing and `additionalProperties: false` reports the element. - Child elements are written in the order the schema declares its properties, as XML Schema sequences require. - Text becomes an integer, number, boolean or null where the schema allows it (white space around such values is ignored); `xsi:nil="true"` is null. Elements and attributes the schema doesn't declare are kept by local name, so `additionalProperties: false` reports them. - A body that isn't well-formed is `malformed-xml` (`request.body.malformed`, answered with 400; `response.body.malformed`), with its line and column. Document type declarations are refused, so external entities and entity expansion are errors. A SOAP service described in WSDL 1.1 is served after [`apigenie convert --to openapi31`](/docs/reference/cli/convert#wsdl-11-input): the converted document describes the SOAP envelopes with these `xml` objects. --- # Contract testing (validating proxy) Source: https://apigenie.pl/docs/reference/server/contract-testing Part of the reference of [apigenie-server](https://apigenie.pl/docs/reference/server.md). Its other pages: [Responses](https://apigenie.pl/docs/reference/server/responses.md), [Scenarios and extensions](https://apigenie.pl/docs/reference/server/scenarios.md), [Scripts](https://apigenie.pl/docs/reference/server/scripts.md), [Document store](https://apigenie.pl/docs/reference/server/store.md), [Several services](https://apigenie.pl/docs/reference/server/services.md), [Validation and security](https://apigenie.pl/docs/reference/server/validation.md), [Session recording and replay](https://apigenie.pl/docs/reference/server/recording.md), [AsyncAPI](https://apigenie.pl/docs/reference/server/asyncapi.md), [Protobuf / gRPC](https://apigenie.pl/docs/reference/server/grpc.md), [GraphQL](https://apigenie.pl/docs/reference/server/graphql.md), [Configuration](https://apigenie.pl/docs/reference/server/configuration.md), [Dashboard and admin API](https://apigenie.pl/docs/reference/server/dashboard.md), [TLS](https://apigenie.pl/docs/reference/server/tls.md). With `--proxy-to`, an OpenAPI document is not mocked: every request goes to the real server, and the mock checks the request and the server's response against the document. (A GraphQL schema and an AsyncAPI document's WebSocket, MQTT and HTTP channels work the same way, with checks of their own: see [GraphQL contract testing](/docs/reference/server/graphql#contract-testing-of-a-graphql-api), [WebSocket contract testing](/docs/reference/server/asyncapi#contract-testing-of-a-websocket-api), [MQTT contract testing](/docs/reference/server/asyncapi#contract-testing-of-mqtt-channels) and [HTTP channels](/docs/reference/server/asyncapi#contract-testing-of-http-channels).) Point your tests, your frontend or a load test at the mock instead of the server, and the traffic becomes a contract test. To send the requests yourself, from `.http` files or generated from the document, with the same checks and reports, use [`apigenie test`](/docs/reference/cli/test). For the checks and what report and enforce mean, explained with a server to try them on, see [What the validating proxy checks](/docs/concepts/what-the-proxy-checks). ```sh apigenie-server openapi.yaml --proxy-to http://localhost:8080 --report contract.json --fail-on errors ``` The upstream gets the request as it came, without the mock's `__` query parameters and `X-Apigenie-Mock-*` headers, with `Via`, `X-Forwarded-For`, `X-Forwarded-Host` and `X-Forwarded-Proto`, and `Accept-Encoding: identity` so that bodies can be checked. A path in the URL (`http://localhost:8080/api`) is put before the request's path. The admin API, CORS preflights and answers of scripts' `onRequest` stay local; the global network simulation, a request's `Prefer: delay=` or `drop=`, and scripts' `onResponse` apply to the upstream's responses. Scenario rules and examples don't: nothing is mocked, unless the server fails in fallback mode (below). **What is checked.** Each problem is a violation with a check, a severity and a location: | Check | Severity | When | | --- | --- | --- | | `request.path-or-method.unknown` | warn | The document has no operation for the method and path. | | `request.operation.deprecated`, `request.parameter.deprecated` | info | A deprecated operation or parameter is used (the response gets `Deprecation: true`). | | `request.authorization.missing`, `request.authorization.rejected` | error | No credentials for any security requirement; credentials other than the configured ones (`security.mode: enforce`). | | `request.authorization.oauth2-scheme`, `request.authorization.oauth2-scope` | warn | `apigenie test` only: a request with an OAuth 2 token for an operation that has no OAuth 2 or OpenID Connect scheme; a token requested with scopes the operation doesn't declare, or without those it requires. | | `request.path.incompatible`, `request.query.incompatible`, `request.header.incompatible`, `request.cookie.incompatible` | error | A parameter is missing or doesn't match its schema (every style). | | `request.query.unknown` | warn | An undeclared query parameter (`validation.unknown_query_parameters: error`). | | `request.content-type.incompatible`, `request.body.malformed`, `request.body.incompatible` | error | The body's media type isn't declared, the body can't be parsed (JSON, XML, multipart), or doesn't match its schema (for XML, see [XML bodies](/docs/reference/server/validation#xml-bodies)). | | `response.status.unknown` | error for 2xx, else warn | No response covers the status (exact code, then `2XX`, then `default`). | | `response.status.default` | info | Only `default` covers the status. | | `response.status.server-error` | info | The server answered with 5xx. | | `response.content-type.incompatible` | error | The response's media type isn't one of the declared ones. | | `response.body.incompatible`, `response.body.malformed` | error | The body is missing, doesn't match its schema (`writeOnly` properties aren't required), or isn't JSON or XML where the media type says so. | | `response.body.unexpected` | warn | A body where the response declares no content. | | `response.body.unvalidatable` | info | A body that can't be checked: binary, compressed. | | `response.header.incompatible` | error | A declared header is missing when required, or doesn't match its schema. | | `response.header.undefined` | off | A header the response doesn't declare (common ones such as `Date` or `ETag` aside). | `contract.severity` in the configuration changes a check's severity (`error`, `warn`, `info`) or turns it off (`ignore`). **Report or enforce.** By default a proxy reports only (`validation.request` and `validation.response` are `log` unless the configuration says otherwise), since test suites send invalid requests on purpose to see the server refuse them. Every response then carries the violations of its exchange: ```http X-Apigenie-Mock-Source: proxy X-Apigenie-Mock-Operation: getPet X-Apigenie-Mock-Violations: 1 X-Apigenie-Mock-Violations-Detail: [{"location":["response","body","/id"],"check":"response.body.incompatible","code":"type","severity":"error","message":"expected type integer, found string"}] ``` The detail is cut at 8 KB, with a last item counting what was left out. The log has the same violations, `upstreamStatus` for each request, and `fallback: true` for the mock's own answers in fallback mode. `--strict` (or `enforce` in the configuration) turns errors into answers. A request with an error doesn't reach the server: it gets 401 or 403 (security), 415 (media type), 400 (malformed body) or 422. A response with an error is replaced by a 502: ```json { "type": "https://apigenie.pl/mock/errors#invalid-upstream-response", "title": "The upstream response does not match the specification", "status": 502, "detail": "response.body/id: expected type integer, found string", "validation": [{"location": "response.body/id", "code": "type", "message": "expected type integer, found string", "severity": "error", "check": "response.body.incompatible", "path": ["response", "body", "/id"]}], "upstream": {"status": 200, "contentType": "application/json"} } ``` Warnings and notes never block anything. A server that can't be reached is answered with 502 (`upstream-unreachable`, `upstream-bad-response`, `upstream-response-too-large`), one that doesn't answer in time with 504 (`upstream-timeout`). **Fallback mode.** With `--proxy-mode fallback` (or `proxy.mode: fallback`), every request still goes to the server first, but the mock answers itself, as it would without `--proxy-to` (examples, generated data, scenario rules, `Prefer`), when the server can't be reached, doesn't answer in time, or answers 404 or 501 for an operation of the document. A frontend can then work against a server that is down or only partly implemented. The answer says so: ```http X-Apigenie-Mock-Source: generated X-Apigenie-Mock-Upstream-Status: 404 ``` The log record has `fallback: true` and `upstreamStatus` (absent when the server didn't answer). The server's 404 or 501 isn't checked against the document, so it isn't a `response.status.unknown` violation. Requests for no operation of the document are not the mock's to answer: the server's 404 reaches the client. An answer that isn't HTTP or is too large is still a 502: the server did answer. **Record and replay.** `--record-dir DIR` writes each exchange the server answered as a stub file, `getPet-1.yaml` (`GET_health-1.yaml` for a route of no operation; numbers already taken are skipped), and `--stubs DIR` makes a mock without `--proxy-to` answer with them: ```sh apigenie-server openapi.yaml --proxy-to http://localhost:8080 --record-dir recorded apigenie-server openapi.yaml --stubs recorded ``` ```yaml stubs: - name: getPet-1 operationId: getPet request: method: GET path: /pets/1 # as the client sent it, without the proxy's prefix query: full=true # without the mock's __ parameters headers: {Accept: application/json, Authorization: "[redacted]"} # match: {headers: [X-Tenant]} # these request headers must be equal too response: status: 200 headers: {Content-Type: application/json, ETag: '"v1"'} body: {id: 1, name: Rex} # JSON; text: for other text, base64: for bytes ``` A request matches a stub when its method, path, query (in any order) and body (JSON compared as JSON) are the same; headers count only when `match.headers` names them. The first stub that matches answers, files in name order; its source is `stub:getPet-1`. Requests still go through security and request validation; the answer isn't checked again. Answers the mock gave or replaced (fallback, `--strict`) aren't recorded. The values of `Authorization`, `Cookie`, `Set-Cookie`, `Proxy-Authorization` and `X-Api-Key` are written as `[redacted]` (`proxy.redact` sets the list), and what the connection or the proxy adds (`Host`, `User-Agent`, `Via`, `X-Forwarded-*`, `Date`, ...) is left out. A recorded header that matters for matching has to be restored by hand. **HAR.** `--record-har session.har` writes every exchange through the proxy as an HTTP Archive (HAR 1.2) when the server stops: the server's answers and the mock's own (fallback answers, rejected requests, replaced responses, the problems of a failed server). Each entry's `comment` is `proxy` or `mock`, and `_apigenie` has the source, the operation, the server's status, `fallback` and the violations. Headers of `proxy.redact` are written as `[redacted]`; binary bodies are in Base64, and bodies above 1 MiB are left out (their sizes stay). Browsers' developer tools, Postman and HAR viewers read it. **Coverage.** The mock counts what the traffic exercised: each operation, its request body (seen with a 2xx or 3xx answer) and each declared response (`200`, `4XX`, `default`). An operation is `covered` when all of these were seen, `partial`, or `not-tested`; requests for no operation are listed as undocumented. Mocked traffic is counted too, without `--proxy-to` or in fallback mode; the report tells the two apart: `summary.sources` and each operation's `sources` count the answers of the server (`proxy`) and of the mock (`mock`, also the problems of a failed server and rejected requests), `mockedResponses` the statuses the mock answered with, and, when the mock answered any, the summary printed at the end has a `Sources:` line. **Reports.** `GET /__apigenie/contract` returns the report at any time, and `DELETE` starts it over (a reload does too). When the server stops (Ctrl+C or `POST /__apigenie/shutdown`) it prints a summary, writes `--report` (JSON) and `--report-junit` (one test case per operation, skipped when not tested, failed with error violations; one per undocumented route; one for the coverage threshold), and exits with 5 when `--fail-on` or `--min-coverage` isn't met. In CI: ```sh apigenie-server openapi.yaml --proxy-to http://localhost:8080 --port 4010 \ --report contract.json --report-junit contract.xml --fail-on errors --min-coverage 80 & API_URL=http://localhost:4010 npm test curl -X POST http://localhost:4010/__apigenie/shutdown wait $! # 5 when the contract failed ``` The JSON report has `summary` (requests, their sources, violations by severity, coverage of branches and operations, the gate with its reasons), `operations` (the JSON `pointer` of the operation in the document, e.g. `/paths/~1pets/get`, requests, responses seen and missing, undeclared statuses, sources and the mock's statuses, violations by check), `undocumented` and `violations` (each distinct one with its count and the first time it was seen). Its `formatVersion` is the version of the format, which changes only when a member is removed or changes meaning (see [Compatibility](/docs/reference/cli/compatibility)); `version`, its former name, is deprecated and will be removed in the next release. The JSON Schema of the members the OpenAPI, AsyncAPI, GraphQL and gRPC reports share is [`apigenie-contract-report.json`](https://apigenie.pl/schemas/apigenie-contract-report.json). --- # Session recording and replay Source: https://apigenie.pl/docs/reference/server/recording Part of the reference of [apigenie-server](https://apigenie.pl/docs/reference/server.md). Its other pages: [Responses](https://apigenie.pl/docs/reference/server/responses.md), [Scenarios and extensions](https://apigenie.pl/docs/reference/server/scenarios.md), [Scripts](https://apigenie.pl/docs/reference/server/scripts.md), [Document store](https://apigenie.pl/docs/reference/server/store.md), [Several services](https://apigenie.pl/docs/reference/server/services.md), [Validation and security](https://apigenie.pl/docs/reference/server/validation.md), [Contract testing (validating proxy)](https://apigenie.pl/docs/reference/server/contract-testing.md), [AsyncAPI](https://apigenie.pl/docs/reference/server/asyncapi.md), [Protobuf / gRPC](https://apigenie.pl/docs/reference/server/grpc.md), [GraphQL](https://apigenie.pl/docs/reference/server/graphql.md), [Configuration](https://apigenie.pl/docs/reference/server/configuration.md), [Dashboard and admin API](https://apigenie.pl/docs/reference/server/dashboard.md), [TLS](https://apigenie.pl/docs/reference/server/tls.md). A run of the server, every exchange of every service and protocol, kept as files that a replay reads back as a mock, in a test suite too. ## Session recording `--record DIR` keeps a run whole: every exchange the server answered, of every service and every protocol, in the order it happened, each marked with the test that sent it, as files a replay can read and a reviewer can diff: ```sh apigenie-server openapi.yaml --proxy-to http://localhost:8080 --record sessions/checkout apigenie-server --config apigenie-server.yaml --record sessions/checkout # several services apigenie-server session export sessions/checkout --har checkout.har ``` ```text sessions/checkout/ session.yaml # the session and the exchanges in order pets/0001-getPet.yaml # an HTTP exchange of the service pets (a stub) pets/0002-createPet.yaml events/0003-ws-in-sendMessage.yaml # a WebSocket message from a client events/0004-ws-out-sendMessage.yaml # a message to it chat/0005-Chat.Talk.yaml # a gRPC call with its messages (a stub) ``` A server of one document writes the files in `DIR` itself (`--stubs DIR` and the GraphQL examples skip `session.yaml`). `session.yaml` names the session (the directory's name unless `record.name` or `/record/start` says), the server, when it started and stopped, the services (name, document, `specification`, the SHA-256 of the document's bytes, mount) and the exchanges: ```yaml name: checkout server: apigenie-server 1.0.0 started: 2026-10-13T10:00:00.000Z stopped: 2026-10-13T10:00:42.512Z services: - {name: pets, spec: pets.yaml, specification: openapi, sha256: cfada1c0..., mount: /pets} - {name: events, spec: events.yaml, specification: asyncapi, sha256: 9b2f..., mount: /events} exchanges: - {sequence: 1, id: 2, service: pets, test: checkout-happy, kind: http, time: 2026-10-13T10:00:01.555Z, durationMs: 3, source: proxy, summary: GET /pets/1 200, file: pets/0001-getPet.yaml} - {sequence: 3, id: 7, service: events, test: checkout-happy, kind: ws, time: ..., source: mock, summary: ws-in rooms/7 notice, file: events/0003-ws-in-sendMessage.yaml} ``` **The exchange files.** Each has a `session` note (the index's line) next to the protocol's own form, so what already reads that form reads the file: - `http`: `{session, stubs: [stub]}`, the stub form of [`--record-dir`](/docs/reference/server/contract-testing), so `--stubs sessions/checkout/pets` makes a mock answer with the service's exchanges as before (the first matching stub answers, whatever the test). OpenAPI exchanges, AsyncAPI HTTP channels and GraphQL requests that aren't one operation answered with JSON (batches, errors, GraphiQL). The answer is kept as the client got it, less the CORS headers the server adds to every answer. The request's `X-Apigenie-Test` header is left out. - `graphql`: one operation and its answer, in the [example form](/docs/reference/server/graphql#examples) (`name`, `operation`, `query`, `variables`, `response`, `status`) the mock's examples load; the note's `path` is the endpoint. - `grpc`: `{session, stubs: [stub]}`, the stub form of a `.proto` file's [`--record-dir`](/docs/reference/server/grpc#proxy-and-record), with the whole streams (at most 100 messages per side); the note's `order` (`[in, out, in, out]`) says which side each message came from, `code` the status. The `x-apigenie-test` metadata is left out. - `ws` and `mqtt`: one file per message of either side: ```yaml session: {sequence: 3, id: 7, service: events, test: checkout-happy, kind: ws, time: ..., source: mock} message: direction: in # from the client; out: to it channel: rooms/7 # the channel's address, and the route it matched route: rooms/{roomId} operation: sendMessage name: notice contentType: application/json connection: 4 json: {text: hi} # text: for other text, base64: for bytes ``` **Tests.** An exchange's `test` is the `X-Apigenie-Test` header of the request or of the WebSocket handshake, or the `x-apigenie-test` metadata of a gRPC call; MQTT messages have none of their own. Without one, it is the current **mark**: `POST /__apigenie/record/mark {"test": "checkout-happy"}` names the test of the exchanges to come (`{}` clears it), for clients that can't send the header. A Playwright suite sends the header with `page.setExtraHTTPHeaders` and marks the test in `beforeEach`. **Order.** `sequence` numbers the exchanges in the order they completed, which is the log's order; a request still in flight when a short one is answered comes after it. Each exchange keeps its `time` and `durationMs` (a gRPC call its `started`), so a tool can sort by arrival. What isn't an exchange isn't recorded: requests the client abandoned or the simulation dropped, CORS preflights, the admin API's own traffic, the dashboard. **Redaction.** The values of `Authorization`, `Cookie`, `Set-Cookie`, `Proxy-Authorization` and `X-Api-Key` are written as `[redacted]`, as in `--record-dir`. `--record-redact` (or `record.redact`) adds header and metadata names, and JSON pointers, which start with `/`, to values of JSON bodies, message payloads, gRPC messages and GraphQL variables and answers: `--record-redact X-Session --record-redact /owner/password`. A pointer is matched exactly (`/items/0/key` is the first item's key). A redacted request body no longer matches on replay. **Start and stop.** `--record` records from the start and writes `session.yaml` when the server stops; the startup line says `Recording the session to DIR` (`record` in JSON). The admin API records a part of a run: `POST /__apigenie/record/start {"dir": "sessions/run-7", "name": "run 7"}` (`dir` defaults to `record.dir`; 409 while a session is on, 400 for a directory that isn't empty), `POST /__apigenie/record/stop` (the session's `dir`, `name`, `exchanges`, `file`; 409 without one), `GET /__apigenie/record` (`recording`, and the same while one is on, `test` for the mark). The [dashboard](/docs/reference/server/dashboard#dashboard)'s Traffic screen has Record session and Save session. A session has at most 10 000 exchanges: past that it counts on but writes no more files, with one warning in the log and `truncated: true` in the index. When the server dies before writing `session.yaml`, the exchange files tell: `session export` rebuilds the index from their notes. **Export.** `apigenie-server session export DIR --har FILE` writes the HTTP exchanges, GraphQL operations (as `POST` requests to the endpoint) and gRPC calls (as `POST` requests with `application/grpc+json` bodies, the messages as JSON arrays, and a `grpc-status` header) as a HAR 1.2 file, in the session's order, each entry with `_apigenie.service`, `test`, `sequence` and `kind`; WebSocket and MQTT messages have no form in HAR and are left out (the command says how many). URLs keep the services' mount prefixes. The design is ADR-168. ## Session replay `--replay DIR` serves the services of a [recorded session](#session-recording) the way they answered when it was recorded, without the real servers: each request gets the next unused recorded exchange of its test that matches it, so a test suite replays the same run every time, and fails when the application asks for something the recording doesn't have. ```sh apigenie-server openapi.yaml --record sessions/checkout --proxy-to http://localhost:8080 # once apigenie-server openapi.yaml --replay sessions/checkout # every run apigenie-server --config apigenie-server.yaml # replay: {dir: sessions/checkout}, several services ``` **Tests and order.** A request's test is its `X-Apigenie-Test` header (of a WebSocket handshake too) or a gRPC call's `x-apigenie-test` metadata. It draws from the exchanges recorded under that test, in their order: the first `GET /pets/1` of test `checkout` gets the first one recorded for it, the second the second, and a third matches none. Tests replay side by side, each with its own counters, so the parallel workers of a suite don't take each other's exchanges. Requests without a tag share one test that draws from the whole session in order, for suites that don't tag their requests (and MQTT, whose clients send none). `POST /__apigenie/replay/reset {"test": "checkout"}` (or with the header) restarts a test's counters, at the start of each test; without a test it restarts every test. **What is compared.** The method and path; the query, in any order; the headers the recording kept (not `Host`, `User-Agent`, `Accept-Encoding` and the other headers a client changes from run to run: `Date`, `Origin`, `Referer`, `Accept-Language`, `Cache-Control`, the `Sec-*` headers, `traceparent`, `X-Request-Id`, ...), a recorded `[redacted]` value standing for any; and the body, JSON regardless of key order and number formatting. Left out: - strings that are both RFC 3339 dates or date-times (`2026-10-13`, `2026-10-13T10:00:00Z`), in bodies and query parameters; - the fields of an OpenAPI request body that its schema marks `readOnly`, which a client sends back as it got them (`id`, `createdAt`); - what `--replay-ignore` (or `replay.ignore`) names: headers, and JSON pointers into bodies, messages, gRPC messages and GraphQL variables (`--replay-ignore /cartId --replay-ignore /items/*/addedAt`; `*` stands for any index or key). **When nothing matches.** `--replay-missing fail`, the default, answers with a 502 `application/problem+json` naming the closest recording (of the same test and kind; the same operation first, then the fewest differences) and how the request differs from it: ```json { "type": "https://apigenie.pl/mock/errors#replay-missing", "title": "No recorded exchange matches", "status": 502, "detail": "no recorded exchange of test 'checkout' matches POST /carts; the closest, pets/0004-createCart.yaml, differs at /items/0/quantity", "test": "checkout", "closest": {"file": "pets/0004-createCart.yaml", "sequence": 4, "summary": "POST /carts 201", "used": false}, "differences": [{"where": "/items/0/quantity", "recorded": 1, "received": 2}] } ``` `used: true` says the matching exchange was replayed already in that test (a request sent once more than when it was recorded). `generate` lets the mock answer (stubs, the document store, examples, generated values); `passthrough` forwards the request to `--proxy-to`, and with `--replay-update` records the run (replayed and forwarded exchanges alike) into `DIR.update` and puts it in place of `DIR` when the server stops: the way to refresh a recording after the application changed on purpose. A request that matched none is reported either way. **Every protocol.** - HTTP (OpenAPI, AsyncAPI HTTP channels, GraphQL batches): the recorded status, headers and body, with `X-Apigenie-Mock-Source: replay:0002-getPet.yaml`. - GraphQL queries and mutations: by operation name, query (formatting aside) and variables; the recorded answer. One none matches gets a `REPLAY_MISSING` error (status 502) with the same members in `extensions.replay`. - GraphQL subscriptions (graphql-transport-ws, graphql-ws, SSE) and AsyncAPI WebSocket channels: a connection replays a recorded connection of its route and test as the server's side: what the server sent first (`connection_ack`, the first scheduled messages) at once, then, after each message the client sends that is the recorded one, the messages that followed it. The subscriptions' ids are the client's own. A message that isn't the recorded one gets the problem as a message (GraphQL: an `error` message). The scheduled messages and generated replies are off. - MQTT: a subscriber of a topic gets the messages a subscriber got before any client published; a published message that is the next recorded one gets the messages that followed it. - gRPC: unary and server-streaming calls by their metadata and first request, client streams by all their requests, bidirectional streams in their recorded interleaving (the session's `order`): a message the client sends that isn't the recorded one fails the call. A call none matches fails with `FAILED_PRECONDITION`, the problem in the `apigenie-replay-problem` trailer. WebSocket and MQTT messages can't be forwarded one at a time: under `passthrough` they are answered as under `fail`. **The report.** When the server stops it prints how many recorded exchanges were replayed, the ones never replayed and the requests that matched none, with their tests (with `--log-format json`, one `{"event": "replay", ...}` line), and exits with status 5 if there are any; `--replay-update` prints the report but doesn't fail. `GET /__apigenie/replay` gives the same report at any time, with `passed` and the exchanges each test used since its reset. The startup line says `Replaying the session in DIR (N exchanges, missing: fail)` (`replay` in JSON). A document that changed since the session was recorded (another SHA-256) and a service the session lacks are warned about at startup. `--stubs`, the GraphQL examples and the gRPC stubs stay: the per-exchange forms, where the first match answers whatever the test. The design is ADR-169. ## Replay in a test suite A Playwright suite recorded against the real backend once replays it in every run, each test with its own exchanges. The server starts with the suite and every request of a test carries its name: ```ts // playwright.config.ts import { defineConfig } from "@playwright/test"; export default defineConfig({ webServer: { command: "apigenie-server openapi.yaml --port 4010 --replay recordings/checkout", url: "http://127.0.0.1:4010/__apigenie", reuseExistingServer: false, }, globalTeardown: "./replay-teardown.ts", }); ``` ```ts // checkout.spec.ts import { expect, test } from "@playwright/test"; const admin = "http://127.0.0.1:4010/__apigenie"; test.beforeEach(async ({ page }, testInfo) => { const name = testInfo.titlePath.join(" > "); // every request of the page names the test, the API's included await page.setExtraHTTPHeaders({ "X-Apigenie-Test": name }); // the test starts at its first recorded exchange, also when it is retried await fetch(`${admin}/replay/reset`, { method: "POST", body: JSON.stringify({ test: name }) }); }); test("checks out a cart", async ({ page }) => { await page.goto("/cart"); await page.getByRole("button", { name: "Check out" }).click(); await expect(page.getByText("Thank you")).toBeVisible(); }); ``` ```ts // replay-teardown.ts: the run fails when the application drifted from the recording export default async function teardown() { const report = await (await fetch("http://127.0.0.1:4010/__apigenie/replay")).json(); if (!report.passed) { throw new Error( `the replay failed: ${report.neverReplayedCount} exchanges never replayed, ` + `${report.unmatchedCount} requests matched none: ${JSON.stringify(report.unmatched, null, 2)}`, ); } } ``` The server answers the CORS preflight of the header for a page served from another origin. To record the suite, run it once with `--record recordings/checkout --proxy-to https://staging.example.com` in place of `--replay`: the same header tags the recorded exchanges with the tests. Playwright stops its web servers without letting them finish, so such a recording has no `session.yaml`; the replay reads the index from the exchange files, as `session export` does. On CI, a request the recording lacks gets a 502, so the test that sent it fails at that step, with the closest recording and the differences in the response; the teardown fails the run when a test no longer sends what was recorded (exchanges never replayed). A job that runs the server itself sees the same as its exit status: ```sh apigenie-server openapi.yaml --port 4010 --replay recordings/checkout --log-format json > replay.log & server=$! npx playwright test curl -s -X POST http://127.0.0.1:4010/__apigenie/shutdown wait $server # 5 when the run drifted from the recording; replay.log has the report ``` --- # AsyncAPI Source: https://apigenie.pl/docs/reference/server/asyncapi Part of the reference of [apigenie-server](https://apigenie.pl/docs/reference/server.md). Its other pages: [Responses](https://apigenie.pl/docs/reference/server/responses.md), [Scenarios and extensions](https://apigenie.pl/docs/reference/server/scenarios.md), [Scripts](https://apigenie.pl/docs/reference/server/scripts.md), [Document store](https://apigenie.pl/docs/reference/server/store.md), [Several services](https://apigenie.pl/docs/reference/server/services.md), [Validation and security](https://apigenie.pl/docs/reference/server/validation.md), [Contract testing (validating proxy)](https://apigenie.pl/docs/reference/server/contract-testing.md), [Session recording and replay](https://apigenie.pl/docs/reference/server/recording.md), [Protobuf / gRPC](https://apigenie.pl/docs/reference/server/grpc.md), [GraphQL](https://apigenie.pl/docs/reference/server/graphql.md), [Configuration](https://apigenie.pl/docs/reference/server/configuration.md), [Dashboard and admin API](https://apigenie.pl/docs/reference/server/dashboard.md), [TLS](https://apigenie.pl/docs/reference/server/tls.md). For an AsyncAPI 3.x document the mock plays the application the document describes. Servers with the `ws`, `http` and `mqtt` protocols are served (and `wss`, `https` and `mqtts` over TLS with `--tls-cert`, cleartext without). Kafka and AMQP channels aren't served, but are read from a real cluster or broker with `--proxy-to kafka://` ([below](#contract-testing-of-kafka-channels)) and `--proxy-to amqp://` ([below](#contract-testing-of-amqp-channels)); the others are listed as not served. - **WebSocket.** A client connects to a channel's address under its server's `pathname` (`ws://127.0.0.1:4010/v1/rooms/42` for `rooms/{roomId}`). It gets the messages of the channel's `send` operations, one after another, every second by default: the message's examples in turn, or values generated from its payload schema (always with `--dynamic`). What it sends is checked against the `receive` operations: a match is answered with the operation's `reply`, anything else with a problem details message. - **HTTP.** A `receive` operation takes messages with `POST` (or its HTTP binding's method) and answers 202, or 200 with its reply; an invalid message gets 422. A `send` operation answers `GET` with a message. - **MQTT.** A broker on its own port takes subscriptions to the channels' topics (wildcards included: a parameter of an address takes its default, first enum value or example) and publishes the `send` operations' messages with their MQTT binding's QoS. Messages clients publish go to the other subscribers, as with any broker, once they match a `receive` operation; its reply is published to the reply channel's topic. MQTT 3.1.1 and 5 clients are served; MQTT 5 subscribers also get the MQTT 5 properties of a message: its headers as user properties (the first example's, else generated from the header schemas), and the payload format indicator, content type, correlation data and response topic of its MQTT binding (generated from their schemas when they are schemas) and the operation binding's message expiry. An MQTT 5 client's properties and user properties are checked as the [MQTT proxy](#contract-testing-of-mqtt-channels) checks them; its request is answered on the topic of its reply address user property, or on its Response Topic when the reply channel has `address: null`, with its correlation id and Correlation Data. Retained messages expire with their Message Expiry Interval. `x-apigenie-mock` on a `send` operation sets `interval` (milliseconds), `count` (messages per client, 0 for no limit), `jitter`, `messages` (the names to send) and `publish: false`. ```yaml operations: sendNotices: action: send channel: {$ref: '#/channels/room'} x-apigenie-mock: {interval: 500, count: 10} ``` The log has `ws-open`, `ws-in`, `ws-out` and `ws-close` events for WebSocket clients and `mqtt-subscribe`, `mqtt-in`, `mqtt-out` and `mqtt-unsubscribe` ones for MQTT, with the channel's address, the operation and the message. When the server stops, WebSocket clients get the close code 1001 and MQTT 5 clients a DISCONNECT; after a reload they reconnect to the new version. ## Contract testing of a WebSocket API With `--proxy-to ws://host:port` an AsyncAPI document's WebSocket channels aren't mocked: each client of a channel gets a connection to the real server, and every message of either side is checked against the document. Point a frontend or a test suite at the mock instead of the server. ```sh apigenie-server chat.yaml --proxy-to ws://localhost:9000 --report contract.json --fail-on errors ``` The mock connects to the server first, with the client's path under the URL's prefix, its query, `Origin`, cookies, `Authorization` and `Sec-WebSocket-Protocol`, plus `Via` and `X-Forwarded-*`; the client gets the subprotocol the server chose. A server that can't be reached answers the client's handshake with 502 (504 when it doesn't answer in time), and a server that refuses it (401, 404, ...) has its answer passed on. What clients send is checked against the channel's `receive` operations, what the server sends against its `send` operations. A client's message of an operation with a `reply` on the same channel waits for its reply: the first message the server sends that is one of the reply's messages is checked as that reply (logged as `name (reply)` with the request's operation), not against the `send` operations. Messages are relayed whole (fragments are put together first); pings are answered on each side; a close frame goes on with its code. No WebSocket extension is negotiated (`permessage-deflate` is left out of the handshake). HTTP channels go to the same server (see [below](#contract-testing-of-http-channels)); the MQTT channels to the broker of a second `--proxy-to mqtt://...`, or they keep being mocked. | Check | Severity | When | | --- | --- | --- | | `message.incompatible` | error | The message matches none of the messages of the channel's operations in its direction. | | `message.malformed` | error | The message isn't JSON where JSON is expected. | | `message.frame.unexpected` | warn | A binary frame for a text or JSON message, or a text frame for a binary one (`image/png`, `application/octet-stream`, Protobuf, Avro, ...). | | `message.qos.unexpected` | warn | MQTT: a client published at a QoS other than the one of the operation's MQTT binding. | | `channel.parameter.invalid` | error | A parameter of the channel's address (a path segment, a topic level) has a value outside the parameter's `enum`. | | `channel.receive.undeclared` | warn | A client sent a message on a channel the application has no `receive` operation for. | | `channel.send.undeclared` | warn | The server sent a message on a channel it has no `send` operation for. | | `message.reply.uncorrelated` | error | The reply's `correlationId` (in the payload) isn't the request's, or is missing. | | `operation.query.invalid` | error | HTTP channels: the request's query doesn't match the `query` of the operation's HTTP binding. | | `message.headers.invalid` | error | HTTP channels: the request's or the reply's header fields don't match the message's `headers` or its HTTP binding's `headers`. | | `message.cloudevents.invalid` | error | A [CloudEvents](https://cloudevents.io) message (structured mode: an `application/cloudevents+json` content type; binary mode: attribute headers such as `ce_id`) lacks `id`, `source`, `specversion` or `type`, or has an invalid attribute: a `specversion` other than `1.0`, an empty `id`, `type` or `subject`, a `source` that is no URI-reference, a `time` that is no RFC 3339 date-time. Checked over every transport, in the headers of the binding the document uses (none over MQTT 3.1.1). | `validation.request` sets what happens to the clients' messages and `validation.response` to the server's: `log` by default for a proxy (reported, and forwarded), `enforce` with `--strict`. In enforce mode a message with an error isn't forwarded, and the client gets a problem message instead (`asyncapi.validate_incoming` stays the mock's setting): ```json {"type": "https://apigenie.pl/mock/errors#invalid-upstream-message", "title": "The upstream's message doesn't match the specification", "status": 422, "channel": "rooms/1", "direction": "upstream", "validation": [{"location": "message/text", "code": "type", "message": "expected type string, found integer", "check": "message.incompatible", "severity": "error"}]} ``` A client's message gets `#invalid-message` with `"direction": "client"`. The log has the `ws-open`, `ws-in`, `ws-out` and `ws-close` events with the operation, the message's name, the violations and `source: proxy` (`mock` for what the proxy answered itself). `contract.severity` changes the checks' severities as for the other proxies. **Coverage and reports.** Each message of each operation is a branch: it is covered once a valid one went by. An operation is `covered`, `partial` or `not-tested`; a message that matches none is counted for the operation it was checked against first. `GET /__apigenie/contract` returns the report (`"specification": "asyncapi"`, connections, messages in and out, channels, operations, violations), `--report` and `--report-junit` write it when the server stops (a test case per operation), and `--fail-on` and `--min-coverage` (the share of messages) make the exit status 5. ## Contract testing of MQTT channels With `--proxy-to mqtt://host:port` the mock's broker relays to a real broker: each client that connects to the mock gets a connection of its own to the broker, and every message published either way is checked against the document. ```sh apigenie-server devices.yaml --proxy-to mqtt://localhost:1884 --mqtt-port 1883 --report contract.json apigenie-server events.yaml --proxy-to ws://localhost:9000 --proxy-to mqtt://localhost:1884 ``` The upstream connection has the client's MQTT version, client identifier (the one the mock assigns when the client gives none), clean start, keep-alive, will, user name and password. The client's CONNECT gets the broker's CONNACK, a refusal included; a broker that can't be reached is answered with "server unavailable" (return code 3, MQTT 5 0x88). Subscriptions are the broker's: the SUBACK is its answer, and the broker decides who gets which message. What clients publish is checked against the topic's channel's `receive` operations, with the QoS of the operation's MQTT binding when it gives one (`message.qos.unexpected`); what the broker delivers against the `send` operations. A subscriber also gets other clients' messages, so on a channel without `send` operations a delivery is checked against the `receive` operations. Topics of no channel are relayed unchecked (debug level in the log). In enforce mode a client's message with an error isn't forwarded (MQTT 5 clients get reason code 0x99 in their acknowledgement), and a broker's message with an error isn't delivered. A client that disconnects is disconnected from the broker; one whose connection is lost has its upstream connection dropped too, so the broker publishes its will; a client the broker disconnects is disconnected. A reload keeps the clients connected. The log has `mqtt-connect`, `mqtt-subscribe`, `mqtt-in`, `mqtt-out`, `mqtt-unsubscribe` and `mqtt-disconnect` events with `source: proxy` (`mock` for what the proxy decided itself), and coverage and reports work as for WebSocket. MQTT 5 properties are relayed both ways: user properties, payload format indicator, content type, response topic, correlation data and message expiry (not the topic alias and subscription identifiers, which belong to one connection). An MQTT 5 message's are checked against the MQTT bindings (0.2.0): | Binding | Checked (`message.properties.invalid`, `error`) | | --- | --- | | message `payloadFormatIndicator` | The Payload Format Indicator is the same (absent counts as 0) | | message `contentType` | The Content Type is the same, ignoring case | | message `correlationData` | Correlation Data is present and matches the schema | | message `responseTopic` | A Response Topic is present, the string given or matching the schema | | operation `messageExpiryInterval` | A Message Expiry Interval is present and no longer | Its user properties are its headers, checked against the message's `headers` (`message.headers.invalid`). MQTT 3.1.1 messages have no properties: nothing is checked for them. The report counts the messages whose bindings state properties, checked or not: `summary.properties: {"checked": 3, "unchecked": 1}`, `properties` of each operation, and a summary line `MQTT 5 properties: checked on 3 messages, not on 1 (MQTT 3.1.1)`. A client's QoS 1 and 2 messages are acknowledged by the mock before the broker acknowledges them, and the mock delivers at most QoS 1. An `mqtts://` broker (port 8883 by default) is reached over TLS and verified as `https://` upstreams are (see [TLS](/docs/reference/server/tls)). ## Contract testing of Kafka channels There is no Kafka broker in the mock. With `--proxy-to kafka://host:port` (port 9092 by default; `kafkas://`, port 9093, over TLS) the server is a client of the real cluster, a validating tap: it reads the topics of the document's Kafka channels and checks every record on them, whoever produced it. ```sh apigenie-server shop.yaml --proxy-to kafka://localhost:9092 --report contract.json apigenie-server events.yaml --proxy-to mqtt://localhost:1883 --proxy-to kafka://localhost:9092 ``` A channel with a `kafka` or `kafka-secure` server is a Kafka channel; its topic is the channel's Kafka binding `topic`, else its address. Parameters of the address match the topic's segments, so `stock.{region}` reads `stock.eu` and `stock.us`; the cluster's topics are looked at again every 10 seconds for new ones. The tap reads every partition from the offset it had when the server started, outside any consumer group, so it never takes partitions from the application's consumers and commits no offsets. A topic the cluster doesn't have yet is reported once and read once it appears; a lost connection is reported and tried again. A record doesn't say who produced it, so the channel's operations tell. On a channel with only `send` operations it is the application's (a `kafka-out` event, checked against them); with only `receive` operations it is a client's (`kafka-in`); with both it is checked as the application's, and as a client's when that doesn't match. What is checked: | What | Checked against | Check | | --- | --- | --- | | The value | The operations' messages | `message.incompatible`, `message.malformed` | | The headers | The message's `headers` (values read as the type the schema says) | `message.headers.invalid` | | The key | The message's Kafka binding `key` (an error too when the record has none) | `message.key.invalid` (`error`) | | The partition | The channel's Kafka binding `partitions` | `message.partition.invalid` (`warn`) | | The topic | The address's parameters | `channel.parameter.invalid` | Records are on the cluster before the tap sees them, so enforce mode reports them like log mode. Kafka operations count in the coverage, `GET /__apigenie/contract`, `--report` and `--report-junit` like any other, and the report's `upstream` lists the `kafka://` URL. The log has `kafka-in` and `kafka-out` events with the topic as `channel`, the record's partition and offset in the message, and its key (as `kafka-key`) and headers as the event's headers; what the tap found or failed at are `server` events with `source: kafka`. The SASL PLAIN user and password come from `APIGENIE_KAFKA_USERNAME` and `APIGENIE_KAFKA_PASSWORD` (`apigenie test` reads them too), never from the URL. `kafkas://` brokers are verified as `https://` upstreams are (see [TLS](/docs/reference/server/tls)). The cluster needs Kafka 2.3 or later. Compressed record batches aren't read: they are reported (`3 record(s) at offset 40 compressed with zstd`) and skipped. A `kafka://` upstream goes with one document, not with [several services](/docs/reference/server/services). See ADR-170 for what the client does and doesn't do. ## Contract testing of AMQP channels There is no AMQP broker in the mock either. With `--proxy-to amqp://host:port/vhost` (port 5672 by default; `amqps://`, port 5671, over TLS; the path is the virtual host, `/%2Fcarpet-express` for `/carpet-express`, none for `/`) the server is an AMQP 0-9-1 client of the real broker, a validating tap. ```sh APIGENIE_AMQP_USERNAME=conformance APIGENIE_AMQP_PASSWORD=conformance \ apigenie-server customs.yaml --proxy-to amqp://localhost:5672/%2Fcarpet-express --report contract.json ``` A channel with an `amqp` or `amqps` server is an AMQP channel. Its AMQP channel binding says what it is: - **`is: routingKey`** (the default): the address is a routing key of `exchange.name` (of `exchange.type`, topic by default). The tap binds a queue of its own (exclusive, deleted when it disconnects) to the exchange: for a topic exchange with the address's parameters as `*` words (`customs.{country}.filing` is `customs.*.filing`), for a fanout or headers exchange with any key. Direct exchanges bind the address itself, so their addresses can't have parameters. It reads that queue, so it gets a copy of every message the exchange routes there, and the application's queues are left alone. An exchange the broker doesn't have is reported, and looked for again every 10 seconds. - **`is: queue`**, and routing keys of the default exchange: a queue the application consumes. Reading it would take the application's messages, so the tap doesn't, and says so when it starts. What `apigenie test` and the admin API send there is checked. Messages are checked as the [Kafka tap](#contract-testing-of-kafka-channels) checks records, in the same direction: their body and headers against the operations' messages, and their properties against the AMQP bindings (0.3.0) (`message.properties.invalid`, `error`): | Binding | Checked | | --- | --- | | operation `deliveryMode`, `priority`, `userId`, `replyTo` | The property is present and the same | | operation `expiration` | An expiration is present and no longer | | operation `timestamp: true` | A timestamp is present | | message `contentEncoding` | The content encoding is the same | | message `messageType` | The `type` property is the same | The log has `amqp-in` and `amqp-out` events with the routing key as `channel` and the exchange in the message; coverage and reports work as for Kafka, and enforce mode reports too. The PLAIN user and password come from `APIGENIE_AMQP_USERNAME` and `APIGENIE_AMQP_PASSWORD` (`guest` without them), never from the URL. An `amqp://` upstream goes with one document. See ADR-171. ## Contract testing of HTTP channels With `--proxy-to http://host:port` (or the `ws://` server of the WebSocket channels) an AsyncAPI document's HTTP channels go to that server through the same transport as an OpenAPI document's proxy (`Via`, `X-Forwarded-*`, 502 and 504 problems), checked against the document instead of an OpenAPI one: - A `receive` operation takes requests with its HTTP binding's method (POST by default). The request's body is checked against the operation's messages, its query against the binding's `query` schema (`operation.query.invalid`) and its header fields against the message's `headers` and HTTP binding `headers`, its traits' included (`message.headers.invalid`). A 2XX response's body and header fields are checked against its `reply`. - A `send` operation is asked with GET, as the mock serves it; a 2XX response with a body is checked against its messages (not its header fields: they are the webhook's). - Other paths get 404 and other methods 405, without the server. Query parameters and header fields are read as the type their schema says (`integer`, `number`, `boolean`, an `array` from repeated parameters); header fields the schemas don't name are left out. `apigenie test` checks the requests of HTTP channels with the same code and the same checks (see [Requests of HTTP channels](/docs/reference/cli/test/validation#requests-of-http-channels)). In enforce mode an invalid request gets 422 (`#invalid-message`) without the server, and an invalid response is replaced by 502 (`#invalid-upstream-message`). Responses carry `X-Apigenie-Mock-Source`, `X-Apigenie-Mock-Operation` and `X-Apigenie-Mock-Violations`, and each exchange counts as a message of its operation in the coverage. Responses other than 2XX and the reply's `statusCode` binding aren't checked; fallback mode, `--record-dir` and `--record-har` are for OpenAPI documents. --- # Protobuf / gRPC Source: https://apigenie.pl/docs/reference/server/grpc Part of the reference of [apigenie-server](https://apigenie.pl/docs/reference/server.md). Its other pages: [Responses](https://apigenie.pl/docs/reference/server/responses.md), [Scenarios and extensions](https://apigenie.pl/docs/reference/server/scenarios.md), [Scripts](https://apigenie.pl/docs/reference/server/scripts.md), [Document store](https://apigenie.pl/docs/reference/server/store.md), [Several services](https://apigenie.pl/docs/reference/server/services.md), [Validation and security](https://apigenie.pl/docs/reference/server/validation.md), [Contract testing (validating proxy)](https://apigenie.pl/docs/reference/server/contract-testing.md), [Session recording and replay](https://apigenie.pl/docs/reference/server/recording.md), [AsyncAPI](https://apigenie.pl/docs/reference/server/asyncapi.md), [GraphQL](https://apigenie.pl/docs/reference/server/graphql.md), [Configuration](https://apigenie.pl/docs/reference/server/configuration.md), [Dashboard and admin API](https://apigenie.pl/docs/reference/server/dashboard.md), [TLS](https://apigenie.pl/docs/reference/server/tls.md). For a `.proto` file the mock serves its services over gRPC, on the same port as HTTP: clients connect with cleartext HTTP/2 (`-plaintext` in grpcurl, `createInsecure()` in grpc-js, `--http2-prior-knowledge` in buf curl), or over TLS when the mock has `--tls-cert` (grpcurl without `-plaintext`, `createSsl()` in grpc-js; see [TLS](/docs/reference/server/tls)). Imports are looked up in `--proto-path` directories, then next to the file, then among the embedded standard files: the well-known types, `google/api/annotations.proto`, `google/rpc/status.proto`, `code.proto` and `error_details.proto`. ```sh apigenie-server greeter.proto --stubs stubs/ buf curl --protocol grpc --http2-prior-knowledge -d '{"name":"Ann"}' \ http://127.0.0.1:4010/acme.greeter.v1.Greeter/SayHello ``` ```text Listening on http://127.0.0.1:4010 (spec: greeter.proto, 1 service, 3 methods, gRPC over HTTP/2) ``` Unary, server-streaming, client-streaming and bidirectional methods are served. A call is answered by the first of: 1. Its `x-apigenie-mock-*` metadata (below). 2. A script's `onRequest`. 3. The rules of the active scenarios. 4. The stubs. 5. The upstream of `--proxy-to`. 6. Messages generated from the response type, seeded by `--seed`: one, or one to three for a server stream; with `grpc.generation: false`, UNIMPLEMENTED. Fields marked `(google.api.field_behavior) = REQUIRED` are always set (not to their default value; lists and string- or bool-keyed maps get an item), except where that would make a message contain itself; fields marked `INPUT_ONLY` are left out. The response metadata `x-apigenie-mock-source` (`stub:hello-ann`, `generated`, `proxy`, `scenario:outage`) and `x-apigenie-mock-stub` say which one it was. ## Stubs Stub files are YAML or JSON: a list, `{stubs: [...]}`, or a single stub. Their JSON Schema is [`apigenie-mock-grpc-stubs.json`](/schemas/apigenie-mock-grpc-stubs.json); add `# yaml-language-server: $schema=https://apigenie.pl/schemas/apigenie-mock-grpc-stubs.json` to a file for completion in editors. ```yaml stubs: - name: hello-ann method: acme.greeter.v1.Greeter/SayHello priority: 10 request: equals: {name: Ann} response: headers: {x-greeting: formal} message: {message: "Hello Ann", sentAt: "2026-10-04T10:00:00Z", mood: MOOD_HAPPY} trailers: {x-cost: "1"} - name: hello-tenant method: acme.greeter.v1.Greeter/SayHello request: contains: {name: Bob} metadata: equals: {x-tenant: acme} response: message: {message: "Hello Bob of {{metadata.x-tenant}}"} - name: hello-empty method: acme.greeter.v1.Greeter/SayHello request: equals: {} response: status: code: INVALID_ARGUMENT message: name is required details: - "@type": type.googleapis.com/google.rpc.BadRequest fieldViolations: [{field: name, description: must not be empty}] - name: hello-all method: acme.greeter.v1.Greeter/SayHelloToAll response: each: {message: {message: "Hi {{message.name}}"}} ``` - **`method`** is `package.Service/Method` (or `method: Method` with `service: package.Service`). An unknown method stops the start with exit status 2 and the methods there are. - **`request`** matches the request message, written as proto3 JSON: `equals` compares canonical forms, so default values may be left out; `contains` matches a subset, recursively (arrays as subsets, `ignoreArrayOrder` for any order); `matches` holds regular expressions for string fields. `request.metadata` matches the metadata the same three ways. - **`requests`** matches the messages of a client stream, after the client has finished sending: a list matched one by one, or `{every: matcher}`. - **`priority`** (higher first, then the order of the files) and **`times`** (how many calls a stub answers before it's skipped) order the candidates. - **`response`** has `headers`, `message` or `messages` (a list of `{message, delay}` for a stream), `each` (bidirectional streams: one answer per message received), `trailers`, `status` (`code` as a name or a number, `message`, `details` as `google.protobuf.Any` JSON), `delay` (milliseconds), `drop` (`reset`, `close`, `timeout`, `truncate`) and `generate: true` (fill the fields the message doesn't give). - **Templates.** String values can use `{{request.name}}`, `{{requests[1].name}}`, `{{requests.length}}`, `{{message.name}}` (the message `each` answers), `{{metadata.x-tenant}}` and `{{fake:person.firstName}}`. A value that is a template alone keeps the type of what it refers to. ## Metadata directives | Metadata | Effect | | --- | --- | | `x-apigenie-mock-code: NOT_FOUND` | End the call with that status (a name or a number). | | `x-apigenie-mock-message: text` | The status message that goes with it. | | `x-apigenie-mock-stub: hello-ann` | Answer with that stub. | | `x-apigenie-mock-delay: 1500` | Answer after 1.5 seconds. | | `x-apigenie-mock-drop: reset` | Reset the connection (`close`, `timeout` and `truncate` too). | | `x-apigenie-mock-scenario: outage` | Apply that scenario to this call. | | `x-apigenie-mock-dynamic: true` | Generate the answer. | ## What a gRPC server does - `grpc-timeout` sets a deadline: a call that would answer later ends with DEADLINE_EXCEEDED. - Messages larger than `grpc.max_message_bytes` (4 MiB) fail with RESOURCE_EXHAUSTED; compressed ones with UNIMPLEMENTED and `grpc-accept-encoding: identity`; undecodable ones with INVALID_ARGUMENT. An unknown method is UNIMPLEMENTED. - Requests are validated against their message type (`grpc.validation.request`): a violation is INVALID_ARGUMENT with a `google.rpc.BadRequest` in `grpc-status-details-bin`. Fields marked `[(google.api.field_behavior) = REQUIRED]` must be set (see [gRPC contract testing](#contract-testing-of-a-grpc-api)). - Errors are sent as Trailers-Only responses; `grpc-message` is percent-encoded, `-bin` metadata base64-encoded. - `grpc.reflection.v1` and `v1alpha` let grpcurl, buf curl, Postman, Kreya and Bruno list the services and fetch their descriptors; `grpc.health.v1.Health` answers `Check` and `Watch` with SERVING for every service and for `""`. - Scenario rules match `operationId` (`acme.greeter.v1.Greeter/SayHello`), `path`, or the tags `grpc` and the service's name, and set `grpc_status` and `grpc_message` besides delays and drops: ```yaml scenarios: outage: rules: - match: {operationId: acme.greeter.v1.Greeter/SayHello} grpc_status: UNAVAILABLE grpc_message: the greeter is down ``` ## Proxy and record ```sh apigenie-server greeter.proto --proxy-to greeter.internal:50051 --record-dir recorded/ apigenie-server greeter.proto --stubs recorded/ ``` With `--proxy-to`, calls no stub answers go to the upstream server (every call with `grpc.proxy.mode: always`), with their metadata and deadline; an unreachable upstream is UNAVAILABLE. `--record-dir` writes each proxied call as a stub file (`Greeter.SayHello-1.yaml`, ...) that matches its request and gives the upstream's answer. Transport headers are left out, and so is the metadata of `grpc.proxy.redact` (`authorization`, `cookie`, `x-api-key` and `proxy-authorization` by default). ## Contract testing of a gRPC API The proxy checks both sides of every call it forwards against the `.proto` file. Point your clients, tests or a load test at the mock, and the traffic becomes a contract test of the server: ```sh apigenie-server greeter.proto --proxy-to greeter.internal:50051 --report contract.json --report-junit contract.xml --fail-on errors ``` Messages are decoded with their method's types and checked against them: their JSON Schema (the proto3 JSON form), the fields marked `[(google.api.field_behavior) = REQUIRED]` (proto3 has no required fields; a REQUIRED field without explicit presence must not have its default value), and deprecated fields and enum values. The status of the answer is checked against the gRPC protocol and the `google.rpc` conventions. Each violation has a check and a severity that `contract.severity` changes: | Check | Severity | What it means | | --- | --- | --- | | `request.method.unknown` | warn | The call is for a method the file doesn't declare; it is answered UNIMPLEMENTED, not forwarded | | `request.message.malformed` | error | A request message can't be decoded as the input type | | `request.message.incompatible` | error | A request message doesn't match its type, or misses a REQUIRED field. A field that came with another wire type than its declared type's (a string where an `int64` is declared) is dropped by decoding, as protobuf parsers do, and reported with the code `wire-type` | | `request.message.deprecated` | info | A request sets a deprecated field or enum value | | `response.status.invalid` | error | An HTTP status other than 200, a content type other than `application/grpc`, a missing or unknown `grpc-status`, a `grpc-message` that isn't percent-encoded | | `response.status.details-incompatible` | error | `grpc-status-details-bin` isn't a base64 `google.rpc.Status`, or its `code` isn't `grpc-status`; a warning for a detail of a type the file doesn't know | | `response.status.server-error` | info | The upstream answered UNKNOWN, INTERNAL, UNAVAILABLE, DATA_LOSS or UNIMPLEMENTED | | `response.message.malformed` | error | A response message can't be decoded as the output type | | `response.message.incompatible` | error | A response message doesn't match its type, or misses a REQUIRED field. A field that came with another wire type than its declared type's (a string where an `int64` is declared) is dropped by decoding, as protobuf parsers do, and reported with the code `wire-type` | | `response.message.count` | error | A unary or client-streaming call ended OK without exactly one message; a warning for messages before an error status | | `response.message.deprecated` | info | A response sets a deprecated field or enum value | | `response.metadata.invalid` | warn | A `-bin` metadata value isn't base64, or a metadata name isn't lowercase letters, digits, `-`, `_` and `.` | Locations are the message's index and a JSON pointer, `message[0]/items/2/sku`; a message that can't be decoded is located at the field the decoder stopped at. **Report or enforce.** With `--proxy-to`, `grpc.validation.request` and `grpc.validation.response` are `log` unless the configuration sets them: violations are logged and reported, and calls go through as they are, since test suites send invalid calls on purpose. `--strict` (or `enforce`) checks each request message before it goes to the upstream (a violation is INVALID_ARGUMENT with a `google.rpc.BadRequest`) and each upstream message before it goes to the client: a violation ends the call with INTERNAL, `the upstream's answer isn't a valid acme.greeter.v1.HelloReply: ...`. Enforcing holds each message until it is whole, so streams lag by one message. Without `--proxy-to`, requests are enforced as before. **Coverage and reports.** The mock counts the calls of each method of the file (built-in reflection and health aside): `covered` when a call had no error violation, whatever its status, `partial` when every call had one, `not-tested` otherwise. Mocked calls count too, under `sources`. `GET /__apigenie/contract` is the report; when the server stops it prints a summary, writes `--report` and `--report-junit` (a test case per method, named by service and method, one per undocumented method and one for the coverage threshold) and exits with 5 when `--fail-on` or `--min-coverage` (the share of methods) isn't met. The JSON report has `"specification": "grpc"`, `summary` (`calls`, `documented`, `undocumented`, `sources`, `messages`, `violations`, `coverage.methods`, `gate`), `services`, `methods` (each with its `kind`, `status`, `calls`, `statuses` by status name, `messages` and `violations` by check), `undocumented` and `violations` (with the `method` and the `direction`, `in` or `out`). The upstream is `HOST:PORT` for cleartext HTTP/2, or `https://host[:port]` for HTTP/2 over TLS (see [TLS](/docs/reference/server/tls)). Compressed messages (an encoding the client offered and the server chose) are forwarded unchecked. [`apigenie test`](/docs/reference/cli/test) sends `GRPC` requests of `.http` files with the same checks and reports. ## Scripts and the log Scripts see a gRPC call as a `POST` to `/package.Service/Method` whose `operationId` is `package.Service/Method`, with the metadata as headers and the message as a JSON body. In `onResponse`, the status is in the `grpc-status` and `grpc-message` headers and the body is the first message; `onMessage` gets each message of a stream, with `direction` `in` or `out`. The log has a `grpc` event for each call with its status `code`, and `grpc-in` and `grpc-out` events for streamed messages. --- # GraphQL Source: https://apigenie.pl/docs/reference/server/graphql Part of the reference of [apigenie-server](https://apigenie.pl/docs/reference/server.md). Its other pages: [Responses](https://apigenie.pl/docs/reference/server/responses.md), [Scenarios and extensions](https://apigenie.pl/docs/reference/server/scenarios.md), [Scripts](https://apigenie.pl/docs/reference/server/scripts.md), [Document store](https://apigenie.pl/docs/reference/server/store.md), [Several services](https://apigenie.pl/docs/reference/server/services.md), [Validation and security](https://apigenie.pl/docs/reference/server/validation.md), [Contract testing (validating proxy)](https://apigenie.pl/docs/reference/server/contract-testing.md), [Session recording and replay](https://apigenie.pl/docs/reference/server/recording.md), [AsyncAPI](https://apigenie.pl/docs/reference/server/asyncapi.md), [Protobuf / gRPC](https://apigenie.pl/docs/reference/server/grpc.md), [Configuration](https://apigenie.pl/docs/reference/server/configuration.md), [Dashboard and admin API](https://apigenie.pl/docs/reference/server/dashboard.md), [TLS](https://apigenie.pl/docs/reference/server/tls.md). A GraphQL schema is served as a GraphQL endpoint, `/graphql` under `--base-path` (`graphql.path` changes it). Every query, mutation and subscription the schema allows is answered, with no resolvers to write. - **GraphQL over HTTP.** `POST` with `application/json` (`{query, variables, operationName, extensions}`) or `application/graphql`, `GET` with the same as query parameters (queries only: a mutation over `GET` gets 405), and batches (a JSON array of requests, `graphql.max_batch`). Clients that accept `application/graphql-response+json` get 400 for requests that fail before execution; `application/json` clients get 200 for every well-formed request, as the specification asks. - **Validation.** Requests are checked against the schema with the rules of graphql-js and its messages (unknown fields and arguments, wrong values and variable types, fragments that can't apply, fields that can't be merged...). Errors have `locations` and `extensions.code` (`GRAPHQL_PARSE_FAILED`, `GRAPHQL_VALIDATION_FAILED`, `BAD_USER_INPUT`), and the log shows each as a violation. - **Execution.** Fragments, inline fragments, aliases, variables with defaults, `@skip`, `@include` and `__typename` behave as in a real server. Interfaces and unions return one of their object types. A field that fails is null and its error has the field's `path`; a non-null field's null goes up to the nearest nullable one. - **Introspection.** `__schema` and `__type` are complete, so GraphiQL, Apollo Sandbox and code generators work against the mock (`graphql.introspection: false` turns it off). The SDL is at `/graphql/schema.graphql` and `GET /__apigenie/spec`. - **GraphiQL.** A browser opening the endpoint gets GraphiQL, loaded from esm.sh (`graphql.playground: false` turns it off). ## Generated data Values follow the field's type: enum values, list lengths between `graphql.lists.min` and `max` (or a `first`, `last`, `limit`, `count`... argument, the field's own or its connection's), nulls with `graphql.null_probability`, and realistic values for fields named like `email`, `city`, `phone`, `url` or `firstName`, for `name`, `title` and `genre` by the type they belong to (`Author.name` is a person's, `Book.title` a book's), and for custom scalars by their name (`DateTime`, `Date`, `URL`, `UUID`, `JSON`, `Long`, `Decimal`, `EmailAddress`...). `--seed` repeats a run. The schema can say more, with graphql-faker's directives or the mock's own. They need no definitions in the schema and don't show in introspection: ```graphql type User { name: String @fake(type: fullName) email: String @fake(type: email, options: {emailProvider: "example.com"}) joined: String @fake(type: pastDate, options: {dateFormat: "YYYY-MM-DD"}) role: Role @examples(values: ["ADMIN", "EDITOR"]) tags: [String!] @listLength(min: 1, max: 3) score: Int @mock(min: 0, max: 100) code: String @mock(faker: "string.numeric", args: [6]) nickname: String @mock(nullProbability: 0.5) } scalar Money @mock(min: 1, max: 500) ``` - `@fake(type:, options:)` takes the 64 types of graphql-faker and the options most used (`minMoney`, `maxMoney`, `decimalPlaces`, `minNumber`, `maxNumber`, `precisionNumber`, `dateFormat`, `dateFrom`, `dateTo`, `loremSize`, `imageSize`, `imageKeywords`, `passwordLength`, `emailProvider`, `useFullAddress`). Data is English whatever the `locale`. - `@examples(values:)` picks one of the values; `@listLength(min:, max:)` sizes a list. - `@mock` takes `faker` (any faker provider, as `x-faker`) with `args` (a list by position or an object by name), `value` or `values`, `min` and `max` for numbers, `length` or `minLength` and `maxLength` for lists, and `nullProbability`. On a root field, `delay` (milliseconds) delays the response and `errorRate` with `error` makes it fail; on a subscription field, `interval` and `count` pace its events. `graphql.fields` does the same from the configuration, for a field (`Type.field`) or a scalar, over the schema's directives. A schema that defines a directive of the same name keeps it: the mock leaves it alone. ## The store Objects whose type has an `id` field are entities: once made, their fields keep their values for the next requests, so `{ user(id: "7") { name } }` answers the same name every time. The usual root fields work on them, by their names and types: | Field | What it does | | --- | --- | | `user(id: ID!): User`, `node(id: ID!): Node` | The entity with that id; a new one when there is none (`graphql.store.unknown_ids: null` answers null). | | `users: [User!]!` | The users, made up to the list's length once, then the same. | | `usersConnection(first:, after:, last:, before:)` | The users as a Relay connection: `edges { cursor node }`, `nodes`, `pageInfo`, `totalCount`. | | `createUser(input: ...)`, `addUser(...)`, `newUser`, `registerUser`... | A new user with the input's fields; payload types get it in their field and `clientMutationId` back. | | `updateUser(id:, input:)`, `editUser`, `setUser`... | The user, with the input's fields. | | `deleteUser(id:)`, `removeUser`... | Removes the user; returns it, `true`, its id or a payload. | `--dynamic` and `graphql.store.enabled: false` turn the store off; `POST /__apigenie/seed` empties it, and so does a reload. `graphql.store.max_entities` (10000) bounds it. ## Examples An example answers a request with data of its own. Operation examples match an operation's name, its document (layout and comments don't count) and some of its variables; field examples are the value of a field for some arguments, in any operation: ```yaml # schema_examples/users.yaml, next to schema.graphql: an example, or a list of them - name: ada operation: GetUser variables: {id: "1"} response: data: {user: {id: "1", name: Ada Lovelace}} - name: grace # a field example field: Query.user arguments: {id: "2"} data: {name: Grace Hopper} ``` Example data is cut to the request's selection set, and fields it lacks are generated, so one example serves every query of its operation. Examples come from `graphql.examples` in the configuration, from `graphql.examples_files` (files and directories of `.json`, `.yaml` and `.yml`, each an example or a list of them) and from the directory named after the schema (`schema.graphql` takes `schema_examples/`). `Prefer: example=ada` picks one by name; `--dynamic` and `Prefer: dynamic=true` leave them out. An example's `errors` and `extensions` are added to the response, and `status` sets the HTTP status. ## Scenarios and errors Rules of scenarios and `operations` match GraphQL operations by the operation's name (`operationId: GetUser`) or by a root field (`operationId: Query.user`, or `tag: Query.user`). Besides `status`, `headers`, `body` (the whole response), `example`, `dynamic` and the simulation, they take `errors`: ```yaml scenarios: users-down: rules: - match: {operationId: Query.user} errors: - message: The users service is down. path: [user] extensions: {code: UNAVAILABLE} - Partial results # no path: added to the response's errors ``` An error with a path fails that field: it is null (or null up to the nearest nullable field) and the error has its locations. `Prefer: code=`, `example=`, `dynamic=`, `delay=`, `drop=` and `scenario=` apply as for OpenAPI. ## Subscriptions WebSocket clients of the endpoint speak `graphql-transport-ws` (the `graphql-ws` library: Apollo Client, urql, GraphiQL) or the legacy `graphql-ws` of `subscriptions-transport-ws`, by the subprotocol they offer. A subscription gets an event every `graphql.subscriptions.interval` (1000 ms), each a fresh execution of its operation, until `count` events (0: until the client completes it); a field's `@mock(interval:, count:)` wins. Queries and mutations over WebSocket get one result. A request that accepts `text/event-stream` gets the same as server-sent events (`next` events, then `complete`: graphql-sse's distinct connections mode). The log has `ws-open`, `ws-in`, `ws-out` and `ws-close` events; the server's stop closes the clients with 1001 and a reload with 1012. ## Contract testing of a GraphQL API With `--proxy-to`, the GraphQL endpoint goes to a real GraphQL server, and the mock checks every request against the schema and every answer against the schema and the request's selection set. Point your frontend, your tests or a load test at the mock, and the traffic becomes a contract test of the server: ```sh apigenie-server schema.graphql --proxy-to http://localhost:4000/graphql --report contract.json --fail-on errors ``` ```text Listening on http://127.0.0.1:4010/graphql (spec: schema.graphql, 12 operations) Proxy: http://localhost:4000/graphql (requests: log, responses: log, unknown routes: forward, mode: always) ``` The URL's path is the server's endpoint (`HOST:PORT` alone keeps the mock's, `/graphql`). The upstream gets the request as it came (a batch stays a batch), without the mock's `__` query parameters and `X-Apigenie-Mock-*` headers, with `Via` and `X-Forwarded-*`, and `Accept-Encoding: identity`. GraphiQL, `/graphql/schema.graphql`, the admin API and `OPTIONS` stay local. Requests for other paths are forwarded unchecked (`request.path.unknown`), or answered 404 with `--proxy-unknown reject`. A proxy makes up no subscription events: WebSocket and server-sent events subscriptions aren't served. **What is checked.** Requests as the mock checks them (graphql-js's rules and messages), and each answer as graphql-js would have produced it, field by field: | Check | Severity | When | | --- | --- | --- | | `request.body.malformed` | error | Not a GraphQL request: not JSON, no query, an unsupported content type. | | `request.query.malformed`, `request.operation.unknown` | error | The query can't be parsed; `operationName` names no operation, or is missing. | | `request.query.invalid`, `request.variables.incompatible` | error | The operation isn't valid against the schema; a variable doesn't match its type. | | `request.method.incompatible` | error | A mutation over `GET`. | | `request.field.deprecated` | info | A deprecated field, argument, input field or enum value is used. | | `request.path.unknown` | warn | A request for another path than the endpoint (forwarded unchecked). | | `response.status.incompatible` | error | A 1xx or 3xx status, or a 4xx with `data`: an executed operation that says it failed. | | `response.status.server-error` | info | The server answered with 5xx. | | `response.content-type.incompatible` | error | Neither `application/json` nor `application/graphql-response+json`. | | `response.body.malformed` | error | Not JSON, or a batch not answered with a list of as many results. | | `response.shape.incompatible` | error | Not a map of `data`, `errors` and `extensions`: other keys, neither `data` nor `errors`, `data: null` without `errors`, empty `errors`. | | `response.errors.incompatible` | error | An error without a string `message`, with `locations` that aren't `{line, column}`, a `path` of other than names and indexes, `extensions` that aren't an object. | | `response.errors.unexpected`, `response.errors.path-unknown` | warn | An error's entries outside `extensions`; a `path` that names no field the operation selects. | | `response.data.incompatible` | error | A selected field (or alias) missing; `null` in a non-null position that no error's `path` explains; a list, an object or a scalar where the type says otherwise; `Int` beyond 32 bits, a non-finite `Float`, a `String`, `Boolean` or `ID` of another kind, an unknown enum value; a `__typename` that isn't a possible type. | | `response.data.unexpected` | warn | A key the operation didn't select. | | `response.data.typename-missing` | info | An object of an interface or union came without `__typename`: only the selections outside type conditions are checked. | | `response.data.unvalidatable` | info | Nesting deeper than 64, or more than 100 violations in one answer. | | `response.field-error` | warn | The server ran the operation, but fields failed: `errors` next to `data` (`null` or partial), one per error, e.g. `the field book failed: not implemented`. Valid GraphQL, but a contract test shouldn't pass it silently; `--fail-on warnings` (or `contract.severity`) fails on it. | | `response.request-error` | warn | The server didn't execute the operation (authentication, persisted queries...). | | `response.schema-drift` | error | The server rejected an operation the schema allows (`GRAPHQL_VALIDATION_FAILED`, "Cannot query field..."): its schema differs. | | `schema.drift`, `schema.addition` | error, info | The server's schema (introspected) lacks or changed something of the schema; has more. | | `schema.unchecked` | info | The server's schema can't be introspected. | Fragments, inline fragments, `@skip` and `@include` (with the request's variables), aliases and merged fields are followed as the server must; custom scalars take any JSON value. `contract.severity` changes a check's severity or turns it off, as for OpenAPI. **The server's schema.** With the first request it forwards, the proxy also sends the server the usual introspection query (with that request's `Authorization`, `Cookie` and `X-Api-Key`), turns the answer into a schema and compares it with the served one, as `apigenie diff` does: what the server lacks or changed incompatibly is `schema.drift` (located by `Type.field`), what it adds `schema.addition`. The log has a `server` event with the result (`schema of http://localhost:4000/graphql: 1 breaking difference, 2 additions`), and the report a `schema` section. A server that isn't up yet is asked again with the next request; `POST /__apigenie/contract/schema-check` asks now. `proxy.schema_check: false` turns it off. **Report or enforce.** As for OpenAPI, the proxy reports by default: answers carry `X-Apigenie-Mock-Violations` and `X-Apigenie-Mock-Violations-Detail` (locations such as `["response", "body", "/data/book/title"]`, `/2/data/...` for the third result of a batch). With `--strict`, a request with errors isn't forwarded: it gets the GraphQL errors the mock answers with (`GRAPHQL_VALIDATION_FAILED`...). An answer with errors is replaced by the `invalid-upstream-response` 502 problem. Warnings and notes never block. **Fallback mode.** `--proxy-mode fallback` (`proxy.mode`) lets scenario rules, examples and the scripts' `onGraphQL` answer first, as for a mock; what nothing answers goes to the server. A batch goes to the server whole as soon as one of its operations does. **Recording.** `--record-dir DIR` writes the answer to each valid operation as an example file (`GetBook-1.yaml`: `name`, `operation`, `query`, `variables`, `response`, and `status` when not 200), which the mock serves as it is: point `graphql.examples_files` at the directory, or name it after the schema (`schema_examples/`). Bodies are recorded as they are. **Coverage and reports.** The mock counts the schema's fields that requests selected (every field of its object and interface types, as GraphQL Inspector's coverage does) and its root fields (`Query.book`): `covered`, `partial` (some fields under it never selected) or `not-tested`. Mocked traffic counts too. `GET /__apigenie/contract` is the report; when the server stops it prints a summary, writes `--report` and `--report-junit` (a test case per root field, one for the server's schema, one for the coverage threshold) and exits with 5 when `--fail-on` or `--min-coverage` (the share of fields) isn't met. The JSON report has `summary`, `schema`, `rootFields`, `fields`, `uncoveredFields`, `operations` (by name), `otherRoutes` and `violations`. --- # Configuration Source: https://apigenie.pl/docs/reference/server/configuration Part of the reference of [apigenie-server](https://apigenie.pl/docs/reference/server.md). Its other pages: [Responses](https://apigenie.pl/docs/reference/server/responses.md), [Scenarios and extensions](https://apigenie.pl/docs/reference/server/scenarios.md), [Scripts](https://apigenie.pl/docs/reference/server/scripts.md), [Document store](https://apigenie.pl/docs/reference/server/store.md), [Several services](https://apigenie.pl/docs/reference/server/services.md), [Validation and security](https://apigenie.pl/docs/reference/server/validation.md), [Contract testing (validating proxy)](https://apigenie.pl/docs/reference/server/contract-testing.md), [Session recording and replay](https://apigenie.pl/docs/reference/server/recording.md), [AsyncAPI](https://apigenie.pl/docs/reference/server/asyncapi.md), [Protobuf / gRPC](https://apigenie.pl/docs/reference/server/grpc.md), [GraphQL](https://apigenie.pl/docs/reference/server/graphql.md), [Dashboard and admin API](https://apigenie.pl/docs/reference/server/dashboard.md), [TLS](https://apigenie.pl/docs/reference/server/tls.md). `apigenie-server` reads `--config`, else `apigenie-server.yaml` (`.yml`, `.json`), then `apigenie-mock.yaml` (`.yml`, `.json`; the name before the rename, still read) or `.apigenie.yaml` in the current directory, else the shared `apigenie.yaml` of the project (in the current directory or a parent, up to the root of the repository; see [configuration](/docs/reference/cli/configuration#where-the-file-is-found)). In a file of its own the settings are at the top level; in a shared configuration they are under `commands.mock`. The command line wins over the environment variables, which win over the file; [`apigenie config --for mock --origin`](/docs/reference/cli/config) shows which one set each value. The JSON Schema of a file of its own is `https://apigenie.pl/schemas/apigenie-server-config/latest.json`. ```yaml version: "1.0" specs: openapi.yaml server: {host: 127.0.0.1, port: 4010, base_path: /api, trailing_slash: ignore, watch: true} # strict_base_path: serve the paths only under the prefix (true with base_path) cors: {enabled: true, origins: ["*"], allow_credentials: true, expose_headers: ["*"], max_age: 600} responses: {mode: static} headers: {diagnostics: true} generation: seed: 42 max_depth: 8 null_probability: 0 smart_names: false limits: {min_items: 1, max_items: 5, min_length: 1, max_length: 32, min_properties: 0, max_properties: 10, minimum: 0, maximum: 1000} validation: {request: enforce, response: log, formats: true, unknown_query_parameters: allow} security: mode: check # off, check (presence) or enforce (the credentials below) credentials: {api_keys: {apiKey: [secret]}, bearer_tokens: [token], basic: [{user: u, password: p}]} request_overrides: {header: true, query_params: true} simulation: {latency: 100-300, jitter: 20, drop: {probability: 0.01, mode: reset}} operations: getPet: {status: 404} GET /pets: {latency: 1000} stubs: [recorded] # OpenAPI: recorded exchanges to answer with (--stubs) scenarios: outage: description: the backend is down rules: - match: {tag: pets} status: 503 headers: {Retry-After: "30"} body: {title: Service unavailable} overrides: [] scripts: [mock.mjs] # relative to the configuration file scripting: {timeout_ms: 1000, memory_limit_mb: 64, fail_mode: log} asyncapi: server: null # the one server to serve publish: {enabled: true, interval: 1000, count: 0, jitter: 0} validate_incoming: enforce # off, log or enforce mqtt_port: 1883 # 8883 when tls.cert serves MQTT over TLS grpc: proto_path: [protos] # relative to the configuration file stubs: [stubs] max_message_bytes: 4194304 reflection: true health: true validation: {request: enforce, response: log} # off, log or enforce; both log with --proxy-to unless set here generation: true # false: UNIMPLEMENTED when nothing answers proxy: {target: null, mode: fallback, record_dir: null, redact: [authorization, cookie, x-api-key, proxy-authorization]} # target: HOST:PORT (h2c) or https://host[:port] (TLS) history_size: 1000 graphql: path: /graphql # under server.base_path introspection: true playground: true # GraphiQL schema_endpoint: true # /graphql/schema.graphql allow_get_mutations: false lists: {min: 1, max: 3} null_probability: 0 max_depth: 0 # deeper operations are rejected; 0 for no limit max_batch: 10 fields: User.email: {faker: internet.email} Book.pages: {min: 50, max: 900} Status: {values: [OPEN, CLOSED]} examples: [] # as the files of examples_files examples_files: [more_examples] discover_examples: true # schema_examples/ next to schema.graphql store: {enabled: true, max_entities: 10000, unknown_ids: generate} subscriptions: {enabled: true, interval: 1000, count: 0, jitter: 0, legacy_protocol: true, init_timeout: 3000} proxy: # OpenAPI, GraphQL: contract testing against a real server (gRPC: grpc.proxy) target: http://localhost:8080 # or https://, HOST:PORT, ws:// or wss:// (AsyncAPI); OpenAPI, AsyncAPI: a path is put before the requests' paths, # AsyncAPI: a list may add an mqtt:// or mqtts:// broker: [ws://localhost:9000, mqtt://localhost:1884] # GraphQL: the path is the server's endpoint unknown_routes: forward # or reject (404, 405) mode: always # or fallback: OpenAPI: the mock answers when the server can't be # reached, times out or answers 404/501 for an operation; # GraphQL: examples, scenarios, scripts answer first schema_check: true # GraphQL: introspect the server and compare the schemas record_dir: null # OpenAPI: write the exchanges as stub files there; # GraphQL: write the answers as examples there record_har: null # OpenAPI: write the session as a HAR file redact: [authorization, cookie, set-cookie, proxy-authorization, x-api-key] timeout_ms: 30000 connect_timeout_ms: 5000 max_in_flight: 64 max_response_bytes: 16777216 contract: report: contract.json # relative to the configuration file report_junit: contract.xml fail_on: none # none, errors or warnings: exit status 5 min_coverage: 0 # percent of operations, request bodies and responses (GraphQL: fields; AsyncAPI: messages; gRPC: methods) severity: {response.header.undefined: warn, response.status.default: ignore} # GraphQL's, AsyncAPI's and gRPC's checks too record: # see Session recording; the directory relative to the configuration file dir: null # record the session there from the start (--record); new or empty name: null # the session's name; the directory's when not given redact: [] # hidden besides proxy.redact: header names, and JSON pointers (/password) to values of bodies and messages replay: # see Session replay; the directory relative to the configuration file dir: null # answer from the session recorded there (--replay) missing: fail # fail (502 problem), generate (the mock answers) or passthrough (proxy.target answers) ignore: [] # not compared besides dates, readOnly fields and volatile headers: header names, JSON pointers (/id, /items/*/id) update: false # with missing: passthrough, record the run and replace the session with it at stop admin: {enabled: true, path: /__apigenie, port: null, allow_remote: false, log_size: 1000} log: {level: info, format: stylish, bodies: false, body_limit: 4096, headers: false, file: null} tls: # see TLS; paths relative to the configuration file cert: null # serve HTTPS with this certificate chain and key (both or neither) key: null client_ca: null # require client certificates of these authorities (mTLS); needs cert ca_certs: [] # trusted for https://, wss:// and mqtts:// upstreams, besides the system's roots insecure: false # don't verify upstream certificates client_cert: null # presented to upstreams that ask for a client certificate (with client_key) client_key: null db: # see Document store; paths relative to the configuration file crud: explicit # auto: serve /things and /things/{id} from the store (--crud); explicit: only x-apigenie-mock resources; off seed: {notes: seed/notes.json} # or a directory of <collection>.json/.yaml files: seed, seed/*.json generate: 3 # documents generated for a resource's collection nothing else seeds max_documents: 10000 # per collection and namespace; 0 for no limit file: null # keep the store across runs (--db-file) ``` A mistake in the file stops the server with exit status 2, the position and the JSON pointer of the value; an unknown setting is reported with the closest known name. --- # Dashboard and admin API Source: https://apigenie.pl/docs/reference/server/dashboard Part of the reference of [apigenie-server](https://apigenie.pl/docs/reference/server.md). Its other pages: [Responses](https://apigenie.pl/docs/reference/server/responses.md), [Scenarios and extensions](https://apigenie.pl/docs/reference/server/scenarios.md), [Scripts](https://apigenie.pl/docs/reference/server/scripts.md), [Document store](https://apigenie.pl/docs/reference/server/store.md), [Several services](https://apigenie.pl/docs/reference/server/services.md), [Validation and security](https://apigenie.pl/docs/reference/server/validation.md), [Contract testing (validating proxy)](https://apigenie.pl/docs/reference/server/contract-testing.md), [Session recording and replay](https://apigenie.pl/docs/reference/server/recording.md), [AsyncAPI](https://apigenie.pl/docs/reference/server/asyncapi.md), [Protobuf / gRPC](https://apigenie.pl/docs/reference/server/grpc.md), [GraphQL](https://apigenie.pl/docs/reference/server/graphql.md), [Configuration](https://apigenie.pl/docs/reference/server/configuration.md), [TLS](https://apigenie.pl/docs/reference/server/tls.md). The dashboard shows the server's log and state in a browser; the admin API behind it is what tests and scripts use to switch scenarios, add stubs and read the log. ## Dashboard `http://127.0.0.1:4010/__apigenie/ui` is a page served by the server itself, for a browser on the same machine: it follows the [admin API](#admin-api)'s rules (local clients only unless `admin.allow_remote`, on `admin.port` when the admin API has a port of its own, off with `--admin off`). The header on every screen names the documents and how they answer (mock, proxy, generated), where they listen, the seed, the uptime, the requests and violations so far, and has Reload and Stop; with [several services](/docs/reference/server/services) a switcher narrows every screen to one. | Screen | What it shows and does | | --- | --- | | Traffic | Every exchange as it happens (the [event stream](#the-event-stream)), with filters; an exchange's request and answer (headers and bodies, captured while the page is open) and its validation problems with where they point in the document. Copy as curl, Replay, Save as stub (`POST /stubs`), Add to `.http` (a file built up in the browser, to copy or download), Copy as YAML (the answer as an `operations` entry of the configuration). Record session and Save session: a [session recording](/docs/reference/server/recording#session-recording) of what happens from here, written where the server runs. | | Operations | The operations by tag, with their hits, their last status and what answered them last (an example, a generated body, a scenario, a proxy). For one operation: a fixed answer (a declared status, one of its examples, a generated body, a dropped connection), a latency and whether its requests are validated, saved as an always-on [override](/docs/reference/server/scenarios) (`PUT /overrides`) until the server stops, with the `Prefer` header (and `__` parameters) that do the same for one request. | | Scenarios and network | The scenarios of the configuration, the document and the admin API, switched on and off, with their rules and hits; a builder for a new one (by operation, tag, method and path, header or query parameter; status, example, latency, probability); the network simulation of every response (fixed, uniform, normal or log-normal latency, jitter, dropped connections, bandwidth, the seed) with the response times of the last requests. | | Contract | Whether the server would pass `--fail-on` and `--min-coverage` if it stopped now, the coverage, the violations by check (and the exchanges they were seen in), the operations never called, the report as JSON or JUnit to download, and Start over (`DELETE /contract`). | | Data | The [document store](/docs/reference/server/store)'s collections with their documents, Reset to seed, snapshots to save and restore; and `ctx.state`, the values the scripts keep, to edit or reset. | | Channels | For an [AsyncAPI](/docs/reference/server/asyncapi) document only (the screen is listed when a served document has channels): the channels by WebSocket, MQTT and HTTP, with their operations, the clients connected and the messages counted (`GET /asyncapi/channels`); for a channel, its messages in and out as the event stream brings them (with an exchange's payload and validation problems, and Open in Traffic), its clients (`GET /asyncapi/clients`, followed through the `ws-open`, `ws-close`, `mqtt-subscribe` and `mqtt-unsubscribe` events), and Publish: a message sent as the application would (`POST /asyncapi/publish`), to every client of the channel or to one, with a payload started from the document's examples or left to the server; a payload the message's schema refuses shows the violations and goes nowhere, until Send anyway; Copy as curl. | Every panel copies its settings as the configuration's YAML, or as `x-apigenie-mock` for the document, so what was tried in the dashboard is kept in a file (Channels changes no setting: it copies the publish as curl). The page follows the system's light or dark theme, or the one chosen in the header. The page is built from the web components package (`src/app_web`, the `apg-server-*` elements) and embedded in the binary; nothing is fetched from the network. The design is ADR-167. ![The Traffic screen of the dashboard](/server-dashboard-light.png) ## Admin API On by default for local clients only (`admin.allow_remote` opens it, `admin.port` moves it to a port of its own). The `/db` endpoints work on the namespace of an `X-Apigenie-Test` header (or a `?test=` parameter), the default one without it: | Endpoint | Description | | --- | --- | | `GET /__apigenie` | Status: version, `url` (where clients reach the server), document (with its proxies and stubs; an AsyncAPI document's `mqttProxy` and `mqttClients`), seed, uptime (`uptimeSeconds`, `startedAt`), requests (the clients', not the admin API's), active scenarios, simulation, `logSize`. | | `GET /__apigenie/ui/` | The [dashboard](#dashboard): the page and its files (`GET /__apigenie/ui` redirects to it). | | `GET /__apigenie/routes` | The operations served, with their `hits`, `lastStatus`, `lastSource` (what answered last) and `lastAt`; an OpenAPI operation's `tags`, `deprecated` and `responses` (each status with its content types and the names of its examples). | | `DELETE /__apigenie/hits` | Start the hits of routes and scenarios over (a reload keeps them). | | `GET /__apigenie/services` | The services: name, mount, URL, document (see [several services](/docs/reference/server/services)). | | `GET /__apigenie/scenarios`, `PUT` / `DELETE /__apigenie/scenarios/{name}` | List (with `hits`, `lastStatus`, `lastSource` and `lastAt`, and the rules as `ruleList` next to their count `rules`), add or remove scenarios. | | `POST /__apigenie/scenarios/{name}/activate`, `/deactivate` | Switch a scenario on or off. | | `GET`, `PUT /__apigenie/overrides` | The always-on rules, whole: what `GET` answers, `PUT` takes back. | | `GET`, `PUT /__apigenie/simulation` | The network simulation of every response. | | `POST /__apigenie/seed` | Reseed: `{"seed": 42}`. | | `GET`, `DELETE /__apigenie/log?limit=&after=&level=` | The recent events, with headers and bodies when they were captured (see [log entries](#log-entries)). | | `GET /__apigenie/events?type=&level=&service=&after=` | The events as they happen, as Server-Sent Events (see [the event stream](#the-event-stream)). | | `POST /__apigenie/stubs` | A stub file of a logged exchange: `{"id": 42, "dir": "stubs", "name": "rex"}` (see [stubs from the log](#stubs-from-the-log)). | | `GET /__apigenie/record` | The [session recording](/docs/reference/server/recording#session-recording): `recording`, and the session's `dir`, `name`, `started`, `exchanges` while one is on; `test`, the mark. | | `POST /__apigenie/record/start`, `/stop` | Record a session in `{"dir": "sessions/run-7", "name": "run 7"}` (`dir` defaults to `record.dir`), or stop it and write `session.yaml`. | | `POST /__apigenie/record/mark` | `{"test": "checkout-happy"}`: the test of the exchanges to come that carry no `X-Apigenie-Test` of their own; `{}` clears it. | | `GET /__apigenie/replay` | The [session replay](/docs/reference/server/recording#session-replay)'s report so far: `exchanges`, `replayed`, `neverReplayed`, `unmatched` (with their tests and closest recordings), `passed`, and `tests`, the exchanges each test used since its reset. | | `POST /__apigenie/replay/reset` | Restart a test's counters: `{"test": "checkout"}`, or the `X-Apigenie-Test` header, or `?test=`; without one, every test's. 204. | | `POST /__apigenie/reload`, `POST /__apigenie/shutdown` | Reload, or stop gracefully. | | `GET /__apigenie/spec` | The served document, bundled (converted to OpenAPI 3.2 for a Swagger 2.0 document; a `.proto` file with its imports, or a GraphQL schema, as text). | | `GET`, `PUT`, `DELETE /__apigenie/state/{key}` | Values kept between requests. | | `GET /__apigenie/db` | The [document store](/docs/reference/server/store): its file, namespaces, snapshots and collections (documents, seeds, id, and the schema and operations of a resource's collection). | | `GET /__apigenie/db/{name}?limit=&offset=` | A collection's documents (100 by default) and `total`. | | `PUT`, `DELETE /__apigenie/db/{name}` | Replace every document of a collection (a JSON array; all or nothing: 422 when the schema refuses one, 409 for an id used twice), or remove them. | | `POST /__apigenie/db/reset` | Back to the seeds: with `X-Apigenie-Test`, that namespace; without it, the default one, and the tests' namespaces go. `{"collections": ["notes"]}` resets some. | | `GET /__apigenie/db/snapshots`, `PUT`, `DELETE /__apigenie/db/snapshots/{name}` | List, take (or replace) or remove a snapshot of the documents. | | `POST /__apigenie/db/snapshots/{name}/restore` | Put a snapshot's documents back. | | `POST /__apigenie/db/save` | Write the store to `--db-file` now (501 without one). | | `DELETE /__apigenie/db/namespaces/{test}` | Forget a test's namespace. | | `GET`, `DELETE /__apigenie/contract` | The contract report (coverage and violations), or start it over. | | `GET /__apigenie/contract.json`, `GET /__apigenie/contract.xml` | The contract report as `--report` (JSON) and `--report-junit` (JUnit XML) would write it now, to save. | | `GET /__apigenie/contract/violations?operation=&check=&limit=` | The violations seen, by operation (id or `GET /pets/{id}`; GraphQL: the operation's name or a root field such as `Query.book`; AsyncAPI: the operation's key; gRPC: `package.Service/Method` or its path) and check. | | `POST /__apigenie/contract/schema-check` | GraphQL proxy: introspect the server and compare its schema now (202; the result is logged and reported). | | `GET /__apigenie/asyncapi/channels` | AsyncAPI: the channels, their operations and messages (with the document's examples), the clients connected, and the messages counted (see [AsyncAPI channels](#asyncapi-channels-from-the-admin-api)). | | `GET /__apigenie/asyncapi/clients` | AsyncAPI: the WebSocket clients and MQTT subscriptions of the channels. | | `POST /__apigenie/asyncapi/publish` | AsyncAPI: send a message to a channel's clients, or to one of them: `{"channel": "rooms/42", "payload": {"text": "hi"}}`, `{"channel": "room", "client": 7, ...}`. | | `GET /__apigenie/grpc/services` | gRPC: the services and their methods. | | `GET`, `POST`, `DELETE /__apigenie/grpc/stubs` | gRPC: list, add (one stub or a list) or remove the stubs added at run time (`?scope=all`: every stub). | | `GET`, `PUT`, `DELETE /__apigenie/grpc/stubs/{name}` | gRPC: one stub. | | `POST /__apigenie/grpc/stubs/reset`, `GET /__apigenie/grpc/stubs/schema` | gRPC: back to the stub files, and the stubs' JSON Schema. | | `GET`, `DELETE /__apigenie/grpc/history?method=&limit=&after=&q=` | gRPC: the calls received, newest last. | | `POST /__apigenie/grpc/verify` | gRPC: count the calls that match `{method, request, metadata, stub, code}`. | A server of [several services](/docs/reference/server/services) names the service of each item, and takes `?service=NAME` on every endpoint. ### The event stream `GET /__apigenie/events` keeps the connection open and writes each event of the log as it happens, as [Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html): `id:` is the log entry's id, `event:` its kind, and `data:` the same JSON object as a `/log` entry. A dashboard reads it with `EventSource`; a script with `curl -N`: ```bash curl -N 'http://127.0.0.1:4010/__apigenie/events?type=request,violation' ``` ```text : connected id: 12 event: request data: {"event":"request","id":12,"time":"2026-10-12T09:00:00.000Z","level":"info","method":"POST","path":"/pets","operationId":"addPet","status":201,...} id: 13 event: request data: {"event":"request","id":13,...,"status":422,"violations":[...]} id: 13 event: violation data: {"event":"request","id":13,...,"status":422,"violations":[...]} ``` | Event | When | | --- | --- | | `request` | An exchange, request and answer together (there is no separate response event). | | `violation` | After an event with violations: the same id and data. | | `ws-open`, `ws-in`, `ws-out`, `ws-close`, `mqtt-*`, `grpc`, `grpc-in`, `grpc-out` | WebSocket, MQTT and gRPC traffic, as in the log. | | `scenario` | A scenario was added, replaced, removed, activated or deactivated through the admin API (`message` says which). | | `reload` | The documents were reloaded (`POST /reload` or `--watch`). | | `contract-updated` | The contract report's coverage changed (at most once a second), or it started over (`message: "reset"`, after `DELETE /contract` or a reload). | | `db` | A write to the [document store](/docs/reference/server/store): the collection, what changed, who wrote. | | `admin`, `script`, `server` | The admin API's own exchanges, the scripts' logs, the server's errors. | `?type=` keeps the named events, `?level=` those at a level and above (default `debug`), `?service=` one service's. `?after=ID`, or the `Last-Event-ID` header a reconnecting `EventSource` sends, first replays the log's later entries, so a client that reconnects misses nothing the log still holds. A comment every 15 seconds keeps the connection alive. A client that falls more than 1 MiB behind is disconnected. The stream follows the admin API's rules: local clients only unless `admin.allow_remote`, on `admin.port` when the admin API has a port of its own. ### Log entries While at least one event stream is open, the server captures the headers and bodies of every exchange, as `log.headers: true` and `log.bodies: true` do. `/log` entries and stream events then carry `headers` and `responseHeaders` (arrays of `[name, value]`), `requestBody` and `responseBody`, and `captured: {"headers": true, "bodies": true}`. A body that isn't UTF-8 is in Base64 with `requestBodyEncoding` (or `responseBodyEncoding`) `"base64"`. A body is kept up to `log.body_limit` bytes (4096 by default); a longer one is cut and marked `requestBodyTruncated` or `responseBodyTruncated`, and `requestSize` and `responseSize` keep the whole sizes. ### Stubs from the log `POST /__apigenie/stubs` makes a [stub file](/docs/reference/server/contract-testing) of a logged exchange of an OpenAPI document, as `--record-dir` writes them: the client's headers without the connection's, the hidden headers of `proxy.redact` as `[redacted]`, and the query without the mock's own `__` parameters. ```bash curl -X POST http://127.0.0.1:4010/__apigenie/stubs -d '{"id": 12, "dir": "stubs", "name": "new-pet"}' ``` With `dir`, or else the service's `proxy.record_dir`, the stub is written to a new file there, `<operationId>-N.yaml`, and the answer (201) has the `file` and the `stub`. Without either the answer (200) is the file's content, `{"stubs": [...]}`. The entry must still be in the log, and must have been captured whole (an open event stream, or `log.headers` and `log.bodies`, and a `log.body_limit` above its bodies' sizes): else 404 or 409. The running mock answers with the new stub after `POST /__apigenie/reload` when `dir` is one of its `stubs` directories. ### AsyncAPI channels from the admin API `GET /__apigenie/asyncapi/channels` lists the channels: `key`, `address`, `protocols`, `paths`, `messages` (their names) and `messageList` (each message's `name`, `contentType`, `summary` and `examples`, the document's, each with its `payload` and `headers`: a starting point for a payload to publish), `operations` (with `qos` and `retain` for MQTT), the `clients` connected now and the contract report's `connections`, `messagesIn`, `messagesOut` and `unmatched` counts. `GET /__apigenie/asyncapi/clients` lists the WebSocket clients and MQTT subscriptions: `id`, `protocol`, `remote`, `channel`, `address`, `route`, `path` (the WebSocket path, or the MQTT filter), `clientId` (MQTT), `connectedAt` and `messagesOut`. `POST /__apigenie/asyncapi/publish` sends a message to the clients of a channel, as the schedule sends one: scripts see it, and each delivery is logged as `ws-out` or `mqtt-out` with `source: "admin"`. ```bash curl -X POST http://127.0.0.1:4010/__apigenie/asyncapi/publish \ -d '{"channel": "rooms/42", "message": "notice", "payload": {"text": "maintenance at noon"}}' ``` ```json {"channel": "room", "address": "rooms/42", "operation": "sendNotices", "message": "notice", "source": "admin", "contentType": "application/json", "payload": "{\"text\":\"maintenance at noon\"}", "delivered": 1, "webSocket": 1, "mqtt": 0, "clients": [7]} ``` With a [Kafka tap](/docs/reference/server/asyncapi#contract-testing-of-kafka-channels), a Kafka channel's message is produced to the cluster instead. The record's `key`, `headers` (an object of strings) and `partition` may be given; without them the key and headers are made from the message's Kafka binding and headers, and the partition is the key's. The record is checked as the tap checks records (422 with the `violations`, nothing produced, unless `"validate": false`), produced, and answered with where it went; a cluster that can't be reached or refuses it answers 502. The tap then reads it like any other record. ```bash curl -X POST http://127.0.0.1:4010/__apigenie/asyncapi/publish \ -d '{"channel": "orders", "payload": {"sku": "A-1"}, "key": "cust-1", "headers": {"correlationId": "c-1"}}' ``` ```json {"channel": "orders", "operation": "placeOrder", "message": "order", "source": "admin", "contentType": "application/json", "payload": "{\"sku\":\"A-1\"}", "kafka": {"upstream": "kafka://localhost:9092", "topic": "shop.orders", "partition": 1, "offset": 42, "key": "cust-1", "headers": {"correlationId": "c-1"}}} ``` With an [AMQP tap](/docs/reference/server/asyncapi#contract-testing-of-amqp-channels), an AMQP channel's message is published to the broker: a queue channel's through the default exchange, any other to its exchange with `routingKey` (else the address given, else the address with its parameters filled). Its `properties` (`contentType`, `contentEncoding`, `deliveryMode`, `priority`, `correlationId`, `replyTo`, `expiration`, `messageId`, `timestamp`, `type`, `userId`, `appId`) and `headers` may be given; without them they come from the message's and the operation's AMQP bindings and the message's headers. The message is checked (422), published mandatory with publisher confirms, and answered with `{"amqp": {"upstream", "exchange", "routingKey", "headers"}}`; a message no queue takes answers 409 `asyncapi-unroutable`. `channel` is a channel's key (every client of the channel gets the message) or an address with its parameters (that address's clients only); `client`, an `id` of `/asyncapi/clients`, narrows it to that one client. `message` names one of the channel's messages; without it, the first message of its first `send` operation is sent. `payload` is the message as JSON, `raw` as text, and without either one is made as for the schedule. A payload that doesn't match the message's schema answers 422 with the `violations` and is sent to nobody, unless `"validate": false`. Unknown channels and messages answer 404, as does a `client` that isn't connected to the channel (`asyncapi-unknown-client`). An admin publish isn't retained by the MQTT broker. Only clients the mock matched to a channel get it. Clients of a validating proxy are counted in the status, not listed. A server of several services lists every AsyncAPI service's channels and clients, and needs `?service=` to publish when several services serve AsyncAPI. --- # TLS Source: https://apigenie.pl/docs/reference/server/tls Part of the reference of [apigenie-server](https://apigenie.pl/docs/reference/server.md). Its other pages: [Responses](https://apigenie.pl/docs/reference/server/responses.md), [Scenarios and extensions](https://apigenie.pl/docs/reference/server/scenarios.md), [Scripts](https://apigenie.pl/docs/reference/server/scripts.md), [Document store](https://apigenie.pl/docs/reference/server/store.md), [Several services](https://apigenie.pl/docs/reference/server/services.md), [Validation and security](https://apigenie.pl/docs/reference/server/validation.md), [Contract testing (validating proxy)](https://apigenie.pl/docs/reference/server/contract-testing.md), [Session recording and replay](https://apigenie.pl/docs/reference/server/recording.md), [AsyncAPI](https://apigenie.pl/docs/reference/server/asyncapi.md), [Protobuf / gRPC](https://apigenie.pl/docs/reference/server/grpc.md), [GraphQL](https://apigenie.pl/docs/reference/server/graphql.md), [Configuration](https://apigenie.pl/docs/reference/server/configuration.md), [Dashboard and admin API](https://apigenie.pl/docs/reference/server/dashboard.md). `apigenie-server` serves TLS itself, and its proxies reach `https://` and `wss://` servers and `mqtts://` brokers. TLS 1.2 and 1.3 come from Mbed TLS. It's built with what modern servers use: AES-GCM and ChaCha20-Poly1305, ECDHE key exchange on x25519, P-256, P-384 and P-521, and RSA and ECDSA certificates. A server that offers only static RSA or DHE key exchange, or other ciphers, can't be reached. **Serving.** `--tls-cert server.pem --tls-key server.key` (or `tls.cert` and `tls.key` in the configuration) turns the port into HTTPS. WebSocket channels and GraphQL subscriptions become WSS, and clients that ask for `h2` by ALPN get HTTP/2, which is how browsers and gRPC clients over TLS connect. The admin API on a port of its own (`admin.port`) uses the same certificate. The MQTT broker of an AsyncAPI document serves MQTT over TLS too, on port 8883 unless `--mqtt-port` says otherwise. The startup line shows `https://` and `mqtts://` URLs and, as JSON, `"tls": true`. The certificate file may hold the chain, the server's certificate first. The key must be PEM and not encrypted. For local development, `mkcert localhost 127.0.0.1` makes a pair your system trusts: ```sh apigenie-server openapi.yaml --tls-cert localhost+1.pem --tls-key localhost+1-key.pem curl https://localhost:4010/pets ``` **Upstreams.** `--proxy-to https://api.example.com` (OpenAPI, GraphQL, AsyncAPI HTTP channels), `wss://...` (AsyncAPI WebSocket channels), `mqtts://...` (AsyncAPI MQTT channels, port 8883 unless given) and `https://host[:port]` (gRPC, HTTP/2 over TLS) connect over TLS, port 443 unless given. Certificates are verified against the system's roots: - macOS: the system keychain, and the certificates an administrator or the user marked as always trusted; - Windows: the ROOT store; - Linux: the first CA bundle found (`/etc/ssl/certs/ca-certificates.crt`, `/etc/pki/tls/certs/ca-bundle.crt`, ...). `SSL_CERT_FILE` and `SSL_CERT_DIR` replace them on every system. `--ca-cert FILE` adds authorities, such as a company's own root or a test CA, and `--insecure` skips verification altogether. The host name of the URL is checked against the certificate (an IP address against its IP addresses). An upstream whose certificate is rejected gets the usual 502 `upstream-unreachable`, with the reason in the detail. ```yaml tls: cert: certs/server.pem # relative to the configuration file key: certs/server.key ca_certs: [certs/company-root.pem] insecure: false ``` ## Client certificates (mTLS) **Requiring them.** `--tls-client-ca clients-ca.pem` (or `tls.client_ca`) makes every HTTPS, WSS, gRPC and MQTTS connection present a client certificate issued by an authority of that PEM file, as a service behind mutual TLS does. It needs `--tls-cert`. The certificate's extended key usage must allow client authentication when it has one. - A client without a certificate, or with one the authorities didn't issue, fails the TLS handshake. The log gets a warning that says why, for example `TLS handshake with 127.0.0.1 failed: the client presented no certificate`. - The subject of an accepted certificate (`CN=billing, O=Example`) is in each event of the JSON log (`"clientSubject"`), on a `~ client` line of the stylish log, and in the admin API's log. - The contract report lists the clients: `clients` in JSON (`[{"subject": "CN=billing, O=Example", "exchanges": 12}]`, counting HTTP requests, gRPC calls, WebSocket connections and MQTT messages), a `client` property per subject in JUnit, and a `Clients:` line in the summary. - The admin API asks for a certificate too, on the main port and on `admin.port`. ```sh apigenie-server openapi.yaml --tls-cert server.pem --tls-key server.key --tls-client-ca clients-ca.pem curl --cacert ca.pem --cert client.pem --key client.key https://localhost:4010/pets ``` **Presenting one.** `--client-cert client.pem --client-key client.key` (or `tls.client_cert` and `tls.client_key`) is the certificate the proxies present to `https://`, `wss://`, `mqtts://` and gRPC TLS upstreams that ask for one. Upstreams that don't ask never see it. It works with `--insecure` too. The key must be PEM and not encrypted. An upstream that refuses the proxy for want of a certificate gets the usual 502 `upstream-unreachable`, which says so in the detail (an MQTT client's CONNECT gets return code 3). ```yaml tls: cert: certs/server.pem key: certs/server.key client_ca: certs/partners-ca.pem client_cert: certs/proxy.pem client_key: certs/proxy.key ``` **Not supported.** There is no session resumption: every connection does a full handshake. Neither certificate revocation lists (CRL) nor OCSP are checked, so a revoked client or upstream certificate is accepted as long as its chain is valid. Remove a revoked client's authority from `--tls-client-ca`, or issue client certificates with short lifetimes. --- # apigenie-catalog Source: https://apigenie.pl/docs/reference/catalog `apigenie-catalog` lists the API specifications of a repository, records their names and owners in the configuration file, and releases them as Git tags. It is installed next to `apigenie` by every archive and package, npm and Homebrew; `apigenie catalog ...` prints the `apigenie-catalog` command to run instead. > **(experimental, outside the 1.0 compatibility promise)** `apigenie-catalog` is the first part > of a catalog kept in Git: pinned consumers and a catalog spanning several repositories will add > options and settings. ## Usage ```sh apigenie-catalog list [DIR] [--json] [--config FILE | --no-config] [--git PROGRAM] apigenie-catalog init [DIR] [--prune] [--dry-run] [--config FILE] [--git PROGRAM] apigenie-catalog versions NAME [--json] [--config FILE | --no-config] [--git PROGRAM] apigenie-catalog release NAME VERSION [--dry-run] [--push] [--remote REMOTE] [--message MESSAGE] [--json] [--config FILE] [--git PROGRAM] apigenie-catalog --version | --credits | --license [LIBRARY] | --license-list ``` ## Description The repository that holds your specifications is the catalog: nothing is uploaded anywhere. `apigenie-catalog list` works in any repository without configuration. `apigenie-catalog init` writes a `catalog` section in [`apigenie.yaml`](/docs/reference/cli/configuration#catalog) for what can't be derived from the specifications, such as a name that stays when a file moves, an owner and a lifecycle. A release of a specification is a Git tag: `apigenie-catalog release` creates it and `apigenie-catalog versions` lists them. ### What is a specification `apigenie-catalog list` looks at the files below DIR (the current directory by default): - in a Git repository, the files Git tracks or would track: committed and staged files, and new files that no ignore rule (`.gitignore`, `.git/info/exclude`, your global excludes file) excludes; - outside git, every file except those in directories whose name starts with a dot, and in `node_modules`. Files matching a pattern of `catalog.exclude` are left out. Of the others, these are specifications: | Format | Files | | ------ | ----- | | OpenAPI, AsyncAPI, Swagger | JSON and YAML files whose root has the `openapi`, `asyncapi` or `swagger` property | | Protobuf | every `.proto` file | | GraphQL | `.graphql`, `.graphqls` and `.gql` files with type definitions (operation documents are left out) | The files of a split document that only hold components have no `openapi` property, so only its root file is listed. Files that can't be read are reported on the standard error. [What the catalog counts as a specification](/docs/concepts/what-the-catalog-counts-as-a-specification) explains these rules, the names and the root with a repository to try them on. ### What is listed | Column | JSON | Value | | ------ | ---- | ----- | | NAME | `name` | the name given in the catalog section, else derived: `info.title` (`Orders API` is `orders-api`), the Protobuf package (`acme.pricing.v1` is `acme-pricing-v1`), or the file name (GraphQL) | | FORMAT | `format`, `specVersion` | the format and its version: `OpenAPI 3.1.0`, `Protobuf proto3`, `GraphQL` | | VERSION | `version` | `info.version` | | OWNER | `owner` | the owner given in the catalog section; the column is shown when any specification has one | | LIFECYCLE | `lifecycle`, `sunset` | the lifecycle given in the catalog section, with the sunset day in parentheses when one is given: `deprecated (2027-03-31)`. When none is given, the table shows `active` and the JSON `null`. The column is shown when any specification has a `lifecycle` (since 0.12.0) | | PATH | `path` | the file, relative to the root of the catalog | | COMMIT | `commit` | the last commit changing the file (short id and day); `-` for a file not committed yet and outside git | ```text $ apigenie-catalog list NAME FORMAT VERSION PATH COMMIT order-events AsyncAPI 3.0.0 2.0.0 apis/events.json 96175d8 2026-10-12 orders-api OpenAPI 3.1.0 1.2.0 apis/orders/openapi.yaml 4d0c2e1 2026-10-14 schema GraphQL - graphql/schema.graphql 96175d8 2026-10-12 acme-pricing-v1 Protobuf proto3 - proto/pricing.proto 96175d8 2026-10-12 ``` Two specifications with the same derived name are reported on the standard error; name them in the catalog section, which `apigenie-catalog init` does. The **root of the catalog** is the directory of the configuration file (the one given with `--config`, else `apigenie.yaml` found in DIR or a parent up to the root of the repository), else the root of the Git repository, else DIR. Paths are relative to it, in the output and in the catalog section. DIR only narrows the search and must be inside the root. `versions` and `release` take no DIR: they read the catalog of the current directory, found as `list` finds it, and need a Git repository. ### `apigenie-catalog list` | Option | Description | | ------ | ----------- | | `DIR` | The directory to look for specifications in. Defaults to the current directory. | | `--json` | Prints the catalog as JSON (see below). | | `--config FILE` | Uses FILE instead of the configuration file found in the repository. | | `--no-config` | Uses no configuration file: no names, owners or exclusions. | | `--git PROGRAM` | The git program. Defaults to `git`. | With `--json`, the output follows [`apigenie-catalog-report.json`](https://apigenie.pl/schemas/apigenie-catalog-report.json): ```json { "formatVersion": 1, "root": "/home/me/specs", "config": "/home/me/specs/apigenie.yaml", "git": true, "specs": [ { "name": "orders-api", "title": "Orders API", "format": "openapi", "specVersion": "3.1.0", "version": "1.2.0", "path": "apis/orders/openapi.yaml", "owner": "team-commerce", "lifecycle": null, "sunset": null, "listed": true, "commit": { "id": "4d0c2e1f…", "shortId": "4d0c2e1", "author": "Jane Doe", "date": "2026-10-14T09:12:00+02:00", "subject": "Add order cancellation" } } ], "warnings": [] } ``` `listed` tells whether the catalog section lists the file. ### `apigenie-catalog init` Writes the `catalog` section of the configuration file from what `apigenie-catalog list` finds: one entry per specification with its name, its path and `owner: null`, for you to fill in. ```yaml catalog: specs: - name: order-events path: apis/events.json owner: null - name: orders-api path: apis/orders/openapi.yaml owner: null ``` - Without a configuration file, it creates `apigenie.yaml` at the root of the repository (or the file given with `--config`). - In an existing file, it appends the section, or replaces the lines of the section, and leaves the rest of the file as it is. A section written in flow style (`catalog: {...}`) and JSON files are rewritten whole; comments are kept. - Run it again after adding specifications: new ones are added, the entries you edited stay as they are, and entries whose files are gone are reported as "not found". `--prune` removes them. - Names that two specifications would share get a number: `orders-api-2`. | Option | Description | | ------ | ----------- | | `DIR` | The directory to look for specifications in. Defaults to the current directory. | | `--prune` | Removes the entries whose files are gone. | | `--dry-run` | Prints the configuration file instead of writing it. | | `--config FILE` | Writes FILE instead of the configuration file found in the repository; it is created if missing. | | `--git PROGRAM` | The git program. Defaults to `git`. | ```text $ apigenie-catalog init Updated /home/me/specs/apigenie.yaml: 2 added, 4 kept, 1 not found added apis/billing.yaml added apis/orders-v2.yaml not found legacy/swagger.yaml Remove the entries of the files that are gone with --prune. ``` The file is checked against the [configuration schema](/docs/reference/cli/config) before it is written, and `apigenie config check` accepts it. ### `apigenie-catalog versions` Since 0.12.0, lists the releases of a specification: the Git tags that match `catalog.tags.pattern` (`{name}-{version}` by default) for its name and hold a [semantic version](https://semver.org) where `{version}` stands, newest first. A tag that holds anything else there (`orders-api-next`) is not a release. Tags on commits that HEAD doesn't contain, such as on a maintenance branch, are releases too. Tags made with another pattern are not: after a change of `tags.pattern`, `versions` doesn't list them and `release` doesn't check against them. | Option | Description | | ------ | ----------- | | `NAME` | The name of the specification, as `list` prints it. | | `--json` | Prints the releases as JSON (see below). | | `--config FILE` | Uses FILE instead of the configuration file found in the repository. | | `--no-config` | Uses no configuration file: derived names and the default tag pattern. | | `--git PROGRAM` | The git program. Defaults to `git`. | ```text $ apigenie-catalog versions orders-api VERSION TAG COMMIT 1.1.0-rc.1 orders-api-1.1.0-rc.1 c121c1b 2026-10-28 1.0.0 orders-api-1.0.0 12e9f3d 2026-10-12 apis/orders/openapi.yaml is at info.version 1.1.0, which is not released ``` The last line appears when no release holds the file's `info.version`: the version about to be released, or a forgotten tag. Without a release the command prints `No releases of orders-api: no tag matches orders-api-*` and exits with status 0. With `--json`, the output follows [`apigenie-catalog-versions-report.json`](https://apigenie.pl/schemas/apigenie-catalog-versions-report.json): `name`, `path`, `tagPattern`, the file's `version` and whether it is `unreleased`, and `releases` (`version`, `tag`, `commit`), newest first. ### `apigenie-catalog release` Since 0.12.0, releases a specification: creates the annotated tag that `catalog.tags.pattern` names for NAME and VERSION at HEAD. It refuses, with every problem on the standard error and exit status 2, when: - VERSION is not a semantic version (`MAJOR.MINOR.PATCH`, with an optional pre-release such as `1.4.0-rc.1`; no `v`, no build metadata); - VERSION is released already, or below the latest release (a patch of an older line, such as 1.0.1 after 1.1.0, is tagged by hand); - the tag exists; - the file has changes that are not committed (staged or not, or the file is untracked); - the document has an `info.version` (OpenAPI, AsyncAPI, Swagger) and it is not VERSION. A Protobuf file or GraphQL schema has no version field, so its tag is its version; - the catalog section marks the specification `retired`. Nothing is pushed unless `--push` is given; the command prints the `git push` to run otherwise. When the push fails (no such remote, no access), the tag stays in the local repository: the command says so, prints the `git push` to run, and exits with status 2. | Option | Description | | ------ | ----------- | | `NAME` | The name of the specification, as `list` prints it. | | `VERSION` | The version to release. | | `--dry-run` | Runs the checks and prints the tag that would be created, without creating it. | | `--push` | Pushes the tag to the remote after creating it. | | `--remote REMOTE` | The remote `--push` pushes to. Defaults to `origin`. | | `--message MESSAGE` | The message of the annotated tag. Defaults to `NAME VERSION`. | | `--json` | Prints the release as JSON (see below), also when problems stop it. | | `--config FILE` | Uses FILE instead of the configuration file found in the repository. | | `--git PROGRAM` | The git program. Defaults to `git`. | ```text $ apigenie-catalog release orders-api 1.1.0 Tagged orders-api-1.1.0 at b2e21b5 Release 1.1.0 of the Orders API (previous release: 1.1.0-rc.1, tag orders-api-1.1.0-rc.1) Push it with: git push origin orders-api-1.1.0 $ apigenie-catalog release orders-api 1.1.0 1.1.0 is released already, as tag orders-api-1.1.0 at b2e21b5 orders-api 1.1.0 is not released ``` The lines of a refusal go to the standard error. With `--json`, the output follows [`apigenie-catalog-release-report.json`](https://apigenie.pl/schemas/apigenie-catalog-release-report.json): the `tag`, the `commit`, the `previous` release, whether the tag was `created` and `pushed`, the `remote` given with `--push` (else `null`), and the `problems` that stopped the release. The release of a specification is the tag, so `apigenie changelog` lists the changes between two releases with `--from orders-api-1.0.0 --to orders-api-1.1.0`, and `apigenie diff` compares the files that `git show orders-api-1.0.0:apis/orders/openapi.yaml` writes. ## Exit status | Status | Meaning | | ------ | ------- | | 0 | Success, also when files can't be read or specifications other than NAME share a name (reported on the standard error). | | 2 | The directory doesn't exist or is outside the root of the catalog, the configuration file is invalid, git fails, `versions` or `release` runs outside a Git repository, no specification or several have the NAME, a release is refused, `--push` fails (the tag stays in the local repository), an unknown `--license` library, or a usage error. | These are the statuses of every command ([exit status](/docs/reference/cli#exit-status)). ## See also - [Configuration](/docs/reference/cli/configuration#catalog): the `catalog` section. - [changelog](/docs/reference/cli/changelog): the history of a specification from git. --- # The editor's hosts Source: https://apigenie.pl/docs/reference/editor/hosts The API Genie editor edits OpenAPI 3.0, OpenAPI 3.1 and AsyncAPI 3.0 files in forms, on three hosts, with the same page in each: - **Web**: the editor's page in a browser (Chromium, Edge or Firefox), from a folder opened through the File System Access API or dropped on the page, at https://apigenie.pl/editor/, which every website deploy rebuilds from `main` (ADR-174). - **Desktop**: the same page in a window of its own. Since 0.12.0, each `cli-X.Y.Z` release at https://github.com/mykulyak/api-genie/releases has its installers for macOS, Windows and Linux, at the CLI's version. Around the page, the desktop app adds what needs the machine: the system `git`, a Node.js sidecar for the broker client, and the installed `apigenie-server` for the mock server. The app takes the `apigenie-server` that `APIGENIE_SERVER` names, else one next to the app, else the first on `PATH`. Outside Windows, it then looks in `/opt/homebrew/bin`, `/usr/local/bin` and `/home/linuxbrew/.linuxbrew/bin`. - **VS Code**: the same page in the API Genie extension's custom editor, *Open with API Genie Editor* (the `ide-X.Y.Z` releases, on the Marketplace from 1.0.0 on). VS Code owns the text, undo, saving, the colours and the code and diff editors; the extension runs the broker client with VS Code's own runtime, and the mock server with the installed `apigenie-server` (the `apigenie.serverPath` setting, else the first on `PATH`). *About* in the editor's toolbar says which host you are in, the editor's version and the host's own. It gives the addresses of the website and of the releases. ## What each host offers In the tables, **same** means the feature works as in the web editor; any other cell says what that host does instead, or adds a caveat after *same;*. <!-- host-matrix: generated by src/app_editor/src/app/host-features.test.ts from host-features.ts; UPDATE_GOLDEN=1 npm test rewrites it --> ### Opening a spec | Feature | Web | Desktop | VS Code | | --- | --- | --- | --- | | Open spec… (File › Open Spec… on the desktop): the spec, and the files its references reach | same; needs the File System Access API (Chromium, Edge); elsewhere, drop the spec and the files it refers to on the page | same | VS Code opens files: *Open with API Genie Editor* | | Allow access to a folder holding the files a spec's references name, when they can't be read | same; needs the File System Access API; the picked file alone can't reach its neighbours | same | The extension reads the files the spec refers to itself | | Drop a spec on the page | same; without the File System Access API, drop the files the spec refers to with it; a dropped folder is refused | No drop: open the spec with the dialog or on the command line | VS Code opens the spec: *Open with API Genie Editor* | | Start on a spec | A page has no command line: open or drop a spec | same; the spec given on the command line, `apigenie-editor <spec>` | The custom editor opens on its document | | Save files the host can't write to (dropped files) as downloads | same | same | same | ### Toolbar | Feature | Web | Desktop | VS Code | | --- | --- | --- | --- | | Undo and Redo | same | same | VS Code's undo, per document, which also undoes what was typed in its text editor | | Save, with the count of unsaved files | same | same | VS Code saves its documents; the unsaved marker is VS Code's | | Export bundled (the spec and the files it refers to, in one file) | same; needs the `openapi_bundle` WebAssembly module, which a build with `APIGENIE_WASM_DIR` ships | same | same; VS Code asks where to save the bundle | | Mock server (`apigenie-server`) serving the spec as it is edited | Runs `apigenie-server`, which a page can't start | same; needs `apigenie-server` 0.11.0 or later installed | same; needs `apigenie-server` 0.11.0 or later installed | | Theme: the system's, light or dark | same | same | The VS Code theme's colours; no setting of the editor's own | | The title's *API Genie*: a link to the website's home page, in a new tab | same | A link would take the window away from the editor: the name is plain text; About gives the website's addresses | The editor doesn't open links in VS Code's system browser yet: the name is plain text; About gives the website's addresses | | About: the editor's version, the host and its version, the commit it was built from, and the addresses of the website's Docs and Downloads pages, of this page and of the GitHub releases | same; the addresses are links, opened in a new tab | same; the addresses are text, to copy | same; the addresses are text, to copy | ### Menu bar | Feature | Web | Desktop | VS Code | | --- | --- | --- | --- | | Menu bar: File (New, Open Spec, Open Recent, Save, Save As, Close Spec, Exit), Edit (Undo, Redo) and View (Side Bar, Panel, Right Pane), with their shortcuts | A page has no menu bar: the toolbar's buttons and shortcuts; no Close Spec, since Ctrl+W closes the browser tab | same; Quit is in the application menu on macOS, where Edit also has Cut, Copy, Paste and Select All | same; VS Code's own menus, where File › Save and Edit › Undo act on its document and View lays out VS Code's window; *API Genie: New Spec…* is in the Command Palette and the editor's title bar | | File › New…: a new OpenAPI 3.1 or AsyncAPI 3.0 spec next to the open spec, unsaved until Save | No menu bar: create the file outside the editor, then open it | same | same; *API Genie: New Spec…* in the Command Palette or the editor's title bar; VS Code creates the file at once | | File › New… and New spec… with no spec open: the kind, then where to save it, and the new spec opens | No menu bar and no *New spec…* button: create the file outside the editor, then open it | same | *API Genie: New Spec…* puts the new spec next to the file open in the editor: open a spec, or an empty `.yaml` file made with File › New File…, with *Open with API Genie Editor* first | | File › Open Recent: the last ten specs opened, and the last one opens again at start | No Open Recent: the editor keeps no spec's file handle between visits, so Open spec… asks for the spec each time | same; a spec given on the command line opens instead of the last one | VS Code's File › Open Recent and the editors it restores | | View › Side Bar, Panel and Right Pane: show or hide each part of the window, with a check on the ones shown | No menu bar: the status bar's problem counts show and hide the panel; the side bar and the right pane always show | same; Ctrl+B, Ctrl+J and Ctrl+Alt+B (Cmd+B, Cmd+J and Cmd+Option+B on macOS), as in VS Code | VS Code's own View menu lays out its window; in the editor, the status bar's problem counts show and hide the panel | | File › Save As…: the current file's text, anywhere on disk; a copy inside the spec's folder joins it | No Save As: a page can only write the files it opened | same | VS Code's File › Save As… | | Asks to save unsaved files before closing or opening another spec | Unsaved changes are lost when the tab closes or another spec opens | same | VS Code asks about its unsaved documents | ### Panels | Feature | Web | Desktop | VS Code | | --- | --- | --- | --- | | API tree: search, filters, add, rename and delete | same | same | same | | File list with unsaved markers | same | same | same | | Forms for every node, with the Raw section and quick fixes | same | same | same | | Preview: the docs of the selected node, OpenAPI and AsyncAPI | same | same | same | | Flow: the AsyncAPI message flow diagram, editable | same | same | same | | Changes: the API changes since the last save, with their severity | same | same | same | | Changes: the text diff since the last save | same | same | *Show the text changes in the diff editor* opens VS Code's, on the live document | | Git tab: status, diff, commit, branches | No Git tab: it runs the system git, which a page can't | same | No Git tab: VS Code's Source Control view does that | | Problems: validation and API Genie's linters (the rules of `apigenie lint`), under the fields and in the bottom panel's Problems tab | same | same | same | | Problems: the linters read `commands.lint` of the nearest `apigenie.yaml`, and the ruleset files its `extends` names, as `apigenie lint` does. They leave out custom functions and the rules that call them, with a warning. They don't have the [`owasp`](/docs/reference/cli/lint#the-owasp-ruleset) and [`camara`](/docs/reference/cli/lint#the-camara-ruleset) rulesets. Either one in `apigenie.yaml`'s `extends` is an error, and the default rules apply. A ruleset that a ruleset file extends and the linters don't have (`owasp`, `camara`, `@stoplight/spectral-owasp-ruleset`, `spectral:oas`, an npm package) is left out with a warning; the file's other rules apply. An `extends` entry with an absolute path, or a relative path more than 8 folders up, is an error on that entry, and so is a ruleset file that can't be read or doesn't parse. The default rules then apply. With no configuration file, a Spectral ruleset (`.spectral.yaml`, `.yml` or `.json`) found in the same places gets an info finding that names [Migrate from Spectral](/docs/guides/migrate-from-spectral) | same; found among the files you dropped with the spec (Open spec… reads the spec alone), or in a folder allowed with Allow access to their folder…, which appears only when a referenced file can't be read; read when the spec opens; in Safari and Firefox, drop the ruleset files it extends with it, which works only for files beside it (`./house.yaml`), as dropped files have no folders | same; found in the spec's folder, or in a folder allowed with Allow access to their folder…, which appears only when a referenced file can't be read; read when the spec opens | same; found in the workspace folder, or the spec's folder outside a workspace, without stopping at a nested Git repository; an edit to it, or to a ruleset file it extends, applies as you type; ruleset files are read only inside the workspace folder, when named `.yaml`, `.yml` or `.json`, and outside `node_modules`, `.git`, `dist` and `build` | | Library › My schemas: schemas kept by the editor, dragged to and from schema fields, schema rows and the tree | same; kept in this browser's storage for the site | same | same; kept in the extension's global storage | | Library folders: shared schemas in folders beside the spec folder, referred to by relative $ref | same; needs the File System Access API; you type where the folder is, and allow access again after a reload | same; after a restart, Open shows the folder in the dialog to allow access again | same; set in the `apigenie.editor.libraryFolders` setting | ### Editing | Feature | Web | Desktop | VS Code | | --- | --- | --- | --- | | Files changed on disk (a `git checkout`, another editor) are read again when the window gets the focus back; a file with unsaved changes keeps them, the status bar names it, and Save writes over the disk's version | same; needs the File System Access API (Chromium, Edge): files dropped in other browsers are not read again | same | VS Code reloads its documents, and the editor follows them | | Show as code: a node's text in a code editor, inside its form. On a file's root form, such as the *Specification* row's or a file picked in the file list, the whole file, in place of the form. *Show the file as code* does the same while the file has syntax errors or no longer holds the node. A Protobuf file has no form: its code shows instead | same | same | *Show in the text editor* opens VS Code's at the node; a Protobuf file, and a file with syntax errors, are edited in VS Code's text editor | | Import: Swagger 2.0, AsyncAPI 2.x and Postman collections, with the conversion shown as a diff | same | same | *Show the conversion in the diff editor* opens VS Code's | | Ctrl+S / Cmd+S saves | same | same | Asks VS Code to save | | Ctrl+Z / Cmd+Z and Ctrl+Shift+Z undo and redo | same | same | VS Code's undo | ### Try it out | Feature | Web | Desktop | VS Code | | --- | --- | --- | --- | | Try it out: HTTP requests from the operation's preview | same | same | same | | CORS proxy setting for servers that refuse the page's requests | same | same | Not needed: the extension host sends the requests, and CORS doesn't apply | | Authorize with OAuth 2.0 authorization-code and implicit flows (a popup) | same | same | same; the authorization page opens in the system browser, which returns to `http://127.0.0.1:33418/oauth2-redirect` (port in the `apigenie.tryIt.oauth2RedirectPort` setting): register that redirect URL | | Send Try it out to the mock server | Runs `apigenie-server`, which a page can't start | same; needs `apigenie-server` 0.11.0 or later installed | same; needs `apigenie-server` 0.11.0 or later installed | | Try it: publish and subscribe on Kafka, AMQP, MQTT and WebSocket servers (AsyncAPI operations) | Runs a Node.js sidecar, which a page can't start | same | same | <!-- /host-matrix --> ## Host limits Each difference above comes from something the host can't do, or does itself. ### The web editor has no Git tab, broker Try it or mock server They run the system `git`, the broker client's Node.js sidecar and `apigenie-server`, which a web page can't start. The desktop app and the VS Code extension have them. Their mock server needs [API Genie](/tools/server) 0.11.0 or later installed, and names the install commands when it isn't. The Git tab, broker Try it and the mock server may come to the web editor later through integration packages for the frameworks the generators target; none is planned yet. ### VS Code has its own text editor, diff editor and Source Control The custom editor shows no code, of a file or of a node, and no text diffs of its own. *Show in the text editor* opens VS Code's text editor at the node, and *Show the text changes in the diff editor* and *Show the conversion in the diff editor* open VS Code's diff editor. The Git tab's job is VS Code's Source Control view's. Undo, the unsaved marker and Save are VS Code's, since the document is VS Code's, and the editor takes the colours of the VS Code theme. ### VS Code opens folders itself The custom editor works on the file's workspace folder, with its other spec files for `$ref`s; there is no folder picker and no drop. *API Genie: New Spec…*, in the Command Palette and the editor's title bar, does what File › New… does on the desktop with a spec open: the new spec goes next to the one in the editor. Try it out sends its requests from the extension host, so no CORS proxy is needed. The OAuth 2.0 flows with a browser step (authorization code, implicit) can't return to a webview, so the extension opens the authorization page in your system browser, and the authorization server sends it back to `http://127.0.0.1:33418/oauth2-redirect`, which the extension listens on only while a flow waits. Register that redirect URL for your client; choose another port with the `apigenie.tryIt.oauth2RedirectPort` setting. In a remote window (SSH, a container), the browser can reach that address only when VS Code forwards the port. --- # @mykulyak/apigenie-docs Source: https://apigenie.pl/docs/reference/doc-components See also: [apg-api-reference and apg-spec](https://apigenie.pl/docs/reference/doc-components/reference-and-spec.md), [OpenAPI elements](https://apigenie.pl/docs/reference/doc-components/openapi.md), [Swagger 2.0 elements](https://apigenie.pl/docs/reference/doc-components/swagger.md), [AsyncAPI elements](https://apigenie.pl/docs/reference/doc-components/asyncapi.md), [Protobuf and gRPC elements](https://apigenie.pl/docs/reference/doc-components/protobuf.md), [GraphQL elements](https://apigenie.pl/docs/reference/doc-components/graphql.md), [Building blocks](https://apigenie.pl/docs/reference/doc-components/building-blocks.md), [Try it out](https://apigenie.pl/docs/reference/doc-components/try-it-out.md), [Theming](https://apigenie.pl/docs/reference/doc-components/theming.md), [Server-side rendering](https://apigenie.pl/docs/reference/doc-components/server-side-rendering.md), [apigenie-docs build](https://apigenie.pl/docs/reference/doc-components/docs-build.md). The npm package `@mykulyak/apigenie-docs` holds the doc components: standard custom elements, built with Lit, that document OpenAPI 3.0 and 3.1, Swagger 2.0, AsyncAPI 3.0 and 3.1, Protobuf (proto3) and GraphQL APIs on a page, with Try it out for OpenAPI, Swagger 2.0 and GraphQL. It also holds `apigenie-docs build`, which renders the docs bundle of `apigenie-generator docs` into a static site ([apigenie-docs build](/docs/reference/doc-components/docs-build)). The [live examples](/tools/doc-components/examples) render one API in OpenAPI, AsyncAPI, GraphQL and Protobuf with these elements. The guide [Publish API documentation](/docs/guides/publish-api-documentation#or-put-a-reference-into-your-own-page) puts a reference into a page. ## Loading the elements | Where | How | | --- | --- | | Plain HTML or a CMS | `<script type="module" src="…/apigenie-web-components.js"></script>`, the file in the package's `dist/cdn/`. | | A bundler, every element | `import "@mykulyak/apigenie-docs";` | | A bundler, one element | `import "@mykulyak/apigenie-docs/components/apg-operation";` | | Server-side rendering | `@mykulyak/apigenie-docs/ssr`, then the `hydrate` entry point in the browser ([Server-side rendering](/docs/reference/doc-components/server-side-rendering)). | ```sh npm install @mykulyak/apigenie-docs ``` ```html <script type="module"> import "@mykulyak/apigenie-docs"; </script> <apg-api-reference spec-url="/openapi.yaml"></apg-api-reference> ``` ## Elements `<apg-api-reference>` renders a whole reference and picks the elements of the document's standard by itself. The other elements show one part of a document each, for a page of your own design. ### [apg-api-reference and apg-spec](/docs/reference/doc-components/reference-and-spec) | Element | What it shows | | --- | --- | | [`<apg-api-reference>`](/docs/reference/doc-components/reference-and-spec#apg-api-reference) | An API reference: navigation with search, overview, servers, authentication, operations grouped by tag with Try it out, and schemas. | | [`<apg-spec>`](/docs/reference/doc-components/reference-and-spec#apg-spec) | Loads an API document (OpenAPI, Swagger 2.0, AsyncAPI, Protobuf or GraphQL) and shares it with the elements inside it, which then need no `spec-url` of their own. | | [`<apg-nav>`](/docs/reference/doc-components/reference-and-spec#apg-nav) | Navigation: operations grouped by tag, webhooks and schemas, with search. | | [`<apg-changelog>`](/docs/reference/doc-components/reference-and-spec#apg-changelog) | The git changelog of a document, as `apigenie-generator docs --changelog` writes it into the docs bundle (`changelog.json`): by revision (newest first; what each release or commit added, removed, deprecated or changed, with a badge for breaking changes), or the history of each operation (`view="items"`). | ### [OpenAPI elements](/docs/reference/doc-components/openapi) | Element | What it shows | | --- | --- | | [`<apg-overview>`](/docs/reference/doc-components/openapi#apg-overview) | Title, version, description, contact, license and external documentation of the API. | | [`<apg-operation>`](/docs/reference/doc-components/openapi#apg-operation) | Documentation of one operation: parameters, request body, responses (with examples and schemas), security and callbacks, with an optional embedded Try it out. | | [`<apg-schema>`](/docs/reference/doc-components/openapi#apg-schema) | Schema as an expandable tree: properties, items, combinators, constraints, enums, defaults and examples. | | [`<apg-try-it>`](/docs/reference/doc-components/openapi#apg-try-it) | Sends requests to the API: parameters, request body (text, forms, file uploads), server and credentials, with a live URL preview, code samples and a response viewer that streams server-sent events and NDJSON. | | [`<apg-auth>`](/docs/reference/doc-components/openapi#apg-auth) | Credentials for the API's security schemes: API keys, HTTP Basic and Bearer, OAuth 2.0 flows (authorization code with PKCE, client credentials, implicit, password) and OpenID Connect discovery. | | [`<apg-servers>`](/docs/reference/doc-components/openapi#apg-servers) | Chooses the server Try it out sends requests to: a declared server with its variables, or a custom URL. | | [`<apg-code-samples>`](/docs/reference/doc-components/openapi#apg-code-samples) | Code samples for a request: curl, JavaScript (fetch) and Python (requests). | ### [Swagger 2.0 elements](/docs/reference/doc-components/swagger) | Element | What it shows | | --- | --- | | [`<apg-swagger-overview>`](/docs/reference/doc-components/swagger#apg-swagger-overview) | Title, version, description, contact, license and external documentation of a Swagger 2.0 API. | | [`<apg-swagger-hosts>`](/docs/reference/doc-components/swagger#apg-swagger-hosts) | Where a Swagger 2.0 API is served: `host`, `basePath` and `schemes`, the resulting base URLs, and the media types the API consumes and produces. | | [`<apg-swagger-security>`](/docs/reference/doc-components/swagger#apg-swagger-security) | The security definitions of a Swagger 2.0 document: type, where API keys go, OAuth 2.0 flow, URLs and scopes, and the requirements that apply to every operation. | | [`<apg-swagger-operation>`](/docs/reference/doc-components/swagger#apg-swagger-operation) | Documentation of one operation of a Swagger 2.0 document: the media types it consumes and produces, path, query, header and form parameters, the body parameter, responses with their headers, examples and schemas, and security, with an optional embedded Try it out. | ### [AsyncAPI elements](/docs/reference/doc-components/asyncapi) | Element | What it shows | | --- | --- | | [`<apg-asyncapi-overview>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-overview) | Title, version, description, contact, license, tags and external documentation of an AsyncAPI 3 document, with its `id` and default content type. | | [`<apg-asyncapi-servers>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-servers) | The servers of an AsyncAPI document (or the one named by `server`): protocol, URL, variables, security, the channels available on it and its bindings. | | [`<apg-asyncapi-security>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-security) | The security schemes of an AsyncAPI document (`components.securitySchemes`): type, what it asks for, where API keys go, OAuth 2.0 flows with their URLs and scopes, OpenID Connect discovery. | | [`<apg-asyncapi-operation>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-operation) | One operation of an AsyncAPI document: its action (send or receive), channel and address, the messages with their headers, payloads and examples, the reply of request/reply operations, security, traits and bindings. | | [`<apg-asyncapi-channel>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-channel) | One channel of an AsyncAPI document: its address with parameters, the servers it is on, its messages, the operations on it, and its bindings. | | [`<apg-asyncapi-message>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-message) | One message of an AsyncAPI document: content type, headers and payload (schema trees, or the schema as written for formats such as Avro and Protobuf), examples, correlation ID, bindings, and the channels and operations using it. | | [`<apg-asyncapi-bindings>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-bindings) | The protocol bindings of an AsyncAPI server, channel, operation or message, given as the `bindings` of their view: one block per protocol with its `bindingVersion` and fields. | ### [Protobuf and gRPC elements](/docs/reference/doc-components/protobuf) | Element | What it shows | | --- | --- | | [`<apg-protobuf-overview>`](/docs/reference/doc-components/protobuf#apg-protobuf-overview) | The package, file, syntax, header comment, imports and file options of a Protobuf file. | | [`<apg-protobuf-service>`](/docs/reference/doc-components/protobuf#apg-protobuf-service) | A gRPC service of a Protobuf file: its description, options and methods, each with its streaming kind, request and response. | | [`<apg-protobuf-method>`](/docs/reference/doc-components/protobuf#apg-protobuf-method) | A gRPC method: its streaming kind, HTTP/2 path, request and response messages (with their fields), HTTP/JSON transcoding rules (`google.api.http`), JSON examples of both messages and code samples. | | [`<apg-protobuf-message>`](/docs/reference/doc-components/protobuf#apg-protobuf-message) | A message of a Protobuf file: its fields (number, name and JSON name, type, label, oneof, options, comment), oneofs, reserved numbers and names, nested types, the methods using it and an example in the proto3 JSON form. | | [`<apg-protobuf-enum>`](/docs/reference/doc-components/protobuf#apg-protobuf-enum) | An enum of a Protobuf file: its values (name, number, comment, deprecation), reserved numbers and names, and options. | | [`<apg-grpc-code-samples>`](/docs/reference/doc-components/protobuf#apg-grpc-code-samples) | Code samples calling a gRPC method with its example request: grpcurl, Node.js (`@grpc/grpc-js`), Python (`grpcio`) and Go, in the form each takes for the method's streaming kind. | ### [GraphQL elements](/docs/reference/doc-components/graphql) | Element | What it shows | | --- | --- | | [`<apg-graphql-overview>`](/docs/reference/doc-components/graphql#apg-graphql-overview) | The description of a GraphQL schema, its file, root operation types, size and schema directives. | | [`<apg-graphql-operation>`](/docs/reference/doc-components/graphql#apg-graphql-operation) | A GraphQL operation, that is a field of a root operation type (`Query.books`): its arguments, the type it returns (with its fields), an example operation with variables and a response, code samples and Try it out. | | [`<apg-graphql-type>`](/docs/reference/doc-components/graphql#apg-graphql-type) | A type of a GraphQL schema: object and interface types with their fields (and the fields' arguments), input types with their fields and default values, enums with their values, unions with their members, and scalars; the interfaces a type implements, the types implementing an interface, the unions an object belongs to, where the type is used, and an example value of input types. | | [`<apg-graphql-directive>`](/docs/reference/doc-components/graphql#apg-graphql-directive) | A directive definition of a GraphQL schema: its arguments, where it may be used and whether it is repeatable. | | [`<apg-graphql-code-samples>`](/docs/reference/doc-components/graphql#apg-graphql-code-samples) | Code samples sending a GraphQL operation with its example variables: curl, JavaScript (`fetch`) and Python (`requests`), each posting `{query, variables, operationName}` as JSON. | | [`<apg-graphql-try-it>`](/docs/reference/doc-components/graphql#apg-graphql-try-it) | Sends a GraphQL operation to an endpoint: the operation (prefilled with the example), its variables and headers, posted as JSON. | ### [Building blocks](/docs/reference/doc-components/building-blocks) | Element | What it shows | | --- | --- | | [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown) | CommonMark/GFM from the document, sanitized: raw HTML is shown as text, links are limited to http(s)/mailto and open in a new tab, and `#/components/schemas/X` links go to the schema page. | | [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block) | Code with a copy button. | | [`<apg-method-badge>`](/docs/reference/doc-components/building-blocks#apg-method-badge) | HTTP method label, the action of an AsyncAPI operation (`send`, `receive`), the streaming kind of a gRPC method (`unary`, `server-stream`, `client-stream`, `bidi`), or the kind of a GraphQL operation (`query`, `mutation`, `subscription`). | An element given a kind of document it does not show (an OpenAPI element given a Swagger 2.0 or AsyncAPI document, and so on) shows a notice naming the element to use instead, or saying that there is none: `<apg-try-it>`, `<apg-auth>`, `<apg-servers>` and `<apg-code-samples>` are for OpenAPI and Swagger 2.0 documents. ## Where the document comes from The elements that show part of a document have these attributes and properties. They take the document from the first of `api`, `spec` and `spec-url` that is set, and otherwise from the enclosing `<apg-spec>` or `<apg-api-reference>`: | Attribute or property | | | --- | --- | | `api` (property) | An `ApiContext` shared explicitly. Composite elements pass theirs to their parts. | | `spec` (property) | The document as YAML or JSON text, `.proto` or GraphQL text, or a parsed value. | | `spec-url` | A URL. Elements naming the same URL share one context: the document is fetched and parsed once, and the server choice, the credentials and the Try it out input are shared by every element of the page. | | `theme` | `light` or `dark`; by default the page's `color-scheme` decides. | `<apg-code-block>`, `<apg-method-badge>` and `<apg-asyncapi-bindings>` show what they are given and have none of these. `<apg-spec>` and `<apg-api-reference>` also read a child `<script type="application/yaml" data-spec>` (or `application/json`), for a CMS where the document is pasted into the page. ## WebAssembly modules AsyncAPI documents, `.proto` files and GraphQL schemas are read by WebAssembly modules built from the same parsers as the `apigenie` CLI. They are in the package's `dist/wasm/`, and the page loads one when it shows a document of its standard: | Standard | Module | Attribute on `<apg-spec>` and `<apg-api-reference>` | For every element | | --- | --- | --- | --- | | AsyncAPI | `asyncapi.web.mjs`, `asyncapi.web.wasm` | `asyncapi-wasm-url` | `configureAsyncApiEngine(url)` | | Protobuf | `protobuf.web.mjs`, `protobuf.web.wasm` | `protobuf-wasm-url` | `configureProtobufEngine(url)` | | GraphQL | `graphql.web.mjs`, `graphql.web.wasm` | `graphql-wasm-url` | `configureGraphQLEngine(url)` | There is no JavaScript reader of these standards to fall back on: without its module, a document fails to load. The documentation model the module writes (`{"apigenieAsyncAPI": 1, …}`, `{"apigenieProtobuf": 1, …}`, `{"apigenieGraphQL": 1, …}`), which a docs bundle holds, can be given instead of the text and needs no module. OpenAPI and Swagger 2.0 documents are read in JavaScript. ## Frameworks | Framework | What it needs | | --- | --- | | Plain HTML, a CMS | The `<script type="module">` tag; the document inline in a `<script type="application/yaml" data-spec>` child when there is no URL for it. | | React 19 | Nothing: properties such as `spec` and events such as `onapg-request` work natively. React 18 sets properties through a `ref`. | | Vue | `compilerOptions.isCustomElement = (tag) => tag.startsWith("apg-")`, then `<apg-operation :spec="doc" operation-id="getPet" />`. | | Svelte | Nothing: `<apg-spec spec-url="/openapi.yaml">`. | | Angular | `CUSTOM_ELEMENTS_SCHEMA` on the component or the module. | TypeScript knows the elements (`HTMLElementTagNameMap`) and their events (`HTMLElementEventMap`). The package's `custom-elements.json` lists every attribute, property, event, slot, CSS part and CSS custom property, for editors and framework type generators; the pages of this reference are written from it. ## Limitations - OpenAPI 3.0 and 3.1, Swagger 2.0, AsyncAPI 3.0 and 3.1 and proto3 only. OpenAPI 3.2, Swagger 1.x, AsyncAPI 2.x, proto2 and editions are reported as unsupported. - Only references within the document are resolved: bundle a document of several files first (`apigenie bundle`). - Large YAML documents are parsed on the main thread. - The WebAssembly parser engine (`parserEngine`) reads OpenAPI documents; Swagger 2.0 documents always use the JavaScript one. - In Try it out, a `collectionFormat` other than `csv` on path and header parameters of a Swagger 2.0 document is sent comma-separated. - AsyncAPI documents are documentation only: there is no Try it out for brokers. Bindings are listed as written, not explained per protocol, and schemas in formats other than JSON Schema (Avro, Protobuf, RAML) are shown as written. - Protobuf files are documentation only as well: browsers cannot call gRPC services, and the code samples show how to. One file is documented at a time, with the standard imports; extensions (`extend`) are not listed. - GraphQL schemas are read from SDL only, not from introspection results, one file at a time. Try it out sends queries and mutations over HTTP, not subscriptions over WebSocket or SSE. --- # apg-api-reference and apg-spec Source: https://apigenie.pl/docs/reference/doc-components/reference-and-spec Part of the reference of [@mykulyak/apigenie-docs](https://apigenie.pl/docs/reference/doc-components.md). Its other pages: [OpenAPI elements](https://apigenie.pl/docs/reference/doc-components/openapi.md), [Swagger 2.0 elements](https://apigenie.pl/docs/reference/doc-components/swagger.md), [AsyncAPI elements](https://apigenie.pl/docs/reference/doc-components/asyncapi.md), [Protobuf and gRPC elements](https://apigenie.pl/docs/reference/doc-components/protobuf.md), [GraphQL elements](https://apigenie.pl/docs/reference/doc-components/graphql.md), [Building blocks](https://apigenie.pl/docs/reference/doc-components/building-blocks.md), [Try it out](https://apigenie.pl/docs/reference/doc-components/try-it-out.md), [Theming](https://apigenie.pl/docs/reference/doc-components/theming.md), [Server-side rendering](https://apigenie.pl/docs/reference/doc-components/server-side-rendering.md), [apigenie-docs build](https://apigenie.pl/docs/reference/doc-components/docs-build.md). `<apg-api-reference>` renders a whole reference from one tag: navigation with search, the overview, servers, authentication, the operations with Try it out, and the schemas. For an AsyncAPI document, a Protobuf file or a GraphQL schema it uses the elements of that standard. `<apg-spec>` loads a document and shares it with the elements inside it, for a page of your own design. Both carry the settings of Try it out ([Try it out](/docs/reference/doc-components/try-it-out)). ## A page of your own from parts ```html <apg-spec spec-url="/openapi.yaml" oauth2-client-id="docs-site"> <apg-overview></apg-overview> <h2>Quick start</h2> <apg-auth schemes="ApiKey"></apg-auth> <apg-operation operation-id="getPet" try-it="none"></apg-operation> <apg-try-it operation-id="getPet"></apg-try-it> <apg-schema name="Pet" depth="2" with-example></apg-schema> </apg-spec> ``` Operations are selected with `operation-id`, or with `method` and `path`. The pages of [AsyncAPI](/docs/reference/doc-components/asyncapi), [Protobuf](/docs/reference/doc-components/protobuf) and [GraphQL](/docs/reference/doc-components/graphql) elements show the same page for their standards. ## Pages and routes With `layout="sidebar"`, the default, `<apg-api-reference>` shows one page at a time and keeps it in the URL as `routing` says: | `routing` | The URL of an operation's page | | --- | --- | | `hash` (default) | `#/operation/getPet` | | `history` | `<base-path>/operation/getPet`; the server must serve the reference's page for these paths. | | `none` | Unchanged; `route` names the page, as in server-side rendering. | `route` takes `operation/getPet`, `tag/pets` or `schema/Pet`; for AsyncAPI `channel/orders` or `message/orderCreated`; for Protobuf `service/LibraryService`, `method/LibraryService.GetBook`, `message/Book` or `enum/Genre`; for GraphQL `operation/query.books`, `type/Book` or `directive/auth`. `layout="single"` shows every page one after the other and scrolls to the target. Links between pages emit the cancelable `apg-navigate` event: cancel it to route with your application's router. ## `<apg-api-reference>` An API reference: navigation with search, overview, servers, authentication, operations grouped by tag with Try it out, and schemas. It is built from the public parts (`<apg-nav>`, `<apg-operation>`, …) and forwards their CSS parts. Swagger 2.0 documents are shown with the `apg-swagger-*` parts (overview, hosts, security definitions, operations) and their schemas are called definitions. AsyncAPI 3 documents are shown with the `apg-asyncapi-*` parts: overview, servers and security schemes, then pages for operations, channels, messages and schemas. Protobuf files are shown with the `apg-protobuf-*` parts: an overview with the services, then pages for services, gRPC methods, messages and enums. GraphQL schemas are shown with the `apg-graphql-*` parts: an overview with the queries, mutations and subscriptions, then pages for operations (with Try it out), types and directives. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-api-reference";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `layout` | `layout` | `"sidebar" \| "single"` | `"sidebar"` | `sidebar` (one page at a time) or `single` (everything on one page). | | `routing` | `routing` | `RoutingMode` | `"hash"` | How the current page is kept in the URL: `hash`, `history` or `none`. | | `base-path` | `basePath` | `string` | `"/"` | With `routing="history"`: the path the reference is mounted at, such as `/docs`. | | `route` | `route` | `string` | | Page to show, such as `operation/getPet` (used by server-side rendering and with `routing="none"`). | | `hide-try-it` | `hideTryIt` | `boolean` | `false` | Hides Try it out, and the server and credential choices it needs. | | `hide-schemas` | `hideSchemas` | `boolean` | `false` | Hides the schemas (definitions in Swagger 2.0) from the overview and the navigation. | | `show-problems` | `showProblems` | `boolean` | `false` | Show problems found in the document (unresolved references, validation issues). | | `changelog-url` | `changelogUrl` | `string` | | URL of the changelog of a docs bundle (`changelog.json`), fetched in the browser; adds the Changelog page. | | `proxy-url` | `proxyUrl` | `string` | | CORS proxy: `https://proxy.example/?url={url}`, or a prefix the request URL is appended to. | | `credentials` | `credentials` | `RequestCredentials` | `"same-origin"` | Credentials mode of Try-it-out requests: `omit`, `same-origin` or `include`. | | `timeout` | `timeout` | `number` | `30000` | Try-it-out timeout in milliseconds. | | `max-response-bytes` | `maxResponseBytes` | `number` | `5242880` | Response bodies larger than this many bytes (5 MiB) are truncated. | | `persist-auth` | `persistAuth` | `PersistMode` | | Keep credentials across page loads: `session` or `local` storage (default: memory only). | | `oauth2-redirect-url` | `oauth2RedirectUrl` | `string` | | Redirect page registered with the OAuth 2.0 authorization server. | | `oauth2-client-id` | `oauth2ClientId` | `string` | | OAuth 2.0 client ID used by every OAuth 2.0 / OpenID Connect scheme without its own `authConfig`. | | `schema-depth` | `schemaDepth` | `number` | `6` | Levels of referenced schemas expanded inline. | | `asyncapi-wasm-url` | `asyncapiWasmUrl` | `string` | | URL of the asyncapi WebAssembly module (`asyncapi.web.mjs`, with `asyncapi.web.wasm` next to it), which reads AsyncAPI documents; loaded when one is shown. | | `protobuf-wasm-url` | `protobufWasmUrl` | `string` | | URL of the protobuf WebAssembly module (`protobuf.web.mjs`, with `protobuf.web.wasm` next to it), which reads .proto documents; loaded when one is shown. | | `graphql-wasm-url` | `graphqlWasmUrl` | `string` | | URL of the graphql WebAssembly module (`graphql.web.mjs`, with `graphql.web.wasm` next to it), which reads GraphQL schemas; loaded when one is shown. | | `graphql-endpoint` | `graphqlEndpoint` | `string` | | The URL GraphQL operations are sent to (default: `/graphql` on the origin of the document). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Properties | Property | Type | Description | | --- | --- | --- | | `changelog` | `ChangelogFile` | The changelog of a docs bundle, as a value; adds the Changelog page. | | `examples` | `ExampleFile[]` | The example files of a docs bundle, shown on the overview or on the operation they are named after. | | `locales` | `LocaleLink[]` | The same page in other languages (a docs bundle with several locales): the locale switcher of the sidebar. | | `authConfig` | `Record<string, OAuthClientConfig>` | OAuth 2.0 client settings per security scheme. | | `fetch` | `typeof fetch` | `fetch` used by Try it out (for example to add tracing). | | `requestInterceptor` | `ApiSettings["requestInterceptor"]` | Called with every Try-it-out request before it is sent. | | `responseInterceptor` | `ApiSettings["responseInterceptor"]` | Called with every Try-it-out response. | | `parserEngine` | `ParserEngine` | Parser of documents given as text (default: the JavaScript parser). | | `asyncapiEngine` | `AsyncApiEngine` | Reads AsyncAPI documents (instead of `asyncapi-wasm-url`). | | `protobufEngine` | `ProtobufEngine` | Reads .proto documents (instead of `protobuf-wasm-url`). | | `graphqlEngine` | `GraphQLEngine` | Reads GraphQL schemas (instead of `graphql-wasm-url`). | ### Methods | Method | Description | | --- | --- | | `navigate(route)` | Shows a page (and records it in the URL unless `routing="none"`). | ### Events | Event | Description | | --- | --- | | `apg-navigate` | A link was followed; cancel it to route yourself. | | `apg-spec-load` | The document was parsed. | | `apg-spec-error` | The document could not be loaded or parsed. | ### Slots | Slot | Description | | --- | --- | | `logo` | Shown at the top of the sidebar. | | `header` | Shown above the content. | | `intro` | Shown on the overview page, before the API description. | | `footer` | Shown after the content. | ### CSS parts | Part | Description | | --- | --- | | `reference` | The layout grid. | | `sidebar` | The sidebar. | | `content` | The main content. | | `menu-button` | Opens the sidebar on narrow screens. | | `page-title` | Headings of tag and schema pages. | | `problems` | The problems panel (`show-problems`). | | `operation-link` | Operation links in the overview's index. | | `channel-link` | Channel links in the overview's index (AsyncAPI). | | `message-link` | Message links in the overview's index (AsyncAPI, Protobuf). | | `service-link` | Service links in the overview's index (Protobuf). | | `method-link` | Method links in the overview's index (Protobuf). | | `enum-link` | Enum links in the overview's index (Protobuf). | | `type-link` | Type links in the overview's index (GraphQL). | | `directive-link` | Directive links in the overview's index (GraphQL). | | `section-title` | Headings of the overview's sections (servers, authentication, operations, …). | | `address` | Channel addresses in the overview's index (AsyncAPI). | | `locales` | The language switcher, when the reference has `locales`. | | `locale` | One language in it. | | `examples` | The example files of the overview or of a GraphQL operation (`examples`). | | `example-title` | The name of an example file, with its download link. | Forwarded from the elements inside it: - [`<apg-nav>`](/docs/reference/doc-components/reference-and-spec#apg-nav): `nav`, `search`, `nav-group`, `nav-group-title`, `nav-item`, `nav-item-active` - [`<apg-method-badge>`](/docs/reference/doc-components/building-blocks#apg-method-badge): `method` - [`<apg-overview>`](/docs/reference/doc-components/openapi#apg-overview): `overview`, `title`, `version`, `info`, `link` - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` - [`<apg-servers>`](/docs/reference/doc-components/openapi#apg-servers): `servers`, `label`, `select`, `input`, `url` - [`<apg-auth>`](/docs/reference/doc-components/openapi#apg-auth): `auth`, `scheme`, `scheme-name`, `status`, `button`, `button-primary` - [`<apg-operation>`](/docs/reference/doc-components/openapi#apg-operation): `operation`, `header`, `path`, `summary`, `section`, `table`, `parameter-name`, `type`, `required`, `tab`, `tab-active`, `badge`, `tag-link`, `response`, `response-status`, `try-it-button` - [`<apg-schema>`](/docs/reference/doc-components/openapi#apg-schema): `schema`, `schema-row`, `property-name`, `toggle`, `ref-link`, `format-link`, `constraint` - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` - [`<apg-try-it>`](/docs/reference/doc-components/openapi#apg-try-it): `try-it`, `textarea`, `cors` - [`<apg-code-samples>`](/docs/reference/doc-components/openapi#apg-code-samples): `code-samples` - [`<apg-swagger-hosts>`](/docs/reference/doc-components/swagger#apg-swagger-hosts): `hosts` - [`<apg-swagger-security>`](/docs/reference/doc-components/swagger#apg-swagger-security): `security` - [`<apg-swagger-operation>`](/docs/reference/doc-components/swagger#apg-swagger-operation): `media-types` - [`<apg-asyncapi-servers>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-servers): `server`, `server-name`, `protocol` - [`<apg-asyncapi-bindings>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-bindings): `bindings`, `binding`, `binding-protocol` - [`<apg-asyncapi-channel>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-channel): `channel` - [`<apg-asyncapi-message>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-message): `message`, `content-type` - [`<apg-protobuf-overview>`](/docs/reference/doc-components/protobuf#apg-protobuf-overview): `options` - [`<apg-protobuf-service>`](/docs/reference/doc-components/protobuf#apg-protobuf-service): `service`, `full-name` - [`<apg-protobuf-method>`](/docs/reference/doc-components/protobuf#apg-protobuf-method): `grpc-path`, `http-rules` - [`<apg-protobuf-message>`](/docs/reference/doc-components/protobuf#apg-protobuf-message): `fields`, `field` - [`<apg-protobuf-enum>`](/docs/reference/doc-components/protobuf#apg-protobuf-enum): `enum`, `values`, `value` - [`<apg-graphql-overview>`](/docs/reference/doc-components/graphql#apg-graphql-overview): `roots` - [`<apg-graphql-operation>`](/docs/reference/doc-components/graphql#apg-graphql-operation): `coordinate`, `arguments`, `argument` - [`<apg-graphql-type>`](/docs/reference/doc-components/graphql#apg-graphql-type): `kind` - [`<apg-graphql-try-it>`](/docs/reference/doc-components/graphql#apg-graphql-try-it): `graphql-errors` - [`<apg-graphql-directive>`](/docs/reference/doc-components/graphql#apg-graphql-directive): `directive`, `locations` - [`<apg-changelog>`](/docs/reference/doc-components/reference-and-spec#apg-changelog): `changelog`, `entry`, `revision`, `item`, `item-link`, `history` ### CSS custom properties | Property | Description | | --- | --- | | `--apg-sidebar-width` | Width of the sidebar. | | `--apg-content-width` | Maximum width of the content. | | `--apg-sticky-top` | Offset of the sticky sidebar (height of a fixed page header). | ## `<apg-spec>` Loads an API document (OpenAPI, Swagger 2.0, AsyncAPI, Protobuf or GraphQL) and shares it with the elements inside it, which then need no `spec-url` of their own. It renders nothing but its content. The document comes from `spec-url`, the `spec` property or a child `<script type="application/yaml" data-spec>…</script>` (for a CMS). The Try-it-out settings (`proxy-url`, `credentials`, `persist-auth`, `authConfig`, …) apply to every element inside. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-spec";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `proxy-url` | `proxyUrl` | `string` | | CORS proxy: `https://proxy.example/?url={url}`, or a prefix the request URL is appended to. | | `credentials` | `credentials` | `RequestCredentials` | `"same-origin"` | Credentials mode of Try-it-out requests: `omit`, `same-origin` or `include`. | | `timeout` | `timeout` | `number` | `30000` | Try-it-out timeout in milliseconds. | | `max-response-bytes` | `maxResponseBytes` | `number` | `5242880` | Response bodies larger than this many bytes (5 MiB) are truncated. | | `persist-auth` | `persistAuth` | `PersistMode` | | Keep credentials across page loads: `session` or `local` storage (default: memory only). | | `oauth2-redirect-url` | `oauth2RedirectUrl` | `string` | | Redirect page registered with the OAuth 2.0 authorization server. | | `oauth2-client-id` | `oauth2ClientId` | `string` | | OAuth 2.0 client ID used by every OAuth 2.0 / OpenID Connect scheme without its own `authConfig`. | | `schema-depth` | `schemaDepth` | `number` | `6` | Levels of referenced schemas expanded inline. | | `asyncapi-wasm-url` | `asyncapiWasmUrl` | `string` | | URL of the asyncapi WebAssembly module (`asyncapi.web.mjs`, with `asyncapi.web.wasm` next to it), which reads AsyncAPI documents; loaded when one is shown. | | `protobuf-wasm-url` | `protobufWasmUrl` | `string` | | URL of the protobuf WebAssembly module (`protobuf.web.mjs`, with `protobuf.web.wasm` next to it), which reads .proto documents; loaded when one is shown. | | `graphql-wasm-url` | `graphqlWasmUrl` | `string` | | URL of the graphql WebAssembly module (`graphql.web.mjs`, with `graphql.web.wasm` next to it), which reads GraphQL schemas; loaded when one is shown. | | `graphql-endpoint` | `graphqlEndpoint` | `string` | | The URL GraphQL operations are sent to (default: `/graphql` on the origin of the document). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Properties | Property | Type | Description | | --- | --- | --- | | `authConfig` | `Record<string, OAuthClientConfig>` | OAuth 2.0 client settings per security scheme. | | `fetch` | `typeof fetch` | `fetch` used by Try it out (for example to add tracing). | | `requestInterceptor` | `ApiSettings["requestInterceptor"]` | Called with every Try-it-out request before it is sent. | | `responseInterceptor` | `ApiSettings["responseInterceptor"]` | Called with every Try-it-out response. | | `parserEngine` | `ParserEngine` | Parser of documents given as text (default: the JavaScript parser). | | `asyncapiEngine` | `AsyncApiEngine` | Reads AsyncAPI documents (instead of `asyncapi-wasm-url`). | | `protobufEngine` | `ProtobufEngine` | Reads .proto documents (instead of `protobuf-wasm-url`). | | `graphqlEngine` | `GraphQLEngine` | Reads GraphQL schemas (instead of `graphql-wasm-url`). | ### Events | Event | Description | | --- | --- | | `apg-spec-load` | The document was parsed. | | `apg-spec-error` | The document could not be loaded or parsed. | ### Slots | Slot | Description | | --- | --- | | (default) | Components and any other content. | ## `<apg-nav>` Navigation: operations grouped by tag, webhooks and schemas, with search. For AsyncAPI documents: operations, channels, messages and schemas. For Protobuf files: services with their methods, messages and enums. A document of a docs bundle with a changelog gets a Changelog item. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-nav";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `filter` | `filter` | `string` | `""` | Initial search text. | | `hide-search` | `hideSearch` | `boolean` | `false` | Hides the search input. | | `hide-schemas` | `hideSchemas` | `boolean` | `false` | Leaves the schemas out of the navigation. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Properties | Property | Type | Description | | --- | --- | --- | | `route` | `Route` | The page shown, highlighted in the list. | ### Events | Event | Description | | --- | --- | | `apg-navigate` | A link was followed; cancelable. | ### CSS parts | Part | Description | | --- | --- | | `nav` | The `<nav>` element. | | `search` | The search input. | | `nav-group` | A group (tag, webhooks, schemas). | | `nav-group-title` | A group's title link or label. | | `nav-item` | A link; the current page's link also has `nav-item-active`. | | `nav-item-active` | The current page's link. | Forwarded from the elements inside it: - [`<apg-method-badge>`](/docs/reference/doc-components/building-blocks#apg-method-badge): `method` ## `<apg-changelog>` The git changelog of a document, as `apigenie-generator docs --changelog` writes it into the docs bundle (`changelog.json`): by revision (newest first; what each release or commit added, removed, deprecated or changed, with a badge for breaking changes), or the history of each operation (`view="items"`). Items link to their pages when the document has them. The changelog comes from the `changelog` property, or from the docs bundle of the enclosing `<apg-api-reference>`. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-changelog";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `view` | `view` | `"revisions" \| "items"` | `"revisions"` | `revisions` (newest first) or `items` (the history of each operation or method). | | `heading-level` | `headingLevel` | `"1" \| "2" \| "3"` | `"2"` | Level of the title heading. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Properties | Property | Type | Description | | --- | --- | --- | | `changelog` | `ChangelogFile` | The changelog; by default the one of the docs bundle of the enclosing reference. | ### CSS parts | Part | Description | | --- | --- | | `changelog` | The root element. | | `page-title` | The heading of the changelog. | | `entry` | One revision. | | `revision` | The heading of a revision. | | `badge` | A severity or change badge. | | `section-title` | The title of a section of a revision (Operations, Channels, ...). | | `item` | One changed item. | | `item-link` | The link of an item to its page. | | `history` | The history of one item (`view="items"`). | --- # OpenAPI elements Source: https://apigenie.pl/docs/reference/doc-components/openapi Part of the reference of [@mykulyak/apigenie-docs](https://apigenie.pl/docs/reference/doc-components.md). Its other pages: [apg-api-reference and apg-spec](https://apigenie.pl/docs/reference/doc-components/reference-and-spec.md), [Swagger 2.0 elements](https://apigenie.pl/docs/reference/doc-components/swagger.md), [AsyncAPI elements](https://apigenie.pl/docs/reference/doc-components/asyncapi.md), [Protobuf and gRPC elements](https://apigenie.pl/docs/reference/doc-components/protobuf.md), [GraphQL elements](https://apigenie.pl/docs/reference/doc-components/graphql.md), [Building blocks](https://apigenie.pl/docs/reference/doc-components/building-blocks.md), [Try it out](https://apigenie.pl/docs/reference/doc-components/try-it-out.md), [Theming](https://apigenie.pl/docs/reference/doc-components/theming.md), [Server-side rendering](https://apigenie.pl/docs/reference/doc-components/server-side-rendering.md), [apigenie-docs build](https://apigenie.pl/docs/reference/doc-components/docs-build.md). The elements of OpenAPI 3.0 and 3.1 documents. `<apg-nav>`, `<apg-schema>`, `<apg-try-it>`, `<apg-auth>`, `<apg-servers>` and `<apg-code-samples>` show Swagger 2.0 documents as well; [Swagger 2.0 elements](/docs/reference/doc-components/swagger) lists the elements of their own. Operations are selected with `operation-id`, or with `method` and `path`; schemas with `name` (in `components.schemas`) or `pointer`. ## `<apg-overview>` Title, version, description, contact, license and external documentation of the API. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-overview";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `heading-level` | `headingLevel` | `number` | `1` | Level of the title heading (1–6). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `overview` | The container. | | `title` | The API title (`h1` unless `heading-level` says otherwise). | | `version` | Version badges. | | `info` | Contact, license and terms line. | | `link` | Links in the info line. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` ## `<apg-operation>` Documentation of one operation: parameters, request body, responses (with examples and schemas), security and callbacks, with an optional embedded Try it out. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-operation";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `operation-id` | `operationId` | `string` | | The operation, by `operationId`. | | `method` | `method` | `string` | | The operation by method and path (alternative to `operation-id`). | | `path` | `path` | `string` | | The path of the operation, with `method`. | | `pointer` | `pointer` | `string` | | The operation by JSON pointer. | | `try-it` | `tryIt` | `"inline" \| "open" \| "none"` | `"inline"` | `inline`: a button shows Try it out; `open`: shown from the start; `none`: hidden. | | `heading-level` | `headingLevel` | `number` | `2` | Level of the path heading. | | `lazy` | `lazy` | `boolean` | `false` | Render only the header until the operation comes near the viewport (used for long pages; the full content is always rendered on the server). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Methods | Method | Description | | --- | --- | | `reveal()` | Renders the full content of a lazy operation. | ### Events | Event | Description | | --- | --- | | `apg-navigate` | A tag link was followed; cancelable. | ### Slots | Slot | Description | | --- | --- | | `before` | Content shown after the header. | | `after` | Content shown at the end. | ### CSS parts | Part | Description | | --- | --- | | `operation` | The container. | | `header` | The header with method, path and summary. | | `path` | The path. | | `summary` | The summary line. | | `section` | Sections (parameters, body, responses). | | `section-title` | Section headings. | | `table` | Tables. | | `parameter-name` | Parameter names. | | `type` | Type labels of parameters and headers. | | `required` | Required markers. | | `select` | The media type and example choices. | | `tab` | Example and schema tabs; the selected one also has `tab-active`. | | `tab-active` | The selected tab. | | `badge` | Badges (deprecated, webhook). | | `tag-link` | Links to tag pages. | | `response` | One response. | | `response-status` | Its status code. | | `try-it-button` | The button that shows Try it out. | Forwarded from the elements inside it: - [`<apg-method-badge>`](/docs/reference/doc-components/building-blocks#apg-method-badge): `method` - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` - [`<apg-schema>`](/docs/reference/doc-components/openapi#apg-schema): `schema`, `schema-row`, `property-name`, `toggle`, `ref-link`, `format-link`, `constraint` - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` - [`<apg-try-it>`](/docs/reference/doc-components/openapi#apg-try-it): `try-it`, `label`, `input`, `textarea`, `button`, `button-primary`, `url`, `problems`, `cors` - [`<apg-servers>`](/docs/reference/doc-components/openapi#apg-servers): `servers` - [`<apg-auth>`](/docs/reference/doc-components/openapi#apg-auth): `auth`, `scheme`, `scheme-name`, `status` - [`<apg-code-samples>`](/docs/reference/doc-components/openapi#apg-code-samples): `code-samples` ## `<apg-schema>` Schema as an expandable tree: properties, items, combinators, constraints, enums, defaults and examples. Referenced schemas beyond the inline depth and recursive references expand on click. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-schema";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `name` | `name` | `string` | | Name of a schema in `components.schemas`. | | `pointer` | `pointer` | `string` | | JSON pointer of the schema (alternative to `name`). | | `depth` | `depth` | `number` | `1` | Levels of properties shown initially (1: the schema's own properties). | | `with-example` | `withExample` | `boolean` | `false` | Show Schema / Example tabs with an example generated from the schema. | | `hide-description` | `hideDescription` | `boolean` | `false` | Hide the root description (when the surrounding page shows it). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Properties | Property | Type | Description | | --- | --- | --- | | `node` | `SchemaNode` | A schema view model to render directly (used by `<apg-operation>`). | ### Events | Event | Description | | --- | --- | | `apg-navigate` | A schema link was followed; cancelable. | ### CSS parts | Part | Description | | --- | --- | | `schema` | The tree. | | `schema-row` | One property line. | | `property-name` | Property name. | | `type` | Type label. | | `required` | Required marker. | | `toggle` | Expand/collapse button. | | `ref-link` | Link to a component schema's page. | | `format-link` | Link to the specification of a `format`. | | `constraint` | Constraint or fact (enum, default, pattern, …). | | `tab` | Schema and example tabs (`with-example`); the selected one also has `tab-active`. | | `tab-active` | The selected tab. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` ## `<apg-try-it>` Sends requests to the API: parameters, request body (text, forms, file uploads), server and credentials, with a live URL preview, code samples and a response viewer that streams server-sent events and NDJSON. Events: `apg-request` (cancelable; `detail.request` may be replaced) before sending and `apg-response` afterwards. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-try-it";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `operation-id` | `operationId` | `string` | | The operation, by `operationId`. | | `method` | `method` | `string` | | The operation by method and path (alternative to `operation-id`). | | `path` | `path` | `string` | | The path of the operation, with `method`. | | `pointer` | `pointer` | `string` | | The operation by JSON pointer (used by `<apg-operation>`). | | `hide-samples` | `hideSamples` | `boolean` | `false` | Hide the code samples. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Events | Event | Description | | --- | --- | | `apg-request` | Before a request is sent; cancelable, `detail.request` may be replaced. | | `apg-response` | After a response (or failure). | ### CSS parts | Part | Description | | --- | --- | | `try-it` | The container. | | `section-title` | Headings of the form's sections. | | `label` | Field labels. | | `input` | Text inputs. | | `select` | Selects. | | `textarea` | Body and JSON editors. | | `button` | Secondary buttons. | | `button-primary` | The Send button. | | `url` | The request URL. | | `problems` | Problems that block or affect the request. | | `response` | The response viewer. | | `response-status` | The response status code. | | `cors` | What a cross-origin request needs from the server, when it failed before a response. | | `tab` | Response tabs; the selected one also has `tab-active`. | | `tab-active` | The selected tab. | Forwarded from the elements inside it: - [`<apg-method-badge>`](/docs/reference/doc-components/building-blocks#apg-method-badge): `method` - [`<apg-servers>`](/docs/reference/doc-components/openapi#apg-servers): `servers` - [`<apg-auth>`](/docs/reference/doc-components/openapi#apg-auth): `auth`, `scheme`, `scheme-name`, `status` - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` - [`<apg-code-samples>`](/docs/reference/doc-components/openapi#apg-code-samples): `code-samples` - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` ## `<apg-auth>` Credentials for the API's security schemes: API keys, HTTP Basic and Bearer, OAuth 2.0 flows (authorization code with PKCE, client credentials, implicit, password) and OpenID Connect discovery. A token can always be pasted instead of running a flow. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-auth";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `schemes` | `schemes` | `string` | | Comma-separated scheme names to show; all schemes by default. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Events | Event | Description | | --- | --- | | `apg-auth-change` | Credentials of a scheme were set or cleared. | ### CSS parts | Part | Description | | --- | --- | | `auth` | The container. | | `scheme` | One security scheme. | | `scheme-name` | The scheme's name. | | `status` | Authorized / not authorized. | | `label` | Field labels. | | `input` | Inputs. | | `select` | Flow selection. | | `button` | Secondary buttons. | | `button-primary` | Authorize buttons. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` ## `<apg-servers>` Chooses the server Try it out sends requests to: a declared server with its variables, or a custom URL. The choice is shared by every component showing the same API. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-servers";`. ### Attributes Only `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `servers` | The container. | | `label` | Field labels. | | `select` | The server list and enumerated variables. | | `input` | Variable and custom URL inputs. | | `url` | The resolved server URL. | ## `<apg-code-samples>` Code samples for a request: curl, JavaScript (fetch) and Python (requests). Shows the request of an operation's Try-it-out form (credentials masked), or `request` when set. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-code-samples";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `operation-id` | `operationId` | `string` | | Operation whose Try-it-out request is shown (by `operationId`). | | `method` | `method` | `string` | | Operation by method and path (alternative to `operation-id`). | | `path` | `path` | `string` | | The path of the operation, with `method`. | | `languages` | `languages` | `string` | `"curl,javascript,python"` | Comma-separated languages: `curl`, `javascript`, `python`. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Properties | Property | Type | Description | | --- | --- | --- | | `request` | `BuiltRequest` | A request to show instead of an operation's. | ### CSS parts | Part | Description | | --- | --- | | `code-samples` | The container. | | `tab` | Language tabs; the selected one also has `tab-active`. | | `tab-active` | The selected tab. | Forwarded from the elements inside it: - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` --- # Swagger 2.0 elements Source: https://apigenie.pl/docs/reference/doc-components/swagger Part of the reference of [@mykulyak/apigenie-docs](https://apigenie.pl/docs/reference/doc-components.md). Its other pages: [apg-api-reference and apg-spec](https://apigenie.pl/docs/reference/doc-components/reference-and-spec.md), [OpenAPI elements](https://apigenie.pl/docs/reference/doc-components/openapi.md), [AsyncAPI elements](https://apigenie.pl/docs/reference/doc-components/asyncapi.md), [Protobuf and gRPC elements](https://apigenie.pl/docs/reference/doc-components/protobuf.md), [GraphQL elements](https://apigenie.pl/docs/reference/doc-components/graphql.md), [Building blocks](https://apigenie.pl/docs/reference/doc-components/building-blocks.md), [Try it out](https://apigenie.pl/docs/reference/doc-components/try-it-out.md), [Theming](https://apigenie.pl/docs/reference/doc-components/theming.md), [Server-side rendering](https://apigenie.pl/docs/reference/doc-components/server-side-rendering.md), [apigenie-docs build](https://apigenie.pl/docs/reference/doc-components/docs-build.md). Swagger 2.0 documents have their own elements for the overview, the hosts, the security definitions and the operations. `<apg-api-reference>` picks them by itself. `<apg-nav>`, `<apg-schema>`, `<apg-try-it>`, `<apg-auth>`, `<apg-servers>` and `<apg-code-samples>` work with both kinds of document ([OpenAPI elements](/docs/reference/doc-components/openapi)), and the schemas of a Swagger 2.0 document are called definitions. ## `<apg-swagger-overview>` Title, version, description, contact, license and external documentation of a Swagger 2.0 API. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-swagger-overview";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `heading-level` | `headingLevel` | `number` | `1` | Level of the title heading (1–6). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `overview` | The container. | | `title` | The API title (`h1` unless `heading-level` says otherwise). | | `version` | Version badges. | | `info` | Contact, license and terms line. | | `link` | Links in the info line. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` ## `<apg-swagger-hosts>` Where a Swagger 2.0 API is served: `host`, `basePath` and `schemes`, the resulting base URLs, and the media types the API consumes and produces. With `with-picker`, also the server choice Try it out sends requests to (an embedded `<apg-servers>`). Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-swagger-hosts";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `with-picker` | `withPicker` | `boolean` | `false` | Also show the server choice of Try it out. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `hosts` | The container. | | `label` | Field labels. | | `url` | Base URLs. | Forwarded from the elements inside it: - [`<apg-servers>`](/docs/reference/doc-components/openapi#apg-servers): `servers`, `select`, `input` ## `<apg-swagger-security>` The security definitions of a Swagger 2.0 document: type, where API keys go, OAuth 2.0 flow, URLs and scopes, and the requirements that apply to every operation. Credentials are entered in `<apg-auth>`. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-swagger-security";`. ### Attributes Only `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `security` | The container. | | `scheme` | One security definition. | | `scheme-name` | Its name. | | `table` | Scope tables. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` ## `<apg-swagger-operation>` Documentation of one operation of a Swagger 2.0 document: the media types it consumes and produces, path, query, header and form parameters, the body parameter, responses with their headers, examples and schemas, and security, with an optional embedded Try it out. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-swagger-operation";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `operation-id` | `operationId` | `string` | | The operation, by `operationId`. | | `method` | `method` | `string` | | The operation by method and path (alternative to `operation-id`). | | `path` | `path` | `string` | | The path of the operation, with `method`. | | `pointer` | `pointer` | `string` | | The operation by JSON pointer. | | `try-it` | `tryIt` | `"inline" \| "open" \| "none"` | `"inline"` | `inline`: a button shows Try it out; `open`: shown from the start; `none`: hidden. | | `heading-level` | `headingLevel` | `number` | `2` | Level of the path heading. | | `lazy` | `lazy` | `boolean` | `false` | Render only the header until the operation comes near the viewport (used for long pages; the full content is always rendered on the server). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Methods | Method | Description | | --- | --- | | `reveal()` | Renders the full content of a lazy operation. | ### Events | Event | Description | | --- | --- | | `apg-navigate` | A tag link was followed; cancelable. | ### Slots | Slot | Description | | --- | --- | | `before` | Content shown after the header. | | `after` | Content shown at the end. | ### CSS parts | Part | Description | | --- | --- | | `operation` | The container. | | `header` | The header with method, path and summary. | | `path` | The path. | | `summary` | The summary line. | | `section` | Sections (parameters, body, responses). | | `section-title` | Section headings. | | `table` | Tables. | | `parameter-name` | Parameter names. | | `type` | Type labels of parameters and headers. | | `required` | Required markers. | | `select` | The media type choice of a response. | | `tab` | Example and schema tabs; the selected one also has `tab-active`. | | `tab-active` | The selected tab. | | `badge` | Badges (deprecated). | | `tag-link` | Links to tag pages. | | `media-types` | The consumes and produces line. | | `response` | One response. | | `response-status` | Its status code. | | `try-it-button` | The button that shows Try it out. | Forwarded from the elements inside it: - [`<apg-method-badge>`](/docs/reference/doc-components/building-blocks#apg-method-badge): `method` - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` - [`<apg-schema>`](/docs/reference/doc-components/openapi#apg-schema): `schema`, `schema-row`, `property-name`, `toggle`, `ref-link`, `format-link`, `constraint` - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` - [`<apg-try-it>`](/docs/reference/doc-components/openapi#apg-try-it): `try-it`, `label`, `input`, `textarea`, `button`, `button-primary`, `url`, `problems`, `cors` - [`<apg-servers>`](/docs/reference/doc-components/openapi#apg-servers): `servers` - [`<apg-auth>`](/docs/reference/doc-components/openapi#apg-auth): `auth`, `scheme`, `scheme-name`, `status` - [`<apg-code-samples>`](/docs/reference/doc-components/openapi#apg-code-samples): `code-samples` --- # AsyncAPI elements Source: https://apigenie.pl/docs/reference/doc-components/asyncapi Part of the reference of [@mykulyak/apigenie-docs](https://apigenie.pl/docs/reference/doc-components.md). Its other pages: [apg-api-reference and apg-spec](https://apigenie.pl/docs/reference/doc-components/reference-and-spec.md), [OpenAPI elements](https://apigenie.pl/docs/reference/doc-components/openapi.md), [Swagger 2.0 elements](https://apigenie.pl/docs/reference/doc-components/swagger.md), [Protobuf and gRPC elements](https://apigenie.pl/docs/reference/doc-components/protobuf.md), [GraphQL elements](https://apigenie.pl/docs/reference/doc-components/graphql.md), [Building blocks](https://apigenie.pl/docs/reference/doc-components/building-blocks.md), [Try it out](https://apigenie.pl/docs/reference/doc-components/try-it-out.md), [Theming](https://apigenie.pl/docs/reference/doc-components/theming.md), [Server-side rendering](https://apigenie.pl/docs/reference/doc-components/server-side-rendering.md), [apigenie-docs build](https://apigenie.pl/docs/reference/doc-components/docs-build.md). The elements of AsyncAPI 3.0 and 3.1 documents. `<apg-api-reference>` picks them by itself, and `<apg-nav>`, `<apg-schema>` and the [building blocks](/docs/reference/doc-components/building-blocks) serve AsyncAPI documents as well. AsyncAPI documents, as text or as values, are read by the asyncapi WebAssembly module (`asyncapi.web.mjs` and `asyncapi.web.wasm`): give its URL with `asyncapi-wasm-url` on `<apg-spec>` or `<apg-api-reference>`, or to every element with `configureAsyncApiEngine(url)`. The module follows references, applies traits and the specification's defaults, and reports problems, which are listed with their positions. Without the module, AsyncAPI documents fail to load. The documentation model (`{"apigenieAsyncAPI": 1, …}`) can be given instead and needs no module. ```html <apg-spec spec-url="/asyncapi.yaml" asyncapi-wasm-url="/wasm/asyncapi.web.mjs"> <apg-asyncapi-overview></apg-asyncapi-overview> <apg-asyncapi-operation name="receiveLightMeasurement"></apg-asyncapi-operation> <apg-asyncapi-message name="lightMeasured"></apg-asyncapi-message> </apg-spec> ``` Operations, channels and messages are selected with `name` (messages by their name in `components.messages`) or `pointer`. ## `<apg-asyncapi-overview>` Title, version, description, contact, license, tags and external documentation of an AsyncAPI 3 document, with its `id` and default content type. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-asyncapi-overview";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `heading-level` | `headingLevel` | `number` | `1` | Level of the title heading (1–6). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `overview` | The container. | | `title` | The API title (`h1` unless `heading-level` says otherwise). | | `version` | Version badges. | | `info` | Contact, license and terms line. | | `link` | Links in the info line. | | `badge` | Tag chips. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` ## `<apg-asyncapi-servers>` The servers of an AsyncAPI document (or the one named by `server`): protocol, URL, variables, security, the channels available on it and its bindings. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-asyncapi-servers";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `server` | `server` | `string` | | Show only this server (its key). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `servers` | The container. | | `server` | One server. | | `server-name` | Its key. | | `protocol` | The protocol and its version. | | `url` | The URL. | | `label` | Field labels. | | `table` | The variables table. | | `channel-link` | Links to the channels on the server. | | `badge` | Tag chips. | | `link` | External documentation links. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` - [`<apg-asyncapi-bindings>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-bindings): `bindings`, `binding`, `binding-protocol` - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` ## `<apg-asyncapi-security>` The security schemes of an AsyncAPI document (`components.securitySchemes`): type, what it asks for, where API keys go, OAuth 2.0 flows with their URLs and scopes, OpenID Connect discovery. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-asyncapi-security";`. ### Attributes Only `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `security` | The container. | | `scheme` | One security scheme. | | `scheme-name` | Its name. | | `table` | Flow tables. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` ## `<apg-asyncapi-operation>` One operation of an AsyncAPI document: its action (send or receive), channel and address, the messages with their headers, payloads and examples, the reply of request/reply operations, security, traits and bindings. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-asyncapi-operation";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `pointer` | `pointer` | `string` | | The operation by id (`#/operations/<key>`). | | `name` | `name` | `string` | | The operation by key. | | `heading-level` | `headingLevel` | `number` | `2` | Level of the title heading. | | `lazy` | `lazy` | `boolean` | `false` | Render only the header until the operation comes near the viewport (used for long pages; the full content is always rendered on the server). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Methods | Method | Description | | --- | --- | | `reveal()` | Renders the full content of a lazy operation. | ### CSS parts | Part | Description | | --- | --- | | `operation` | The container. | | `header` | The header with the action, title and summary. | | `title` | The title (the operation's title, else its key). | | `summary` | The summary line. | | `address` | The channel's address. | | `badge` | Tag chips. | | `section` | Sections (messages, reply, security). | | `section-title` | Section headings. | | `channel-link` | Links to channels. | | `link` | External documentation links. | Forwarded from the elements inside it: - [`<apg-method-badge>`](/docs/reference/doc-components/building-blocks#apg-method-badge): `method` - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` - [`<apg-asyncapi-message>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-message): `message`, `content-type`, `select`, `operation-link` - [`<apg-schema>`](/docs/reference/doc-components/openapi#apg-schema): `schema`, `schema-row`, `property-name`, `type`, `required`, `toggle`, `ref-link`, `format-link`, `constraint`, `tab`, `tab-active` - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` - [`<apg-asyncapi-bindings>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-bindings): `bindings`, `binding`, `binding-protocol`, `table` ## `<apg-asyncapi-channel>` One channel of an AsyncAPI document: its address with parameters, the servers it is on, its messages, the operations on it, and its bindings. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-asyncapi-channel";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `pointer` | `pointer` | `string` | | The channel by id (`#/channels/<key>`). | | `name` | `name` | `string` | | The channel by key. | | `heading-level` | `headingLevel` | `number` | `2` | Level of the title heading. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `channel` | The container. | | `header` | The header. | | `title` | The title (the channel's title, else its key). | | `address` | The address. | | `summary` | The summary line. | | `badge` | Tag chips. | | `section` | Sections. | | `section-title` | Section headings. | | `table` | The parameters table. | | `parameter-name` | Parameter names. | | `message-link` | Links to messages. | | `operation-link` | Links to operations. | | `link` | External documentation links. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` - [`<apg-method-badge>`](/docs/reference/doc-components/building-blocks#apg-method-badge): `method` - [`<apg-asyncapi-bindings>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-bindings): `bindings`, `binding`, `binding-protocol` - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` ## `<apg-asyncapi-message>` One message of an AsyncAPI document: content type, headers and payload (schema trees, or the schema as written for formats such as Avro and Protobuf), examples, correlation ID, bindings, and the channels and operations using it. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-asyncapi-message";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `pointer` | `pointer` | `string` | | The message by pointer (`#/components/messages/lightMeasured`, or a channel's own message). | | `name` | `name` | `string` | | The message by its key in `components.messages`. | | `heading-level` | `headingLevel` | `number` | `2` | Level of the title heading. | | `embedded` | `embedded` | `boolean` | `false` | Shown inside an operation: framed, without the channels and operations using it. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `message` | The container. | | `header` | The header with the title and badges. | | `title` | The title. | | `summary` | The summary line. | | `badge` | Badges (deprecated, schema format) and tag chips. | | `content-type` | The content type. | | `section` | Sections (headers, payload, examples…). | | `section-title` | Section headings. | | `select` | The example picker. | | `channel-link` | Links to channels. | | `operation-link` | Links to operations. | | `link` | External documentation links. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` - [`<apg-schema>`](/docs/reference/doc-components/openapi#apg-schema): `schema`, `schema-row`, `property-name`, `type`, `required`, `toggle`, `ref-link`, `format-link`, `constraint`, `tab`, `tab-active` - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` - [`<apg-asyncapi-bindings>`](/docs/reference/doc-components/asyncapi#apg-asyncapi-bindings): `bindings`, `binding`, `binding-protocol`, `table` - [`<apg-method-badge>`](/docs/reference/doc-components/building-blocks#apg-method-badge): `method` ## `<apg-asyncapi-bindings>` The protocol bindings of an AsyncAPI server, channel, operation or message, given as the `bindings` of their view: one block per protocol with its `bindingVersion` and fields. Plain values are shown inline, objects (schemas, topic configuration) as JSON. Nothing is shown when there are no bindings. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-asyncapi-bindings";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `open` | `open` | `boolean` | `false` | Start expanded. | ### Properties | Property | Type | Description | | --- | --- | --- | | `bindings` | `BindingView[]` | The bindings, from an AsyncAPI view (`server.bindings`, `channel.bindings`…). | ### CSS parts | Part | Description | | --- | --- | | `bindings` | The collapsible container. | | `binding` | The bindings of one protocol. | | `binding-protocol` | The protocol's name. | | `table` | The fields. | Forwarded from the elements inside it: - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` --- # Protobuf and gRPC elements Source: https://apigenie.pl/docs/reference/doc-components/protobuf Part of the reference of [@mykulyak/apigenie-docs](https://apigenie.pl/docs/reference/doc-components.md). Its other pages: [apg-api-reference and apg-spec](https://apigenie.pl/docs/reference/doc-components/reference-and-spec.md), [OpenAPI elements](https://apigenie.pl/docs/reference/doc-components/openapi.md), [Swagger 2.0 elements](https://apigenie.pl/docs/reference/doc-components/swagger.md), [AsyncAPI elements](https://apigenie.pl/docs/reference/doc-components/asyncapi.md), [GraphQL elements](https://apigenie.pl/docs/reference/doc-components/graphql.md), [Building blocks](https://apigenie.pl/docs/reference/doc-components/building-blocks.md), [Try it out](https://apigenie.pl/docs/reference/doc-components/try-it-out.md), [Theming](https://apigenie.pl/docs/reference/doc-components/theming.md), [Server-side rendering](https://apigenie.pl/docs/reference/doc-components/server-side-rendering.md), [apigenie-docs build](https://apigenie.pl/docs/reference/doc-components/docs-build.md). The elements of Protobuf files with gRPC services. `<apg-api-reference>` and `<apg-nav>` pick them by themselves. Declarations are named by full name (`acme.library.v1.Book`) or by name relative to the package (`Book.Author`, `LibraryService.GetBook`). `.proto` text is read by the protobuf WebAssembly module (`protobuf.web.mjs` and `protobuf.web.wasm`): give its URL with `protobuf-wasm-url` on `<apg-spec>` or `<apg-api-reference>`, or to every element with `configureProtobufEngine(url)`. One file is documented: imports of the standard files (google/protobuf, google/api, google/rpc, grpc) are resolved, and the types of other imports are shown unresolved. The documentation model the module writes (`{"apigenieProtobuf": 1, …}`) can be given instead of the text and needs no module; server-side rendering embeds it in the page. ```html <apg-spec spec-url="/protos/library.proto" protobuf-wasm-url="/wasm/protobuf.web.mjs"> <apg-protobuf-overview></apg-protobuf-overview> <apg-protobuf-method name="LibraryService.GetBook" target="api.example.com:443"></apg-protobuf-method> <apg-protobuf-message name="Book"></apg-protobuf-message> </apg-spec> ``` ## `<apg-protobuf-overview>` The package, file, syntax, header comment, imports and file options of a Protobuf file. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-protobuf-overview";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `heading-level` | `headingLevel` | `number` | `1` | Level of the title heading (1–6). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `overview` | The container. | | `title` | The package (`h1` unless `heading-level` says otherwise). | | `version` | Badges: the package version and the syntax. | | `info` | The file line. | | `section` | Sections (imports, options). | | `section-title` | Section headings. | | `options` | The list of file options. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` ## `<apg-protobuf-service>` A gRPC service of a Protobuf file: its description, options and methods, each with its streaming kind, request and response. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-protobuf-service";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `name` | `name` | `string` | | The service, by full name (`acme.v1.Library`) or by name (`Library`). | | `heading-level` | `headingLevel` | `number` | `2` | Level of the title heading. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `service` | The container. | | `header` | The header with the name and badges. | | `title` | The name. | | `full-name` | The full name. | | `badge` | Badges (deprecated). | | `section` | Sections (methods, options). | | `section-title` | Section headings. | | `method-link` | Links to the methods. | | `type-link` | Links to message pages. | | `options` | Lists of options. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` - [`<apg-method-badge>`](/docs/reference/doc-components/building-blocks#apg-method-badge): `method` ## `<apg-protobuf-method>` A gRPC method: its streaming kind, HTTP/2 path, request and response messages (with their fields), HTTP/JSON transcoding rules (`google.api.http`), JSON examples of both messages and code samples. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-protobuf-method";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `name` | `name` | `string` | | The method, by full name (`acme.v1.Library.GetBook`) or as `Service.Method`. | | `heading-level` | `headingLevel` | `number` | `2` | Level of the title heading. | | `target` | `target` | `string` | | The server the code samples call, `host:port`. | | `hide-samples` | `hideSamples` | `boolean` | `false` | Hide the code samples. | | `lazy` | `lazy` | `boolean` | `false` | Render only the header until the method comes near the viewport (used for long pages; the full content is always rendered on the server). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Methods | Method | Description | | --- | --- | | `reveal()` | Renders the full content of a lazy method. | ### CSS parts | Part | Description | | --- | --- | | `method` | The container. | | `header` | The header with the name and badges. | | `title` | The name. | | `summary` | The summary line, when the method has no description of its own. | | `grpc-path` | The HTTP/2 path of calls. | | `service-link` | The link to the service. | | `badge` | Badges (deprecated, idempotency). | | `section` | Sections (request, response, HTTP, examples, code samples). | | `section-title` | Section headings. | | `http-rules` | The table of HTTP transcoding rules. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` - [`<apg-protobuf-message>`](/docs/reference/doc-components/protobuf#apg-protobuf-message): `message`, `full-name`, `fields`, `field`, `type-link`, `options`, `method-link` - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` - [`<apg-grpc-code-samples>`](/docs/reference/doc-components/protobuf#apg-grpc-code-samples): `code-samples`, `tab`, `tab-active` ## `<apg-protobuf-message>` A message of a Protobuf file: its fields (number, name and JSON name, type, label, oneof, options, comment), oneofs, reserved numbers and names, nested types, the methods using it and an example in the proto3 JSON form. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-protobuf-message";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `name` | `name` | `string` | | The message, by full name (`acme.v1.Book`) or by name relative to the package (`Book.Author`). | | `heading-level` | `headingLevel` | `number` | `2` | Level of the title heading. | | `embedded` | `embedded` | `boolean` | `false` | Shown inside a method: the table of fields only. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `message` | The container. | | `header` | The header with the name and badges. | | `title` | The name. | | `full-name` | The full name. | | `badge` | Badges (deprecated). | | `section` | Sections (fields, oneofs, nested types…). | | `section-title` | Section headings. | | `fields` | The table of fields. | | `field` | A field's row. | | `type-link` | Links to message and enum pages. | | `options` | Lists of options. | | `method-link` | Links to the methods using the message. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` - [`<apg-method-badge>`](/docs/reference/doc-components/building-blocks#apg-method-badge): `method` ## `<apg-protobuf-enum>` An enum of a Protobuf file: its values (name, number, comment, deprecation), reserved numbers and names, and options. In JSON, values are written by name. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-protobuf-enum";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `name` | `name` | `string` | | The enum, by full name (`acme.v1.Genre`) or by name relative to the package (`Book.Author.Role`). | | `heading-level` | `headingLevel` | `number` | `2` | Level of the title heading. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `enum` | The container. | | `header` | The header with the name and badges. | | `title` | The name. | | `full-name` | The full name. | | `badge` | Badges (deprecated). | | `section` | Sections (values, reserved, options). | | `section-title` | Section headings. | | `values` | The table of values. | | `value` | A value's row. | | `options` | Lists of options. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` ## `<apg-grpc-code-samples>` Code samples calling a gRPC method with its example request: grpcurl, Node.js (`@grpc/grpc-js`), Python (`grpcio`) and Go, in the form each takes for the method's streaming kind. The Python and Go samples use the code protoc generates for the file. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-grpc-code-samples";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `method` | `method` | `string` | | The method, by full name (`acme.v1.Library.GetBook`) or as `Service.Method`. | | `target` | `target` | `string` | | The server the samples call, `host:port` (`localhost:50051` by default). | | `languages` | `languages` | `string` | `"grpcurl,node,python,go"` | Comma-separated languages: `grpcurl`, `node`, `python`, `go`. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `code-samples` | The container. | | `tab` | Language tabs; the selected one also has `tab-active`. | | `tab-active` | The selected tab. | Forwarded from the elements inside it: - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` --- # GraphQL elements Source: https://apigenie.pl/docs/reference/doc-components/graphql Part of the reference of [@mykulyak/apigenie-docs](https://apigenie.pl/docs/reference/doc-components.md). Its other pages: [apg-api-reference and apg-spec](https://apigenie.pl/docs/reference/doc-components/reference-and-spec.md), [OpenAPI elements](https://apigenie.pl/docs/reference/doc-components/openapi.md), [Swagger 2.0 elements](https://apigenie.pl/docs/reference/doc-components/swagger.md), [AsyncAPI elements](https://apigenie.pl/docs/reference/doc-components/asyncapi.md), [Protobuf and gRPC elements](https://apigenie.pl/docs/reference/doc-components/protobuf.md), [Building blocks](https://apigenie.pl/docs/reference/doc-components/building-blocks.md), [Try it out](https://apigenie.pl/docs/reference/doc-components/try-it-out.md), [Theming](https://apigenie.pl/docs/reference/doc-components/theming.md), [Server-side rendering](https://apigenie.pl/docs/reference/doc-components/server-side-rendering.md), [apigenie-docs build](https://apigenie.pl/docs/reference/doc-components/docs-build.md). The elements of GraphQL schemas (SDL). Operations, the fields of the root operation types, are named by schema coordinate (`Query.books`), by kind and field (`mutation.borrow`) or by field (`books`); types and directives by name. GraphQL text is read by the graphql WebAssembly module (`graphql.web.mjs` and `graphql.web.wasm`): give its URL with `graphql-wasm-url` on `<apg-spec>` or `<apg-api-reference>`, or to every element with `configureGraphQLEngine(url)`. Type extensions are merged into their types, rules the schema breaks are listed as problems, and undefined types are shown unresolved. The documentation model (`{"apigenieGraphQL": 1, …}`) can be given instead and needs no module. Operations are sent to `graphql-endpoint`, by default `/graphql` on the origin of the document. The proxy, the interceptors and the `apg-request` and `apg-response` events of [Try it out](/docs/reference/doc-components/try-it-out) apply. ```html <apg-spec spec-url="/schema.graphql" graphql-wasm-url="/wasm/graphql.web.mjs" graphql-endpoint="https://api.example.com/graphql"> <apg-graphql-overview></apg-graphql-overview> <apg-graphql-operation name="Query.books"></apg-graphql-operation> <apg-graphql-type name="Book"></apg-graphql-type> </apg-spec> ``` ## `<apg-graphql-overview>` The description of a GraphQL schema, its file, root operation types, size and schema directives. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-graphql-overview";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `heading-level` | `headingLevel` | `number` | `1` | Level of the title heading (1–6). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `overview` | The container. | | `title` | The title: the heading the schema description starts with, or the file name (`h1` unless `heading-level` says otherwise). | | `info` | The file line. | | `roots` | The root operation types. | | `type-link` | Links to the root types. | | `directive-link` | Links to the definitions of the schema's directives. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` ## `<apg-graphql-operation>` A GraphQL operation, that is a field of a root operation type (`Query.books`): its arguments, the type it returns (with its fields), an example operation with variables and a response, code samples and Try it out. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-graphql-operation";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `name` | `name` | `string` | | The operation: its schema coordinate (`Query.books`), kind and field (`mutation.borrow`) or field (`books`). | | `heading-level` | `headingLevel` | `number` | `2` | Level of the title heading. | | `endpoint` | `endpoint` | `string` | | The endpoint the code samples post to; by default the one of Try it out. | | `hide-samples` | `hideSamples` | `boolean` | `false` | Hide the code samples. | | `hide-try-it` | `hideTryIt` | `boolean` | `false` | Hide Try it out. | | `lazy` | `lazy` | `boolean` | `false` | Render only the header until the operation comes near the viewport (used for long pages; the full content is always rendered on the server). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Methods | Method | Description | | --- | --- | | `reveal()` | Renders the full content of a lazy operation. | ### CSS parts | Part | Description | | --- | --- | | `operation` | The container. | | `header` | The header with the name and badges. | | `title` | The name of the field. | | `coordinate` | The schema coordinate (`Query.books`). | | `summary` | The summary line, when the field has no description of its own. | | `badge` | Badges (deprecated). | | `section` | Sections (arguments, response, example, code samples, try it out). | | `section-title` | Section headings. | | `arguments` | The table of arguments. | | `argument` | An argument's row. | | `type-link` | Links to type pages. | | `directive-link` | Links to directive definitions. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` - [`<apg-method-badge>`](/docs/reference/doc-components/building-blocks#apg-method-badge): `method` - [`<apg-graphql-type>`](/docs/reference/doc-components/graphql#apg-graphql-type): `type`, `kind`, `fields`, `field`, `values`, `operation-link` - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` - [`<apg-graphql-code-samples>`](/docs/reference/doc-components/graphql#apg-graphql-code-samples): `code-samples`, `tab`, `tab-active` - [`<apg-graphql-try-it>`](/docs/reference/doc-components/graphql#apg-graphql-try-it): `try-it`, `label`, `input`, `textarea`, `button`, `button-primary`, `problems`, `response`, `response-status`, `graphql-errors`, `cors` ## `<apg-graphql-type>` A type of a GraphQL schema: object and interface types with their fields (and the fields' arguments), input types with their fields and default values, enums with their values, unions with their members, and scalars; the interfaces a type implements, the types implementing an interface, the unions an object belongs to, where the type is used, and an example value of input types. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-graphql-type";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `name` | `name` | `string` | | The type, by name. | | `heading-level` | `headingLevel` | `number` | `2` | Level of the title heading. | | `embedded` | `embedded` | `boolean` | `false` | Shown inside an operation, whose heading names the type: its fields, values or members only. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `type` | The container. | | `header` | The header with the name and badges. | | `title` | The name. | | `kind` | The kind of the type (`object`, `enum`…). | | `badge` | Badges (root, deprecated). | | `section` | Sections (fields, values, members, used by…). | | `section-title` | Section headings. | | `fields` | The table of fields (or input fields). | | `field` | A field's row. | | `arguments` | Tables of arguments. | | `argument` | An argument's row. | | `values` | The table of enum values. | | `type-link` | Links to type pages. | | `operation-link` | Links to operation pages (fields of root types). | | `directive-link` | Links to directive definitions. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` - [`<apg-method-badge>`](/docs/reference/doc-components/building-blocks#apg-method-badge): `method` ## `<apg-graphql-directive>` A directive definition of a GraphQL schema: its arguments, where it may be used and whether it is repeatable. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-graphql-directive";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `name` | `name` | `string` | | The directive, by name with or without `@`. | | `heading-level` | `headingLevel` | `number` | `2` | Level of the title heading. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `directive` | The container. | | `header` | The header with the name and badges. | | `title` | The name (`@name`). | | `badge` | Badges (repeatable). | | `section` | Sections (arguments, locations). | | `section-title` | Section headings. | | `arguments` | The table of arguments. | | `argument` | An argument's row. | | `type-link` | Links to type pages. | | `locations` | The list of locations. | Forwarded from the elements inside it: - [`<apg-markdown>`](/docs/reference/doc-components/building-blocks#apg-markdown): `markdown` ## `<apg-graphql-code-samples>` Code samples sending a GraphQL operation with its example variables: curl, JavaScript (`fetch`) and Python (`requests`), each posting `{query, variables, operationName}` as JSON. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-graphql-code-samples";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `operation` | `operation` | `string` | | The operation: `Query.books`, `query.books` or `books`. | | `endpoint` | `endpoint` | `string` | | The endpoint the samples post to; by default the one of Try it out. | | `languages` | `languages` | `string` | `"curl,javascript,python"` | Comma-separated languages: `curl`, `javascript`, `python`. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### CSS parts | Part | Description | | --- | --- | | `code-samples` | The container. | | `tab` | Language tabs; the selected one also has `tab-active`. | | `tab-active` | The selected tab. | Forwarded from the elements inside it: - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` ## `<apg-graphql-try-it>` Sends a GraphQL operation to an endpoint: the operation (prefilled with the example), its variables and headers, posted as JSON. The endpoint and headers are shared by every operation of the schema. Subscriptions need a streaming transport and are not sent. Events: `apg-request` (cancelable; `detail.request` may be replaced) before sending and `apg-response` afterwards. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-graphql-try-it";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `operation` | `operation` | `string` | | The operation: `Query.books`, `query.books` or `books`. | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Events | Event | Description | | --- | --- | | `apg-request` | Before a request is sent; cancelable, `detail.request` may be replaced. | | `apg-response` | After a response (or failure). | ### CSS parts | Part | Description | | --- | --- | | `try-it` | The container. | | `section-title` | Headings of the form's sections. | | `label` | Field labels. | | `input` | Text inputs. | | `textarea` | The operation and variables editors. | | `button` | Secondary buttons. | | `button-primary` | The Send button. | | `problems` | Problems that block the request. | | `response` | The response viewer. | | `response-status` | The response status code. | | `graphql-errors` | The `errors` of the response. | | `cors` | What a cross-origin request needs from the server, when it failed before a response. | Forwarded from the elements inside it: - [`<apg-method-badge>`](/docs/reference/doc-components/building-blocks#apg-method-badge): `method` - [`<apg-code-block>`](/docs/reference/doc-components/building-blocks#apg-code-block): `code-block`, `code`, `copy-button` --- # Building blocks Source: https://apigenie.pl/docs/reference/doc-components/building-blocks Part of the reference of [@mykulyak/apigenie-docs](https://apigenie.pl/docs/reference/doc-components.md). Its other pages: [apg-api-reference and apg-spec](https://apigenie.pl/docs/reference/doc-components/reference-and-spec.md), [OpenAPI elements](https://apigenie.pl/docs/reference/doc-components/openapi.md), [Swagger 2.0 elements](https://apigenie.pl/docs/reference/doc-components/swagger.md), [AsyncAPI elements](https://apigenie.pl/docs/reference/doc-components/asyncapi.md), [Protobuf and gRPC elements](https://apigenie.pl/docs/reference/doc-components/protobuf.md), [GraphQL elements](https://apigenie.pl/docs/reference/doc-components/graphql.md), [Try it out](https://apigenie.pl/docs/reference/doc-components/try-it-out.md), [Theming](https://apigenie.pl/docs/reference/doc-components/theming.md), [Server-side rendering](https://apigenie.pl/docs/reference/doc-components/server-side-rendering.md), [apigenie-docs build](https://apigenie.pl/docs/reference/doc-components/docs-build.md). The elements the others are built from, for content of your own next to them: descriptions in Markdown, code with a copy button, and the label of a method or an operation's kind. ## `<apg-markdown>` CommonMark/GFM from the document, sanitized: raw HTML is shown as text, links are limited to http(s)/mailto and open in a new tab, and `#/components/schemas/X` links go to the schema page. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-markdown";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `source` | `source` | `string` | | Markdown text. | | `inline` | `inline` | `boolean` | `false` | Render inline content only (no paragraphs). | And `spec-url`, `spec`, `api` and `theme`, like every element that shows a document: [Where the document comes from](/docs/reference/doc-components#where-the-document-comes-from). ### Events | Event | Description | | --- | --- | | `apg-navigate` | A schema link was followed; cancelable. | ### CSS parts | Part | Description | | --- | --- | | `markdown` | The rendered content. | ## `<apg-code-block>` Code with a copy button. JSON is pretty-printed and highlighted. Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-code-block";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `code` | `code` | `string` | `""` | The code shown. | | `language` | `language` | `"json" \| "auto" \| "text"` | `"auto"` | `json` pretty-prints and highlights; `auto` does so when the code parses as JSON. | | `wrap` | `wrap` | `boolean` | `false` | Wraps long lines instead of scrolling. | | `no-copy` | `noCopy` | `boolean` | `false` | Hides the copy button. | | `copy-label` | `copyLabel` | `string` | `"Copy"` | Label of the copy button (for screen readers and the tooltip). | ### CSS parts | Part | Description | | --- | --- | | `code-block` | The container. | | `code` | The `<pre>` element. | | `copy-button` | The copy button. | ### CSS custom properties | Property | Description | | --- | --- | | `--apg-syntax-key` | Colour of JSON keys (likewise `-string`, `-number`, `-boolean`, `-null`). | ## `<apg-method-badge>` HTTP method label, the action of an AsyncAPI operation (`send`, `receive`), the streaming kind of a gRPC method (`unary`, `server-stream`, `client-stream`, `bidi`), or the kind of a GraphQL operation (`query`, `mutation`, `subscription`). Loaded on its own with `import "@mykulyak/apigenie-docs/components/apg-method-badge";`. ### Attributes | Attribute | Property | Type | Default | Description | | --- | --- | --- | --- | --- | | `method` | `method` | `string` | `"get"` | The method, action, streaming kind or operation kind, such as `get`, `receive`, `bidi` or `query`. | | `compact` | `compact` | `boolean` | `false` | Smaller variant used in navigation lists. | ### CSS parts | Part | Description | | --- | --- | | `method` | The label; it also has the part `method-<name>` (for example `method-get`). | ### CSS custom properties | Property | Description | | --- | --- | | `--apg-method-get` | Colour of GET (likewise `--apg-method-post`, `-put`, `-patch`, `-delete`, `-head`, `-options`, `-trace`). | | `--apg-method-send` | Colour of AsyncAPI `send` operations (likewise `--apg-method-receive`). | | `--apg-method-unary` | Colour of unary gRPC methods (likewise `--apg-method-server-stream`, `-client-stream`, `-bidi`). | | `--apg-method-query` | Colour of GraphQL queries (likewise `--apg-method-mutation`, `-subscription`). | --- # Try it out Source: https://apigenie.pl/docs/reference/doc-components/try-it-out Part of the reference of [@mykulyak/apigenie-docs](https://apigenie.pl/docs/reference/doc-components.md). Its other pages: [apg-api-reference and apg-spec](https://apigenie.pl/docs/reference/doc-components/reference-and-spec.md), [OpenAPI elements](https://apigenie.pl/docs/reference/doc-components/openapi.md), [Swagger 2.0 elements](https://apigenie.pl/docs/reference/doc-components/swagger.md), [AsyncAPI elements](https://apigenie.pl/docs/reference/doc-components/asyncapi.md), [Protobuf and gRPC elements](https://apigenie.pl/docs/reference/doc-components/protobuf.md), [GraphQL elements](https://apigenie.pl/docs/reference/doc-components/graphql.md), [Building blocks](https://apigenie.pl/docs/reference/doc-components/building-blocks.md), [Theming](https://apigenie.pl/docs/reference/doc-components/theming.md), [Server-side rendering](https://apigenie.pl/docs/reference/doc-components/server-side-rendering.md), [apigenie-docs build](https://apigenie.pl/docs/reference/doc-components/docs-build.md). `<apg-try-it>` and the Try it out of `<apg-operation>`, `<apg-swagger-operation>` and `<apg-graphql-try-it>` send requests from the page with `fetch`, so the API must allow the page's origin (CORS). These settings go on `<apg-spec>` or `<apg-api-reference>` and apply to every element inside: | Attribute or property | | | --- | --- | | `proxy-url` | CORS proxy. `{url}` is replaced by the encoded request URL (`https://proxy.example/?url={url}`); otherwise the URL is appended. `dev-server/cors-proxy.ts` in the package's repository is an allowlisting proxy. | | `credentials` | The fetch credentials mode: `omit`, `same-origin` (default) or `include`. | | `timeout`, `max-response-bytes` | 30 s and 5 MB by default. | | `persist-auth` | Keep credentials in `session` or `local` storage (default: memory only). | | `oauth2-client-id`, `oauth2-redirect-url`, `.authConfig` | OAuth 2.0 client settings; `authConfig` maps scheme names to `{ clientId, clientSecret, scopes, redirectUrl, usePkce, additionalParams }`. | | `.fetch`, `.requestInterceptor`, `.responseInterceptor` | Replace `fetch`, or change requests and responses. | | `ApiContext.updateSettings({ proxyHint, redirectWhenPopupBlocked })` | For pages that embed the elements in an application: `proxyHint` says where that page sets its CORS proxy (the hint names `proxy-url` otherwise); `redirectWhenPopupBlocked: false` keeps the page when popups are blocked, and the flow fails with advice to allow them. | ## Bodies JSON and text editors with the document's examples, URL-encoded and multipart forms, and file uploads (file inputs and drag and drop) for multipart fields and binary bodies. ## Responses Status, timing, size and headers. JSON is highlighted, images are previewed and binary bodies can be downloaded. `text/event-stream` (server-sent events) and NDJSON, JSON Lines and JSON text sequences are shown as they arrive, and can be cancelled. ## Authentication API keys, HTTP Basic and Bearer; OAuth 2.0 authorization code with PKCE, client credentials, and the deprecated implicit and password flows, with token refresh; OpenID Connect discovery. A token can always be pasted instead. Authorization runs in a popup, and falls back to redirecting the page when popups are blocked. Serve `oauth2-redirect.html` (in the package's `dist/`) from the documentation's origin and register its URL with the authorization server; the OAuth form shows the URL to register. ## CORS When a request fails before reaching the server, the response panel explains CORS and the proxy option, and says what the server must send for this request: the page's origin in `Access-Control-Allow-Origin`, what makes the browser send a preflight (the method, the headers, `Content-Type`), and whether the browser blocks it as mixed content or asks for private network access. Browsers do not let pages set `Cookie`; through a proxy it is sent as `X-Apg-Cookie`, which the reference proxy turns back into `Cookie`. ## Events The page can inspect, change or cancel every request through the cancelable `apg-request` event (`detail.request` may be replaced); `apg-response` reports the result. Code samples mask credentials. --- # Theming Source: https://apigenie.pl/docs/reference/doc-components/theming Part of the reference of [@mykulyak/apigenie-docs](https://apigenie.pl/docs/reference/doc-components.md). Its other pages: [apg-api-reference and apg-spec](https://apigenie.pl/docs/reference/doc-components/reference-and-spec.md), [OpenAPI elements](https://apigenie.pl/docs/reference/doc-components/openapi.md), [Swagger 2.0 elements](https://apigenie.pl/docs/reference/doc-components/swagger.md), [AsyncAPI elements](https://apigenie.pl/docs/reference/doc-components/asyncapi.md), [Protobuf and gRPC elements](https://apigenie.pl/docs/reference/doc-components/protobuf.md), [GraphQL elements](https://apigenie.pl/docs/reference/doc-components/graphql.md), [Building blocks](https://apigenie.pl/docs/reference/doc-components/building-blocks.md), [Try it out](https://apigenie.pl/docs/reference/doc-components/try-it-out.md), [Server-side rendering](https://apigenie.pl/docs/reference/doc-components/server-side-rendering.md), [apigenie-docs build](https://apigenie.pl/docs/reference/doc-components/docs-build.md). The elements keep their styles in shadow roots, so page CSS does not leak in or out. Two mechanisms change their look: design tokens and CSS parts. Light and dark palettes follow the page's `color-scheme`; `theme="light"` or `theme="dark"` forces one. ## Design tokens Custom properties inherit through shadow roots: set them on the element or on any ancestor. Unset tokens fall back to the built-in light and dark values. ```css apg-api-reference { --apg-color-accent: #b4451f; --apg-font-sans: Georgia, serif; --apg-radius: 2px; --apg-sidebar-width: 300px; } ``` | Tokens | | | --- | --- | | Colours | `--apg-color-bg`, `-surface`, `-surface-2`, `-fg`, `-muted`, `-border`, `-accent`, `-accent-fg`, `-success`, `-warning`, `-danger`, `-info`, `-focus` | | HTTP methods | `--apg-method-get`, `-post`, `-put`, `-patch`, `-delete`, `-head`, `-options`, `-trace` | | AsyncAPI actions | `--apg-method-send`, `-receive` | | gRPC streaming kinds | `--apg-method-unary`, `-server-stream`, `-client-stream`, `-bidi` | | GraphQL operation kinds | `--apg-method-query`, `-mutation`, `-subscription` | | JSON | `--apg-syntax-key`, `-string`, `-number`, `-boolean`, `-null` | | Type | `--apg-font-sans`, `--apg-font-mono`, `--apg-font-size-sm`, `-md`, `-lg` | | Layout | `--apg-radius`, `--apg-space-1` to `-6`, `--apg-sidebar-width`, `--apg-content-width`, `--apg-sticky-top`, `--apg-code-max-height` | ## CSS parts Every element names its inner elements with `part`, and composite elements forward the parts of the elements inside them, so one selector reaches every level: ```css apg-api-reference::part(method) { border-radius: 999px; } apg-api-reference::part(nav-item-active) { background: black; color: white; } apg-api-reference::part(button-primary) { text-transform: uppercase; } ``` Part names are public API. The page of each element lists its parts and the parts it forwards, and the [live examples](/tools/doc-components/examples#theming-title) apply the CSS of two looks to an operation. --- # Server-side rendering Source: https://apigenie.pl/docs/reference/doc-components/server-side-rendering Part of the reference of [@mykulyak/apigenie-docs](https://apigenie.pl/docs/reference/doc-components.md). Its other pages: [apg-api-reference and apg-spec](https://apigenie.pl/docs/reference/doc-components/reference-and-spec.md), [OpenAPI elements](https://apigenie.pl/docs/reference/doc-components/openapi.md), [Swagger 2.0 elements](https://apigenie.pl/docs/reference/doc-components/swagger.md), [AsyncAPI elements](https://apigenie.pl/docs/reference/doc-components/asyncapi.md), [Protobuf and gRPC elements](https://apigenie.pl/docs/reference/doc-components/protobuf.md), [GraphQL elements](https://apigenie.pl/docs/reference/doc-components/graphql.md), [Building blocks](https://apigenie.pl/docs/reference/doc-components/building-blocks.md), [Try it out](https://apigenie.pl/docs/reference/doc-components/try-it-out.md), [Theming](https://apigenie.pl/docs/reference/doc-components/theming.md), [apigenie-docs build](https://apigenie.pl/docs/reference/doc-components/docs-build.md). `@mykulyak/apigenie-docs/ssr` renders the elements in Node with `@lit-labs/ssr` into declarative shadow DOM: the documentation is HTML that search engines index and readers see before any script runs. The `hydrate` entry point then makes it interactive without rendering it again. ```js import { renderApiReference, preloadSpecAsync, pathToRoute, seoMeta, seoHead } from "@mykulyak/apigenie-docs/ssr"; const context = await preloadSpecAsync("/openapi.yaml", yamlText); const html = await renderApiReference({ specUrl: "/openapi.yaml", route: "operation/getPet", routing: "history", basePath: "/docs" }); const head = seoHead(seoMeta(context, pathToRoute("operation/getPet"), "/docs"), "https://example.com"); // The page: <head>${head}</head> // <body>${html}<script type="module" src="…/apigenie-web-components-hydrate.js"></script></body> ``` | Function | | | --- | --- | | `renderApiReference(options)` | Renders `<apg-api-reference>` on the page `route`. With `spec`, it reads that document first; without it, it renders the document preloaded for `specUrl`. It throws when no document is preloaded for `specUrl` or the document cannot be read. | | `preloadSpec(url, document, format?, extras?)` | Reads a document for the elements naming `url` in `spec-url`, and returns its context. OpenAPI and Swagger 2.0 text or values and documentation models are read at once. AsyncAPI documents, `.proto` and GraphQL text are read in the background; preload them with `preloadSpecAsync` before rendering. | | `preloadSpecAsync(url, document, format?, extras?)` | The same, resolving once AsyncAPI documents, `.proto` and GraphQL text are read with the configured module. | | `preloadedSpec(url)` | The context preloaded for `url`, if any. | | `clearSpecRegistry()` | Forgets every preloaded document, between two renders of different sites. | | `renderToString(template, renderInfo?)` | Renders a page of parts after `preloadSpec`, each part naming the document in `spec-url`. | | `routes(context)` | Every page of the reference, for a sitemap; the changelog page included when the context has one. | | `routeToPath(route)`, `pathToRoute(path)` | The path of a page, and the page of a path. | | `seoMeta(context, route, basePath?)` | The title, description and path of a page. | | `seoHead(meta, origin?, alternates?)` | The `<head>` HTML of a page: title, description, the canonical link when `origin` is given, and the `hreflang` alternates. | | `specScript(context)` | The document as `<script type="application/json" data-apg-spec>`, which `renderApiReference` embeds. | | `docsScript(context)` | The extras of a docs bundle, as `<script data-apg-docs>`. | | `configureAsyncApiEngine(url)`, `configureProtobufEngine(url)`, `configureGraphQLEngine(url)` | Set the WebAssembly module that reads the documents of each standard. | ## Options of `renderApiReference` | Option | | | --- | --- | | `specUrl` | The key of the document; the elements of the page use it as `spec-url`. Required. | | `spec` | The document as text or a value. Left out, the document preloaded for `specUrl` is rendered. | | `route` | The page, such as `operation/getPet`; by default the overview. | | `routing`, `basePath`, `layout`, `theme` | As the attributes of `<apg-api-reference>`. | | `proxyUrl`, `oauth2RedirectUrl` | As `proxy-url` and `oauth2-redirect-url`. | | `hideTryIt`, `hideSchemas`, `showProblems` | As `hide-try-it`, `hide-schemas` and `show-problems`. | | `embedDocument` | Write the `<script data-apg-spec>` with the document; `true` by default. | ## The embedded document The rendered markup embeds the document as `<script type="application/json" data-apg-spec>`, so the browser uses what the server rendered instead of fetching the document again. For an AsyncAPI document, a Protobuf file or a GraphQL schema it embeds the documentation model, which the browser reads without the module. AsyncAPI documents, as text or values, need the module on the server too: call `configureAsyncApiEngine(url)` with the Node build (`asyncapi.mjs`, as a `file:` URL), then pass the document to `renderApiReference` or `preloadSpecAsync`. After `preloadSpec` it is not read yet. `.proto` text likewise needs `configureProtobufEngine` and `protobuf.mjs`, and GraphQL text `configureGraphQLEngine` and `graphql.mjs`. Their documentation models, which a docs bundle holds, are read without a module. --- # apigenie-docs build Source: https://apigenie.pl/docs/reference/doc-components/docs-build Part of the reference of [@mykulyak/apigenie-docs](https://apigenie.pl/docs/reference/doc-components.md). Its other pages: [apg-api-reference and apg-spec](https://apigenie.pl/docs/reference/doc-components/reference-and-spec.md), [OpenAPI elements](https://apigenie.pl/docs/reference/doc-components/openapi.md), [Swagger 2.0 elements](https://apigenie.pl/docs/reference/doc-components/swagger.md), [AsyncAPI elements](https://apigenie.pl/docs/reference/doc-components/asyncapi.md), [Protobuf and gRPC elements](https://apigenie.pl/docs/reference/doc-components/protobuf.md), [GraphQL elements](https://apigenie.pl/docs/reference/doc-components/graphql.md), [Building blocks](https://apigenie.pl/docs/reference/doc-components/building-blocks.md), [Try it out](https://apigenie.pl/docs/reference/doc-components/try-it-out.md), [Theming](https://apigenie.pl/docs/reference/doc-components/theming.md), [Server-side rendering](https://apigenie.pl/docs/reference/doc-components/server-side-rendering.md). `apigenie-generator docs` compiles OpenAPI, Swagger 2.0, AsyncAPI, GraphQL and Protobuf files into a docs bundle (`apigenie-docs.json` and, per document and locale, the document or its documentation model, with the git changelog and the example files) and an npm project whose `build` script runs `apigenie-docs build` from this package ([apigenie-generator docs](/docs/reference/generator/docs)). ```sh apigenie-generator docs openapi.yaml events.asyncapi.yaml --i18n pl=i18n-pl.json --changelog -o docs cd docs && npm install && npm run build # apigenie-docs build, into dist/ npm run build -- --base /docs/ --origin https://docs.example.com ``` ## Usage ```text apigenie-docs build [--bundle DIR] [--out DIR] [--base PATH] [--origin URL] [--clean] [--no-markdown] [--quiet] ``` | Option | Default | Description | | --- | --- | --- | | `--bundle DIR` | `.` | The bundle directory, holding `apigenie-docs.json`. | | `--out DIR` | `dist` | The site directory. | | `--base PATH` | `/` | The path the site is served at, such as `/docs/`. | | `--origin URL` | | The site's origin, for the sitemap and canonical links. Without it, the sitemap lists paths. | | `--clean` | | Empty the site directory first. | | `--no-markdown` | | Write no Markdown copy of the pages, `llms.txt` or `llms-full.txt`. | | `--quiet` | | Print nothing but errors. | | `-h`, `--help` | | Print the usage. | ## Exit status | Status | | | --- | --- | | `0` | The site was written, or `--help` printed the usage. | | `1` | The build failed; the error is printed. | | `2` | A usage error: no command, an unknown command or extra argument, an unknown option, an option without its value, or an `--origin` that is not a URL. The usage follows the error. | ## What it writes - One prerendered page per document, locale and route: `<base><locale>/<document>/<route>/index.html`. The locale prefix is left out for the default locale unless the bundle sets `prefixDefaultLocale`. The document prefix is left out for a site of one document, so one document in one locale gives `/`, `/operation/getPet/`, and so on. - An index page per locale when there are several documents, `sitemap.xml`, and, when the default locale has a prefix (`prefixDefaultLocale` in the bundle), an `index.html` at the root that redirects to `<base><locale>/`. - The hydrate script and its chunks under `_apigenie/`, `oauth2-redirect.html`, and each document's JSON next to its pages. - Next to each page its Markdown copy (`operation/getPet.md` beside `operation/getPet/`), for coding agents, linked from the page with `<link rel="alternate" type="text/markdown">`. The site root has `llms.txt`, which lists the copies of the default locale, and `llms-full.txt`, which holds them all. Every page embeds its document (or documentation model) and the bundle's extras, so hydration needs no WebAssembly module and no request. The pages get `<link rel="alternate" hreflang>` links and a locale switcher, a Changelog page (`<apg-changelog>`) when the bundle has a changelog, and the example files on the overview or on the GraphQL operation they are named after. ## As a library The renderer is a library too: `@mykulyak/apigenie-docs/docs` (`buildDocs(options)`, `readBundle(dir)`). The DOM-free part, `@mykulyak/apigenie-docs/bundle` (`parseManifest`, `loadBundle`, `sitePages`, `changelogView`, …), reads a bundle anywhere. `<apg-api-reference>` takes the extras on its own too: `changelog-url` (or the `changelog` property), `examples` and `locales`. --- # Any CI system Source: https://apigenie.pl/docs/ci `apigenie` runs the same three checks on a pull request whatever system runs the pipeline: `lint` for the issues in the files, `format --check` for the files that are not formatted, and `diff` for the changes that break clients. Each command exits with status 1 when it finds something, which fails the job, and writes a report in a format the system shows next to the pull request. This page has the pieces every system needs: the three commands, the reports each system reads, installing the CLI in a job, the comparison with the base branch, and one script that runs the checks. The pages of [GitLab CI](/docs/ci/gitlab), [Azure Pipelines](/docs/ci/azure-pipelines), [Jenkins](/docs/ci/jenkins), [CircleCI](/docs/ci/circleci) and [Bitbucket Pipelines](/docs/ci/bitbucket-pipelines) put them into one pipeline file each. On GitHub, the [GitHub Action](/docs/ci/github-action) installs the CLI, finds the base of the pull request and turns the reports into annotations. ## The three checks | Check | Command | Fails when | | ---------------- | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | | Lint | `apigenie lint api/openapi.yaml` | An issue of severity `error` is reported. Warnings alone do not fail the check. | | Formatting | `apigenie format --check api/openapi.yaml` | A file would change when formatted. The names of the files go to standard error; nothing is written. | | Breaking changes | `apigenie diff base.yaml api/openapi.yaml` | A change is breaking by the [rules](/docs/reference/cli/diff/rules) of the standard or the configuration. | The commands take several files, and glob patterns where the shell expands them. `lint`, `format` and `diff` read the project's `apigenie.yaml` when there is one, so the job checks what the developers check. Status 2 means a command could not run: a file that cannot be read, an invalid configuration, an option that does not exist. The [exit statuses](/docs/reference/cli#exit-status) are the same in the five binaries. ## Reports the systems read A report goes to standard output, so the job redirects it to a file and hands the file to the system. The job log then shows nothing of the issues; the exit status still fails the job, and the system shows the report next to the pull request. | Formatter | Written by | Read by | | ------------------------ | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `junit` | `lint` | The test reports of GitLab CI, Azure Pipelines, CircleCI and Bitbucket Pipelines, and the JUnit plugin of Jenkins: a test suite per file and a failed test case per issue, named after the rule, warnings included. | | `checkstyle` | `lint` | The Warnings plugin of Jenkins and other readers of Checkstyle XML, which keep the severity and the rule of each issue. | | `sarif` | `lint` | GitHub code scanning, the Warnings plugin of Jenkins and the SARIF viewers. The results link the rule pages, and carry fingerprints that let a dashboard follow an issue across runs. | | `markdown` | `diff` | People: a comment on the pull request, a job summary, an artifact. | | `json` | `lint`, `diff` | Scripts, with the JSON Schemas of the [lint](/docs/reference/cli/lint#json) and [diff](/docs/reference/cli/diff#json-output) reports. | | `unix`, `visualstudio` | `lint`, `diff` | One line per issue or change, with the file, the line and the column: for the job log, and for the problem matchers of editors and of some systems. | The `junit` report marks every issue as a failed test, warnings too, so a test tab can show failures on a job that passed: the status of the job comes from the exit status, which warnings do not change. ## Installing the CLI in a job With npm, on an image that has Node.js 18 or later; the package installs the binary of the job's platform, Linux x64, macOS arm64 or Windows x64: ```sh npm install -g @mykulyak/api-genie ``` From the release archive, on any Linux x64 image with `curl` and `tar`. The archive holds the four binaries, and `tar` extracts the one named; the `.sha256` file next to each asset is in `sha256sum` format: ```sh version=0.10.0 curl -fsSLO "https://github.com/mykulyak/api-genie/releases/download/cli-$version/apigenie-$version-linux-x64.tar.gz" curl -fsSLO "https://github.com/mykulyak/api-genie/releases/download/cli-$version/apigenie-$version-linux-x64.tar.gz.sha256" sha256sum -c "apigenie-$version-linux-x64.tar.gz.sha256" tar xzf "apigenie-$version-linux-x64.tar.gz" apigenie ./apigenie --version ``` In a container, with the `mykulyak/apigenie` image, Alpine Linux with the four binaries and `apigenie` as its entry point; the files are read from the mounted directory: ```sh docker run --rm -v "$PWD:/mnt/data" mykulyak/apigenie:0.10.0 lint api/openapi.yaml ``` A system that runs the job inside the image has to replace the entry point with a shell; the [GitLab CI](/docs/ci/gitlab#the-docker-image) page shows how. Pin the version in every case: a check that moves with `latest` changes under the pull requests. [Downloads](/downloads) lists the packages for the other platforms. ## Comparing with the base branch The `diff` check compares the file of the pull request with its version on the branch the pull request merges into. The system names that branch in a variable, and the job fetches its tip, which a shallow clone does not have, and takes the file from it: ```sh git fetch --depth=1 origin "$BASE" git show FETCH_HEAD:api/openapi.yaml > base.yaml apigenie diff base.yaml api/openapi.yaml ``` `FETCH_HEAD` is what the fetch brought, whatever branches the clone tracks; a clone of the pull request branch alone, which most systems make, has no `origin/main` even after the fetch. | System | The base branch | | ------------------- | ------------------------------------------------------------------------------------------------- | | GitHub Actions | `github.base_ref`; the action finds it itself. | | GitLab CI | `CI_MERGE_REQUEST_TARGET_BRANCH_NAME`, in a merge request pipeline. | | Azure Pipelines | `System.PullRequest.TargetBranch`, as `refs/heads/main` for Azure Repos and `main` for GitHub. | | Jenkins | `CHANGE_TARGET`, in a multibranch pipeline. | | CircleCI | None. The job names the branch, or reads the pull request through the provider's API. | | Bitbucket Pipelines | `BITBUCKET_PR_DESTINATION_BRANCH`, in a pull request pipeline. | A file the pull request adds has no base version, and `git show` fails; the script below skips the comparison then. To compare with the last release instead of the base branch, fetch its tag: `git fetch --depth=1 origin tag v1.4.0` and `git show v1.4.0:api/openapi.yaml`. ## One script for the three checks Every check runs even when an earlier one fails, so the pull request shows all three results at once; the exit status is 1 when any of them failed. `BASE` is the base branch from the table above. ```sh #!/bin/sh # The three checks of api/openapi.yaml; exits with 1 when one of them fails. status=0 apigenie lint --formatter junit api/openapi.yaml > lint.xml || status=1 apigenie format --check api/openapi.yaml || status=1 git fetch --depth=1 origin "$BASE" if git show FETCH_HEAD:api/openapi.yaml > base.yaml 2>/dev/null; then apigenie diff base.yaml api/openapi.yaml || status=1 fi exit $status ``` The script was run with the CLI 0.10.0 in a shallow clone of a pull request branch that removes an operation, with `BASE=main`: the lint report was written, the formatting check passed, the comparison reported the breaking change, and the exit status was 1. For a file the branch added, the comparison was skipped. --- # Azure Pipelines Source: https://apigenie.pl/docs/ci/azure-pipelines An `azure-pipelines.yml` that lints, checks the formatting of and compares an OpenAPI file in every pull request, as one job with a step per check: each step has its own status in the run, and the lint report feeds the Tests tab. [Any CI system](/docs/ci) explains the pieces: the commands, the reports, the installation and the comparison with the target branch. **Unchecked.** The file follows the Azure Pipelines documentation and has not run on a project on Azure DevOps. A run on one, passed or failed, reported in an [issue](https://github.com/mykulyak/api-genie/issues), makes it checked. ## The pipeline ```yaml # azure-pipelines.yml trigger: none pr: branches: include: ['*'] pool: vmImage: ubuntu-latest steps: - script: npm install -g @mykulyak/api-genie displayName: Install API Genie - script: apigenie lint --formatter junit api/openapi.yaml > $(Build.ArtifactStagingDirectory)/lint.xml displayName: Lint - task: PublishTestResults@2 displayName: Publish the lint report condition: succeededOrFailed() inputs: testResultsFormat: JUnit testResultsFiles: $(Build.ArtifactStagingDirectory)/lint.xml testRunTitle: apigenie lint - script: apigenie format --check api/openapi.yaml displayName: Check formatting condition: succeededOrFailed() - script: | base="${TARGET#refs/heads/}" git fetch --depth=1 origin "$base" git show FETCH_HEAD:api/openapi.yaml > base.yaml apigenie diff base.yaml api/openapi.yaml displayName: Breaking changes condition: and(succeededOrFailed(), eq(variables['Build.Reason'], 'PullRequest')) env: TARGET: $(System.PullRequest.TargetBranch) ``` `pr` triggers the pipeline on the pull requests of a repository on GitHub or Bitbucket; for Azure Repos, a build validation policy on the target branch, under *Branch policies*, runs it instead. `succeededOrFailed()` keeps the later steps running after a failed one, so the run shows all three results. `System.PullRequest.TargetBranch` is `refs/heads/main` for Azure Repos and `main` for GitHub; the step strips the prefix. ## What the pull request shows - The status of the pipeline, as a check on GitHub or as the policy's status on Azure Repos. A failed step fails the run. - The Tests tab of the run, from the JUnit report: a failed test per lint issue, named `apigenie.<rule>`, with the message. The task does not fail on failed tests, so the step's exit status alone decides, and warnings do not fail it. - The logs of the steps: the files that would change, and the changes with their severity. The *SARIF SAST Scans Tab* extension from the marketplace adds a Scans tab to the run that reads SARIF files from a published artifact named `CodeAnalysisLogs`; `apigenie lint --formatter sarif` writes one. --- # Bitbucket Pipelines Source: https://apigenie.pl/docs/ci/bitbucket-pipelines A `bitbucket-pipelines.yml` that lints, checks the formatting of and compares an OpenAPI file in every pull request, as three parallel steps: each has its own status on the pipeline, and the lint report feeds the Tests tab. [Any CI system](/docs/ci) explains the pieces: the commands, the reports, the installation and the comparison with the destination branch. **Unchecked.** The file follows the Bitbucket Pipelines documentation and has not run on a repository on Bitbucket. A run on one, passed or failed, reported in an [issue](https://github.com/mykulyak/api-genie/issues), makes it checked. ## The pipeline ```yaml # bitbucket-pipelines.yml image: node:22 pipelines: pull-requests: '**': - parallel: - step: name: Lint script: - npm install -g @mykulyak/api-genie - mkdir -p test-results - apigenie lint --formatter junit api/openapi.yaml > test-results/lint.xml - step: name: Check formatting script: - npm install -g @mykulyak/api-genie - apigenie format --check api/openapi.yaml - step: name: Breaking changes script: - npm install -g @mykulyak/api-genie - git fetch --depth=1 origin "$BITBUCKET_PR_DESTINATION_BRANCH" - git show FETCH_HEAD:api/openapi.yaml > base.yaml - apigenie diff base.yaml api/openapi.yaml ``` `pull-requests` runs the pipeline for every pull request, where `BITBUCKET_PR_DESTINATION_BRANCH` names the destination branch. Bitbucket finds JUnit reports on its own, in a `test-results` or `test-reports` directory at the root of the clone or up to three levels below, with no declaration in the file. The install repeats in each step, because the steps run in parallel in their own containers. ## What the pull request shows - The status of the pipeline on the pull request, with the three steps and their status. A failed pipeline blocks the merge once the merge checks of the repository require a successful build. - The Tests tab of the pipeline, from the JUnit report: a failed test per lint issue, named `apigenie.<rule>`, with the message; warnings are failed tests too, on a step that passed. - The logs of the steps: the files that would change, and the changes with their severity. Annotations on the lines of the pull request, Code Insights, take a call to the Reports API from the step, which the file does not make. --- # CircleCI Source: https://apigenie.pl/docs/ci/circleci A `.circleci/config.yml` that lints, checks the formatting of and compares an OpenAPI file on every push, as one job with a step per check: each has its own status in the job, and the lint report feeds the Tests tab. [Any CI system](/docs/ci) explains the pieces: the commands, the reports, the installation and the comparison with the base branch. **Unchecked.** The file follows the CircleCI documentation and has not run on a project on CircleCI. A run on one, passed or failed, reported in an [issue](https://github.com/mykulyak/api-genie/issues), makes it checked. ## The pipeline ```yaml # .circleci/config.yml version: 2.1 jobs: api: docker: - image: cimg/node:22.12 environment: BASE: main steps: - checkout - run: name: Install API Genie command: npm install -g @mykulyak/api-genie - run: name: Lint command: | mkdir -p reports apigenie lint --formatter junit api/openapi.yaml > reports/lint.xml - store_test_results: path: reports - run: name: Check formatting when: always command: apigenie format --check api/openapi.yaml - run: name: Breaking changes when: always command: | git fetch --depth=1 origin "$BASE" git show FETCH_HEAD:api/openapi.yaml > base.yaml apigenie diff base.yaml api/openapi.yaml workflows: api: jobs: - api ``` CircleCI has no variable for the branch a pull request merges into, so the job compares with `main`, set in `BASE`; a project that merges into release branches changes it per branch with a [pipeline value](https://circleci.com/docs/variables/) or asks the provider's API for the pull request. `when: always` keeps the later `run` steps running after a failed one, so the job shows all three results; `store_test_results` runs after a failed step on its own, and takes no `when`. The `cimg/node` image lets `npm install -g` write without `sudo`. ## What the pull request shows - The status of the job as a check on the pull request, with the steps and their status on the job page. A failed step fails the job. - The Tests tab of the job, from the JUnit report: a failed test per lint issue, named `apigenie.<rule>`, with the message; warnings are failed tests too, on a step that passed. The failed tests also appear in the insights of the project. - The output of the steps: the files that would change, and the changes with their severity. --- # GitLab CI Source: https://apigenie.pl/docs/ci/gitlab A `.gitlab-ci.yml` that lints, checks the formatting of and compares an OpenAPI file in every merge request, as three jobs: each has its own status in the merge request, and the lint report feeds the test summary. [Any CI system](/docs/ci) explains the pieces: the commands, the reports, the installation and the comparison with the target branch. **Unchecked.** The file follows the GitLab CI documentation and has not run on a project on GitLab. A run on one, passed or failed, reported in an [issue](https://github.com/mykulyak/api-genie/issues), makes it checked. ## The pipeline ```yaml # .gitlab-ci.yml .apigenie: image: node:22 rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" before_script: - npm install -g @mykulyak/api-genie lint: extends: .apigenie script: - apigenie lint --formatter junit api/openapi.yaml > lint.xml artifacts: when: always reports: junit: lint.xml format: extends: .apigenie script: - apigenie format --check api/openapi.yaml diff: extends: .apigenie script: - git fetch --depth=1 origin "$CI_MERGE_REQUEST_TARGET_BRANCH_NAME" - git show FETCH_HEAD:api/openapi.yaml > base.yaml - apigenie diff base.yaml api/openapi.yaml ``` The `rules` run the jobs in [merge request pipelines](https://docs.gitlab.com/ci/pipelines/merge_request_pipelines/) only, where `CI_MERGE_REQUEST_TARGET_BRANCH_NAME` names the target branch. `artifacts: when: always` uploads the lint report when the job fails, which is when the report matters; without it, GitLab keeps the artifacts of successful jobs alone. ## What the merge request shows - The pipeline widget lists the three jobs with their status. A failing job blocks the merge once *Pipelines must succeed* is on, under *Settings > Merge requests*. - The test summary, from the JUnit report of `lint`, counts the failed tests and lists them: one per issue, named `apigenie.<rule>`, with the message; warnings are failed tests too, on a job that passed. - The logs of `format` and `diff`: the files that would change, and the changes with their severity. The Code Quality widget reads the CodeClimate format, which `lint` does not write, and GitLab has no reader for the SARIF report. ## The Docker image The jobs can run in the `mykulyak/apigenie` image instead of installing the CLI into `node:22`. The image's entry point is `apigenie`, and a GitLab job needs the shell, so the entry point is cleared; `before_script` goes: ```yaml .apigenie: image: name: mykulyak/apigenie:0.10.0 entrypoint: [""] rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" ``` The image has `git`, so the `diff` job runs in it too. --- # Jenkins Source: https://apigenie.pl/docs/ci/jenkins A `Jenkinsfile` that lints, checks the formatting of and compares an OpenAPI file in every pull request of a multibranch pipeline, as one stage per check: each has its own status on the build, and the Warnings plugin shows the lint issues. [Any CI system](/docs/ci) explains the pieces: the commands, the reports, the installation and the comparison with the target branch. **Unchecked.** The file follows the Jenkins documentation and has not run on a Jenkins. A run on one, passed or failed, reported in an [issue](https://github.com/mykulyak/api-genie/issues), makes it checked. ## The pipeline The agent needs `curl`, `tar` and `git`; the CLI comes from the release archive, checked against its checksum, into the workspace. The [Warnings](https://plugins.jenkins.io/warnings-ng/) plugin reads the Checkstyle report, and a multibranch pipeline with a branch source for GitHub, GitLab or Bitbucket builds the pull requests, with `CHANGE_TARGET` as the target branch. ```groovy // Jenkinsfile pipeline { agent any environment { VERSION = '0.10.0' } stages { stage('Install') { steps { sh ''' curl -fsSLO "https://github.com/mykulyak/api-genie/releases/download/cli-$VERSION/apigenie-$VERSION-linux-x64.tar.gz" curl -fsSLO "https://github.com/mykulyak/api-genie/releases/download/cli-$VERSION/apigenie-$VERSION-linux-x64.tar.gz.sha256" sha256sum -c "apigenie-$VERSION-linux-x64.tar.gz.sha256" tar xzf "apigenie-$VERSION-linux-x64.tar.gz" apigenie ''' } } stage('Lint') { steps { catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { sh './apigenie lint --formatter checkstyle api/openapi.yaml > lint.xml' } } post { always { recordIssues tools: [checkStyle(pattern: 'lint.xml')] } } } stage('Format') { steps { catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') { sh './apigenie format --check api/openapi.yaml' } } } stage('Diff') { when { changeRequest() } steps { sh ''' git fetch --depth=1 origin "$CHANGE_TARGET" git show FETCH_HEAD:api/openapi.yaml > base.yaml ./apigenie diff base.yaml api/openapi.yaml ''' } } } } ``` `catchError` marks the stage and the build as failed and goes on to the next stage, so the build shows all three results; the last stage fails the build on its own. `when { changeRequest() }` runs the comparison for pull requests only, where `CHANGE_TARGET` is set. ## What the pull request shows - The status of the build on the pull request, set by the branch source plugin, and the stages with their status on the build page. - The *Checkstyle Warnings* view of the build, from the Warnings plugin: each lint issue with its file, line, severity and rule, and the trend across builds. The plugin reads the SARIF report as well, with `sarif(pattern: 'lint.sarif')` and `--formatter sarif`; the [JUnit](https://plugins.jenkins.io/junit/) plugin shows `--formatter junit` as failed tests, with `junit 'lint.xml'` in place of `recordIssues`. - The logs of the stages: the files that would change, and the changes with their severity. --- # GitHub Action Source: https://apigenie.pl/docs/ci/github-action The API Genie GitHub Action installs the CLI on GitHub Actions runners and lints, checks the formatting of, or diffs OpenAPI, Swagger 2.0, AsyncAPI, Protobuf and GraphQL files. Issues and changes are shown as annotations on the files of a pull request, and a report is added to the job summary. The action is published on the GitHub Marketplace as `mykulyak/api-genie-action`; its source and its releases are in [mykulyak/api-genie-action](https://github.com/mykulyak/api-genie-action). ## Usage ```yaml on: pull_request jobs: api: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: mykulyak/api-genie-action@v0 with: command: lint files: api/**/*.yaml config: apigenie.yaml - uses: mykulyak/api-genie-action@v0 with: command: format files: api/**/*.yaml - uses: mykulyak/api-genie-action@v0 with: command: diff files: api/openapi.yaml ``` - `lint` fails the step when an issue of severity `error` is reported (see [lint](/docs/reference/cli/lint#exit-status)). - `format` runs `apigenie format --check`: nothing is written, and the step fails when a file is not formatted. - `diff` compares each file with its version at the base commit of the pull request, or the commit before a push, and fails the step on breaking changes. Set `base` to compare with another commit, branch or tag, or `base-file` to compare two files of the repository. - Without `command`, the action only installs the CLI (`apigenie`, `apigenie-generator`, `apigenie-server`, `apigenie-catalog` and, since 0.12.0, `apigenie-mcp`) and puts it on `PATH`, for the steps that follow. ## Inputs | Input | Description | | ----- | ----------- | | `version` | CLI version: `latest` (default), `X.Y.Z` or `cli-X.Y.Z`. 0.9.0 is the oldest supported version. | | `command` | `lint`, `format` or `diff`. | | `files` | Files, one per line or separated by spaces. Glob patterns such as `api/**/*.yaml` are expanded. | | `config` | The [configuration file](/docs/reference/cli/configuration). | | `formatter` | Formatter of `lint` and `diff`. Only the default, `unix`, becomes annotations. | | `report` | Report of `diff`: `status`, `changelog` (default) or `detailed`. | | `fail-on` | `error` (default), `warning` (lint warnings fail the step too) or `never`. | | `base`, `base-file` | What `diff` compares with. | | `args` | More arguments for the command, separated by spaces. | | `annotations`, `summary` | Turn the annotations or the job summary off with `false`. | ## Outputs | Output | Description | | ------ | ----------- | | `status` | `lint`: `clean`, `warnings` or `errors`. `format`: `clean` or `changed`. `diff`: `none`, `non-breaking` or `breaking`. | | `exit-code` | The exit status of the CLI. | | `error-count`, `warning-count` | The numbers of lint errors and warnings. | | `changed-files` | The files that are not formatted. | | `version`, `path` | The installed CLI and its location. | ## Runners The action runs on Linux x64, macOS arm64 and Windows x64 runners. It downloads the CLI from the GitHub release, checks it against the release's checksums, and reuses it in later steps of the same job. --- # The editor's Library Source: https://apigenie.pl/docs/reference/editor/library The Library is the panel under the file list in the API Genie editor. It holds two kinds of schemas, and you drag schemas between it and the spec: - **My schemas**: schemas you keep. The editor keeps them outside your files (ADR-193): in the browser's storage for the site on the web, in the desktop app's own storage, and in the extension's global storage in VS Code. - **Library folders**: folders of YAML or JSON files beside or above the spec folder, such as a `shared` repository checked out next to it. Their files open with the spec folder's. A `$ref` from the spec into them is a relative path, `../shared/errors.yaml#/Error`, which resolves, renames and inlines like a reference between two files of the spec folder. Nothing about the Library is written to a spec. Where each library folder is gets kept per spec folder by the host. ## Adding a library folder | Host | How | | --- | --- | | Web | Type where the folder is, relative to the spec folder (`../shared`), then *Add library folder…* and pick it. After a reload, *Open* asks for access again. Needs the File System Access API. | | Desktop | *Add a library folder…* and pick it; the editor works out its path. After a restart, *Open* shows the folder in the dialog to allow access again. | | VS Code | List the folders in the `apigenie.editor.libraryFolders` setting, by their path from the workspace folder: `["../shared"]`. They open with the editor. | A library folder sits at most 8 levels above the spec folder, never inside it. ✕ closes a library folder and forgets it; it refuses while a file of the folder has unsaved changes. A library file lists schemas at its top level, as a shared file of the spec folder does, or under `components/schemas` when it is an OpenAPI or AsyncAPI file. ## Dragging a schema into the spec What you drag: - a row of My schemas; - a schema of a library folder; - a schema in the spec: a schema in the tree, the handle (⠿) of a row of the schema editor, the chip of a schema field. Where you drop it, and what the editor asks when there is a choice: | Dropped on | From My schemas | From a library folder | | --- | --- | --- | | A schema field (a request or response body, a parameter, a header, a message payload, `items`) | *Copy it here*, or *Add it as a component and refer to it* | *Refer to it in the library*, *Copy it here*, or *Copy it into the components and refer to it* | | A row of the schema editor: an object takes it as a new property named after it, an array as its `items` | the same as a schema field | the same as a schema field | | The `allOf`, `oneOf` or `anyOf` row of the schema editor | a new branch, with the same choices | a new branch, with the same choices | | A spec, or its *Schemas*, in the tree | a new component, without asking | a copy in the components, without asking | A schema of the spec dropped on a schema field offers *Refer to it* and *Copy it here*. *Use* on a row of My schemas adds it to the components of the selected file, as dropping it on that spec in the tree does. Escape, or a click outside the menu, cancels a drop. Each drop is one step of Undo. ### What comes along with a copy A schema that refers to other schemas brings them along: they are added to the components of the spec, and its references point to them. A component of the spec with the same name and the same content is used as it is; one with the same name and other content leaves the copy under the next free name (`Category-2`), which the status bar reports. A schema that refers to itself becomes one component. A reference that leads nowhere in the editor (a URL, a broken `$ref`) is copied as written, and the status bar reports it. ### Dialects A copy is converted to the dialect of the file it lands in. What has no counterpart is kept as written, and the status bar names it. | From | To | Converted | | --- | --- | --- | | OpenAPI 3.0 | OpenAPI 3.1, AsyncAPI 3.0 | `nullable: true` to a `null` in `type` (or in `enum`, without `type`), boolean `exclusiveMinimum` and `exclusiveMaximum` to numbers, `example` to `examples` | | OpenAPI 3.1, AsyncAPI 3.0 | OpenAPI 3.0 | a `type` list of one type and `null` to `nullable: true`, `const` to a one-value `enum`, numeric exclusive bounds to boolean ones, the first of `examples` to `example` | | OpenAPI 3.1 | AsyncAPI 3.0 | `example` to `examples`; `$defs`, `prefixItems`, `unevaluatedProperties` and the other 2020-12 keywords stay, with a note | The dialect of a library file is OpenAPI 3.0's when its schemas use `nullable` or boolean exclusive bounds, and JSON Schema 2020-12's otherwise. ## Dragging a schema into the Library | Dropped on | What happens | | --- | --- | | My schemas | A copy is kept, with the schemas it refers to, under the schema's name (`Order-2` when taken). *Keep … in my library* in the schema editor does the same. | | A file of a library folder | *Copy it into* the file, or *Move it to* the file *and refer to it*: the schema leaves the spec, and a `$ref` to the library takes its place. A component that moves keeps its name and every reference to it follows. | *Move* is refused while the schema refers to other schemas of the spec folder, since a library file refers only to its own folder and to other library folders: copy those schemas to the library first. The library file is saved into its library folder with the spec's files. *Rename* and ✕ on a row of My schemas rename and delete it. The search box filters both parts of the Library by name, and a click on a row shows its schema. --- # Linter rules Source: https://apigenie.pl/docs/linter See also: [OpenAPI linter rules](https://apigenie.pl/docs/linter/openapi.md), [AsyncAPI linter rules](https://apigenie.pl/docs/linter/asyncapi.md), [Swagger 2.0 linter rules](https://apigenie.pl/docs/linter/swagger.md), [GraphQL linter rules](https://apigenie.pl/docs/linter/graphql.md), [Protobuf linter rules](https://apigenie.pl/docs/linter/protobuf.md). [`apigenie lint`](/docs/reference/cli/lint.md) checks each document against the rules of its standard. A ruleset turns a set of rules on with their severities; your configuration extends one and adjusts single rules. | Standard | Rules | Rulesets | | --- | --- | --- | | [OpenAPI](/docs/linter/openapi.md) | 67 | 5 | | [AsyncAPI](/docs/linter/asyncapi.md) | 42 | 4 | | [Swagger 2.0](/docs/linter/swagger.md) | 48 | 3 | | [GraphQL](/docs/linter/graphql.md) | 87 | 4 | | [Protobuf](/docs/linter/protobuf.md) | 39 | 3 | --- # OpenAPI linter rules Source: https://apigenie.pl/docs/linter/openapi See also: [Linter rules](https://apigenie.pl/docs/linter.md), [Recommended ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/recommended.md), [Strict ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/strict.md), [All ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/all.md), [JsonApi ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/json-api.md), [Privacy ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/privacy.md). The linter reads OpenAPI 3.0, 3.1 and 3.2 documents. ## Rulesets - [Recommended ruleset](/docs/linter/openapi/rulesets/recommended.md) - [Strict ruleset](/docs/linter/openapi/rulesets/strict.md) - [All ruleset](/docs/linter/openapi/rulesets/all.md) - [JsonApi ruleset](/docs/linter/openapi/rulesets/json-api.md) - [Privacy ruleset](/docs/linter/openapi/rulesets/privacy.md) ## Rules | Rule | What it checks | Since | | --- | --- | --- | | [`audience-defined`](/docs/linter/openapi/rules/audience-defined.md) | This rule checks that `info` has an `x-audience` field, and that its value is one of `internal-team`, `internal-company`, `partner` and `public`. | 0.0.1 | | [`contact-defined`](/docs/linter/openapi/rules/contact-defined.md) | This rule checks that `info.contact` is present, with a `name` and a `url` or an `email`. | 0.0.1 | | [`id-defined`](/docs/linter/openapi/rules/id-defined.md) | This rule checks that `info` has an identifier field, `x-id` by default, whose value is a UUID or matches a pattern of your own. | 0.0.1 | | [`info-defined`](/docs/linter/openapi/rules/info-defined.md) | This rule checks that `info` has a non-empty `summary`, `description` and `version`. | 0.0.1 | | [`json-api/content-type`](/docs/linter/openapi/rules/json-api-content-type.md) | This rule checks that every request body and response of the document declares the `application/vnd.api+json` media type. | 0.0.1 | | [`json-api/resource-type-unique`](/docs/linter/openapi/rules/json-api-resource-type-unique.md) | This rule checks that every resource object schema of the JSON:API responses declares its `type` as a `const` or a one-value `enum`, and that no two of them declare the same type. | 0.0.1 | | [`json-api/schema-validation`](/docs/linter/openapi/rules/json-api-schema-validation.md) | This rule checks that the schemas of the JSON:API request bodies and responses describe JSON:API documents: a top-level object with `data`, `errors` or `meta`, and resource objects with `type` and `id`. | 0.0.1 | | [`json-schema-validation`](/docs/linter/openapi/rules/json-schema-validation.md) | This rule validates the document against API Genie's own meta-schema of OpenAPI 3.0 or 3.1 and reports every violation the validator finds. | 0.5.0 | | [`license-defined`](/docs/linter/openapi/rules/license-defined.md) | This rule checks that `info.license` is present, with a `name` and a `url` or an SPDX `identifier`. | 0.0.1 | | [`no-content-response-defined`](/docs/linter/openapi/rules/no-content-response-defined.md) | This rule checks that no `204` response declares `content`. | 0.0.1 | | [`openapi-json-schema-validation`](/docs/linter/openapi/rules/openapi-json-schema-validation.md) | This rule validates the document against the JSON Schema the OpenAPI Initiative publishes for its version: OpenAPI 3.0, 3.1 or 3.2. | 0.0.1 | | [`operation-description-defined`](/docs/linter/openapi/rules/operation-description-defined.md) | This rule checks that every operation has a `description` of at least 10 characters. | 0.0.1 | | [`operation-document-not-primitive`](/docs/linter/openapi/rules/operation-document-not-primitive.md) | This rule checks that every request body and response body is an object or an array, not a string, a number or a boolean. | 0.0.1 | | [`operation-id-defined`](/docs/linter/openapi/rules/operation-id-defined.md) | This rule checks that every operation has a non-empty `operationId`: those of paths, webhooks and the path items under `components`, and those of callbacks. | 0.0.1 | | [`operation-id-unique`](/docs/linter/openapi/rules/operation-id-unique.md) | This rule checks that no two operations share an `operationId`, callback operations included: the specification requires the ID to be unique among all operations of the API. Empty IDs are left to operation-id-defined. | 0.0.1 | | [`operation-rate-limiting-defined`](/docs/linter/openapi/rules/operation-rate-limiting-defined.md) | This rule checks that the responses of every operation declare the rate-limiting headers: `RateLimit-Limit`, `X-RateLimit-Limit` or `X-Rate-Limit-Limit` on every 2xx and 4xx response, and `Retry-After` on the `429` and `503` responses. | 0.0.1 | | [`operation-security-defined`](/docs/linter/openapi/rules/operation-security-defined.md) | This rule checks that every operation has security requirements, its own or the document's. | 0.0.1 | | [`operation-success-response`](/docs/linter/openapi/rules/operation-success-response.md) | This rule checks that every operation declares at least one 2xx or 3xx response, as a status code or as the `2XX` or `3XX` range. | 0.0.1 | | [`operation-tags-declared`](/docs/linter/openapi/rules/operation-tags-declared.md) | This rule checks that every tag an operation uses is declared in the document's `tags`. | 0.12.0 | | [`operation-tags-defined`](/docs/linter/openapi/rules/operation-tags-defined.md) | This rule checks that every operation has at least one tag. | 0.0.1 | | [`parameter-description-defined`](/docs/linter/openapi/rules/parameter-description-defined.md) | This rule checks that every parameter has a description of at least 10 characters that is not a placeholder. | 0.0.1 | | [`parameter-naming`](/docs/linter/openapi/rules/parameter-naming.md) | This rule checks that parameter names follow one naming convention per location: `kebab-case` for query parameters, `Header-Case` for header parameters and `snake_case` for the others, unless configured otherwise. | 0.0.1 | | [`parameters-unique`](/docs/linter/openapi/rules/parameters-unique.md) | This rule checks that no path item or operation declares two parameters with the same name and location. | 0.0.1 | | [`patch-request-body-partial`](/docs/linter/openapi/rules/patch-request-body-partial.md) | This rule checks that `PATCH` request bodies do not require properties. | 0.9.0 | | [`path-parameters-defined`](/docs/linter/openapi/rules/path-parameters-defined.md) | This rule checks that every `{placeholder}` of a path has a parameter with `in: path` and that name, on the path item or on each of its operations. | 0.0.1 | | [`path-parameters-on-items`](/docs/linter/openapi/rules/path-parameters-on-items.md) | This rule checks that path parameters are declared on the path item, not repeated on each of its operations. | 0.0.1 | | [`paths-max-count`](/docs/linter/openapi/rules/paths-max-count.md) | This rule checks that a document declares at most 8 paths, or the number configured. | 0.0.1 | | [`paths-max-depth`](/docs/linter/openapi/rules/paths-max-depth.md) | This rule checks that no path has more than 4 segments, or the number configured. A segment is the text between two slashes; `/users/{userId}/posts` has three. | 0.0.1 | | [`paths-sorted`](/docs/linter/openapi/rules/paths-sorted.md) | This rule checks that the paths of a document are in alphabetical order. | 0.0.1 | | [`paths-unique`](/docs/linter/openapi/rules/paths-unique.md) | This rule checks that no two paths match the same requests. Paths that differ only in the names of their placeholders, `/users/{id}` and `/users/{userId}`, are the same path. | 0.0.1 | | [`paths-well-formed`](/docs/linter/openapi/rules/paths-well-formed.md) | This rule checks that every path starts with one slash, ends without one, has no empty segment (`//`), no empty placeholder (`{}`) and no upper-case letter outside the placeholders. | 0.0.1 | | [`privacy/no-credentials-in-url`](/docs/linter/openapi/rules/privacy-no-credentials-in-url.md) | This rule reports passwords, tokens, API keys and other credentials passed in path or query parameters, and API keys that a security scheme sends in the query string. | 0.11.0 | | [`privacy/no-personal-data-in-url`](/docs/linter/openapi/rules/privacy-no-personal-data-in-url.md) | This rule reports personal data, such as e-mail addresses, names, dates of birth, phone numbers and national identification numbers, passed in path or query parameters. | 0.11.0 | | [`ref-no-siblings`](/docs/linter/openapi/rules/ref-no-siblings.md) | This rule checks that, in an OpenAPI 3.0 document, no property other than an extension sits next to the `$ref` of a Reference Object. | 0.12.0 | | [`safe-markdown`](/docs/linter/openapi/rules/safe-markdown.md) | This rule checks that no description contains a `<script>` tag or an `eval()` call. | 0.0.1 | | [`schema-conditional-effective`](/docs/linter/openapi/rules/schema-conditional-effective.md) | This rule checks that `if`, `then` and `else` in schemas have an effect. | 0.9.0 | | [`schema-constraints`](/docs/linter/openapi/rules/schema-constraints.md) | This rule checks that every schema bounds the size of its values: a minimum and a maximum for integers and numbers, a length, format, pattern or enum for strings, a maximum size for arrays, a maximum number of properties or `additionalProperties: false` for objects. | 0.0.1 | | [`schema-datetime-suffix`](/docs/linter/openapi/rules/schema-datetime-suffix.md) | This rule checks that the name of every property with the `date`, `date-time` or `time` format ends with `_at`, or with the suffix configured. | 0.0.1 | | [`schema-discriminator-defined`](/docs/linter/openapi/rules/schema-discriminator-defined.md) | This rule checks that every schema with `oneOf` has a `discriminator`. | 0.0.1 | | [`schema-enum-naming`](/docs/linter/openapi/rules/schema-enum-naming.md) | This rule checks that the string values of `enum` and `const` follow one naming convention, `CONST_CASE` (`ACTIVE_USER`) unless configured otherwise. | 0.0.1 | | [`schema-enum-no-duplicates`](/docs/linter/openapi/rules/schema-enum-no-duplicates.md) | This rule checks that no value appears twice in an `enum`. | 0.0.1 | | [`schema-enum-types`](/docs/linter/openapi/rules/schema-enum-types.md) | This rule checks that the values of `enum` and `const` have the type the schema declares. | 0.0.1 | | [`schema-example-defined`](/docs/linter/openapi/rules/schema-example-defined.md) | This rule checks that every schema that is not trivial, an object, an array or a string with a `pattern`, has an example. | 0.0.1 | | [`schema-format-defined`](/docs/linter/openapi/rules/schema-format-defined.md) | This rule checks that every `integer` and `number` schema has a `format` that says its size: `int32`, `int64` or another integer format for integers, `float`, `double`, `decimal` or another number format for numbers. | 0.0.1 | | [`schema-format-deprecated`](/docs/linter/openapi/rules/schema-format-deprecated.md) | This rule reports the formats which the OpenAPI format registry marks as deprecated, and names what replaces them. | 0.10.0 | | [`schema-format-type-mismatch`](/docs/linter/openapi/rules/schema-format-type-mismatch.md) | This rule checks that the `format` of a schema fits its `type`: `date` on a string, `int64` on an integer. | 0.0.1 | | [`schema-format-unknown`](/docs/linter/openapi/rules/schema-format-unknown.md) | This rule reports a `format` which is neither in the OpenAPI format registry nor declared in `openapi.custom_formats` of the configuration file. | 0.10.0 | | [`schema-keyword-support`](/docs/linter/openapi/rules/schema-keyword-support.md) | This rule reports schema keywords that the tools consuming the document are unlikely to support, and suggests the rewrite where one exists. | 0.11.0 | | [`schema-no-additional-properties`](/docs/linter/openapi/rules/schema-no-additional-properties.md) | This rule checks that every object schema has `additionalProperties: false`. | 0.0.1 | | [`schema-no-contradictions`](/docs/linter/openapi/rules/schema-no-contradictions.md) | This rule reports schemas with contradicting constraints, which reject every value or some of the properties they describe. | 0.9.0 | | [`schema-no-optional-nullable-properties`](/docs/linter/openapi/rules/schema-no-optional-nullable-properties.md) | This rule disallows schema properties that are both optional and nullable. | 0.0.1 | | [`schema-oneof-no-overlap`](/docs/linter/openapi/rules/schema-oneof-no-overlap.md) | This rule reports `oneOf` branches that a single value can match. | 0.9.0 | | [`schema-property-naming`](/docs/linter/openapi/rules/schema-property-naming.md) | This rule checks that the property names of schemas follow one naming convention, `snake_case` (`first_name`) unless configured otherwise. | 0.0.1 | | [`schema-required-properties-defined`](/docs/linter/openapi/rules/schema-required-properties-defined.md) | This rule checks that every name listed in `required` is defined in `properties`. | 0.9.0 | | [`server-urls`](/docs/linter/openapi/rules/server-urls.md) | This rule checks that every server URL is valid, has its scheme and host in lower case, and uses `https`, except on `localhost`. | 0.0.1 | | [`server-urls-no-trailing-slash`](/docs/linter/openapi/rules/server-urls-no-trailing-slash.md) | This rule checks that no URL in the document's top-level `servers`, other than `/`, ends with a slash. | 0.12.0 | | [`servers-defined`](/docs/linter/openapi/rules/servers-defined.md) | This rule checks that the document has at least one server. | 0.0.1 | | [`spell-check`](/docs/linter/openapi/rules/spell-check.md) | This rule checks the spelling of the texts written for humans: titles, summaries and descriptions. | 0.0.1 | | [`standard-media-types`](/docs/linter/openapi/rules/standard-media-types.md) | This rule checks that the media types of request bodies, responses, parameters and headers are ones the rule knows: a top-level type registered with IANA (`application`, `text`, `image`, `multipart`, ...) and one of about sixty common subtypes (`json`, `xml`, `problem+json`, `vnd.api+json`, `form-data`, `x-www-form-urlencoded`, `octet-stream`, `pdf`, `png`, ...), or `*` for either. | 0.0.1 | | [`standard-response-codes`](/docs/linter/openapi/rules/standard-response-codes.md) | This rule checks that every response is keyed by a three-digit HTTP status code from `100` to `599`, by a range from `1XX` to `5XX`, or by `default`. | 0.0.1 | | [`standard-response-errors`](/docs/linter/openapi/rules/standard-response-errors.md) | This rule checks that every 4xx and 5xx response has the error format of one convention, Problem Details (RFC 9457) unless configured otherwise. | 0.0.1 | | [`tag-description-defined`](/docs/linter/openapi/rules/tag-description-defined.md) | This rule checks that every tag has a description of at least 10 characters that is not a placeholder. | 0.0.1 | | [`tags-sorted`](/docs/linter/openapi/rules/tags-sorted.md) | This rule checks that the tags of the document are in alphabetical order of their names. | 0.0.1 | | [`tags-unique`](/docs/linter/openapi/rules/tags-unique.md) | This rule checks that no two tags have the same name, compared without regard to case. | 0.0.1 | | [`unambiguous-response-codes`](/docs/linter/openapi/rules/unambiguous-response-codes.md) | This rule checks that no operation declares both a range, such as `2XX`, and a code of that range, such as `204`. | 0.0.1 | | [`unused-request-body`](/docs/linter/openapi/rules/unused-request-body.md) | This rule checks that `GET`, `HEAD` and `TRACE` operations have no request body. | 0.0.1 | | [`unused-shared-component`](/docs/linter/openapi/rules/unused-shared-component.md) | This rule checks that every component of the document is reachable from its paths, webhooks, security requirements or tags. | 0.0.1 | --- # Recommended ruleset (OpenAPI) Source: https://apigenie.pl/docs/linter/openapi/rulesets/recommended See also: [OpenAPI linter rules](https://apigenie.pl/docs/linter/openapi.md), [Strict ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/strict.md), [All ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/all.md), [JsonApi ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/json-api.md), [Privacy ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/privacy.md). ## Rules | Name | Severity | | ---- | -------- | | [info-defined](/docs/linter/openapi/rules/info-defined) | error | | [no-content-response-defined](/docs/linter/openapi/rules/no-content-response-defined) | error | | [openapi-json-schema-validation](/docs/linter/openapi/rules/openapi-json-schema-validation) | error | | [operation-description-defined](/docs/linter/openapi/rules/operation-description-defined) | error | | [operation-id-defined](/docs/linter/openapi/rules/operation-id-defined) | error | | [operation-id-unique](/docs/linter/openapi/rules/operation-id-unique) | error | | [operation-rate-limiting-defined](/docs/linter/openapi/rules/operation-rate-limiting-defined) | warning | | [operation-security-defined](/docs/linter/openapi/rules/operation-security-defined) | warning | | [operation-success-response](/docs/linter/openapi/rules/operation-success-response) | error | | [operation-tags-declared](/docs/linter/openapi/rules/operation-tags-declared) | warning | | [operation-tags-defined](/docs/linter/openapi/rules/operation-tags-defined) | warning | | [parameter-description-defined](/docs/linter/openapi/rules/parameter-description-defined) | warning | | [parameter-naming](/docs/linter/openapi/rules/parameter-naming) | warning | | [parameters-unique](/docs/linter/openapi/rules/parameters-unique) | error | | [path-parameters-defined](/docs/linter/openapi/rules/path-parameters-defined) | error | | [path-parameters-on-items](/docs/linter/openapi/rules/path-parameters-on-items) | warning | | [paths-max-count](/docs/linter/openapi/rules/paths-max-count) | warning | | [paths-max-depth](/docs/linter/openapi/rules/paths-max-depth) | warning | | [paths-well-formed](/docs/linter/openapi/rules/paths-well-formed) | warning | | [ref-no-siblings](/docs/linter/openapi/rules/ref-no-siblings) | warning | | [safe-markdown](/docs/linter/openapi/rules/safe-markdown) | warning | | [schema-conditional-effective](/docs/linter/openapi/rules/schema-conditional-effective) | warning | | [schema-constraints](/docs/linter/openapi/rules/schema-constraints) | warning | | [schema-datetime-suffix](/docs/linter/openapi/rules/schema-datetime-suffix) | warning | | [schema-discriminator-defined](/docs/linter/openapi/rules/schema-discriminator-defined) | warning | | [schema-enum-no-duplicates](/docs/linter/openapi/rules/schema-enum-no-duplicates) | error | | [schema-enum-types](/docs/linter/openapi/rules/schema-enum-types) | error | | [schema-example-defined](/docs/linter/openapi/rules/schema-example-defined) | warning | | [schema-format-defined](/docs/linter/openapi/rules/schema-format-defined) | error | | [schema-format-deprecated](/docs/linter/openapi/rules/schema-format-deprecated) | warning | | [schema-format-type-mismatch](/docs/linter/openapi/rules/schema-format-type-mismatch) | error | | [schema-no-additional-properties](/docs/linter/openapi/rules/schema-no-additional-properties) | error | | [schema-no-contradictions](/docs/linter/openapi/rules/schema-no-contradictions) | warning | | [schema-no-optional-nullable-properties](/docs/linter/openapi/rules/schema-no-optional-nullable-properties) | warning | | [schema-oneof-no-overlap](/docs/linter/openapi/rules/schema-oneof-no-overlap) | warning | | [schema-required-properties-defined](/docs/linter/openapi/rules/schema-required-properties-defined) | warning | | [server-urls](/docs/linter/openapi/rules/server-urls) | warning | | [server-urls-no-trailing-slash](/docs/linter/openapi/rules/server-urls-no-trailing-slash) | warning | | [servers-defined](/docs/linter/openapi/rules/servers-defined) | warning | | [standard-media-types](/docs/linter/openapi/rules/standard-media-types) | warning | | [standard-response-codes](/docs/linter/openapi/rules/standard-response-codes) | error | | [tag-description-defined](/docs/linter/openapi/rules/tag-description-defined) | warning | | [tags-unique](/docs/linter/openapi/rules/tags-unique) | warning | | [unambiguous-response-codes](/docs/linter/openapi/rules/unambiguous-response-codes) | error | | [unused-request-body](/docs/linter/openapi/rules/unused-request-body) | warning | | [unused-shared-component](/docs/linter/openapi/rules/unused-shared-component) | warning | --- # Strict ruleset (OpenAPI) Source: https://apigenie.pl/docs/linter/openapi/rulesets/strict See also: [OpenAPI linter rules](https://apigenie.pl/docs/linter/openapi.md), [Recommended ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/recommended.md), [All ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/all.md), [JsonApi ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/json-api.md), [Privacy ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/privacy.md). ## Rules | Name | Severity | | ---- | -------- | | [audience-defined](/docs/linter/openapi/rules/audience-defined) | error | | [contact-defined](/docs/linter/openapi/rules/contact-defined) | error | | [id-defined](/docs/linter/openapi/rules/id-defined) | error | | [info-defined](/docs/linter/openapi/rules/info-defined) | error | | [license-defined](/docs/linter/openapi/rules/license-defined) | error | | [no-content-response-defined](/docs/linter/openapi/rules/no-content-response-defined) | error | | [openapi-json-schema-validation](/docs/linter/openapi/rules/openapi-json-schema-validation) | error | | [operation-description-defined](/docs/linter/openapi/rules/operation-description-defined) | error | | [operation-document-not-primitive](/docs/linter/openapi/rules/operation-document-not-primitive) | warning | | [operation-id-defined](/docs/linter/openapi/rules/operation-id-defined) | error | | [operation-id-unique](/docs/linter/openapi/rules/operation-id-unique) | error | | [operation-rate-limiting-defined](/docs/linter/openapi/rules/operation-rate-limiting-defined) | warning | | [operation-security-defined](/docs/linter/openapi/rules/operation-security-defined) | warning | | [operation-success-response](/docs/linter/openapi/rules/operation-success-response) | error | | [operation-tags-declared](/docs/linter/openapi/rules/operation-tags-declared) | error | | [operation-tags-defined](/docs/linter/openapi/rules/operation-tags-defined) | warning | | [parameter-description-defined](/docs/linter/openapi/rules/parameter-description-defined) | warning | | [parameter-naming](/docs/linter/openapi/rules/parameter-naming) | warning | | [parameters-unique](/docs/linter/openapi/rules/parameters-unique) | error | | [patch-request-body-partial](/docs/linter/openapi/rules/patch-request-body-partial) | error | | [path-parameters-defined](/docs/linter/openapi/rules/path-parameters-defined) | error | | [path-parameters-on-items](/docs/linter/openapi/rules/path-parameters-on-items) | warning | | [paths-max-count](/docs/linter/openapi/rules/paths-max-count) | warning | | [paths-max-depth](/docs/linter/openapi/rules/paths-max-depth) | warning | | [paths-sorted](/docs/linter/openapi/rules/paths-sorted) | error | | [paths-unique](/docs/linter/openapi/rules/paths-unique) | error | | [paths-well-formed](/docs/linter/openapi/rules/paths-well-formed) | error | | [ref-no-siblings](/docs/linter/openapi/rules/ref-no-siblings) | error | | [safe-markdown](/docs/linter/openapi/rules/safe-markdown) | error | | [schema-conditional-effective](/docs/linter/openapi/rules/schema-conditional-effective) | error | | [schema-constraints](/docs/linter/openapi/rules/schema-constraints) | warning | | [schema-datetime-suffix](/docs/linter/openapi/rules/schema-datetime-suffix) | error | | [schema-discriminator-defined](/docs/linter/openapi/rules/schema-discriminator-defined) | error | | [schema-enum-naming](/docs/linter/openapi/rules/schema-enum-naming) | error | | [schema-enum-no-duplicates](/docs/linter/openapi/rules/schema-enum-no-duplicates) | error | | [schema-enum-types](/docs/linter/openapi/rules/schema-enum-types) | error | | [schema-example-defined](/docs/linter/openapi/rules/schema-example-defined) | error | | [schema-format-defined](/docs/linter/openapi/rules/schema-format-defined) | error | | [schema-format-deprecated](/docs/linter/openapi/rules/schema-format-deprecated) | warning | | [schema-format-type-mismatch](/docs/linter/openapi/rules/schema-format-type-mismatch) | error | | [schema-format-unknown](/docs/linter/openapi/rules/schema-format-unknown) | warning | | [schema-no-additional-properties](/docs/linter/openapi/rules/schema-no-additional-properties) | error | | [schema-no-contradictions](/docs/linter/openapi/rules/schema-no-contradictions) | error | | [schema-no-optional-nullable-properties](/docs/linter/openapi/rules/schema-no-optional-nullable-properties) | error | | [schema-oneof-no-overlap](/docs/linter/openapi/rules/schema-oneof-no-overlap) | error | | [schema-property-naming](/docs/linter/openapi/rules/schema-property-naming) | error | | [schema-required-properties-defined](/docs/linter/openapi/rules/schema-required-properties-defined) | error | | [server-urls](/docs/linter/openapi/rules/server-urls) | error | | [server-urls-no-trailing-slash](/docs/linter/openapi/rules/server-urls-no-trailing-slash) | error | | [servers-defined](/docs/linter/openapi/rules/servers-defined) | error | | [spell-check](/docs/linter/openapi/rules/spell-check) | warning | | [standard-media-types](/docs/linter/openapi/rules/standard-media-types) | error | | [standard-response-codes](/docs/linter/openapi/rules/standard-response-codes) | error | | [standard-response-errors](/docs/linter/openapi/rules/standard-response-errors) | warning | | [tag-description-defined](/docs/linter/openapi/rules/tag-description-defined) | warning | | [tags-sorted](/docs/linter/openapi/rules/tags-sorted) | error | | [tags-unique](/docs/linter/openapi/rules/tags-unique) | error | | [unambiguous-response-codes](/docs/linter/openapi/rules/unambiguous-response-codes) | error | | [unused-request-body](/docs/linter/openapi/rules/unused-request-body) | error | | [unused-shared-component](/docs/linter/openapi/rules/unused-shared-component) | error | --- # All ruleset (OpenAPI) Source: https://apigenie.pl/docs/linter/openapi/rulesets/all See also: [OpenAPI linter rules](https://apigenie.pl/docs/linter/openapi.md), [Recommended ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/recommended.md), [Strict ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/strict.md), [JsonApi ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/json-api.md), [Privacy ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/privacy.md). ## Rules | Name | Severity | | ---- | -------- | | [audience-defined](/docs/linter/openapi/rules/audience-defined) | error | | [contact-defined](/docs/linter/openapi/rules/contact-defined) | error | | [id-defined](/docs/linter/openapi/rules/id-defined) | error | | [info-defined](/docs/linter/openapi/rules/info-defined) | error | | [license-defined](/docs/linter/openapi/rules/license-defined) | error | | [no-content-response-defined](/docs/linter/openapi/rules/no-content-response-defined) | error | | [openapi-json-schema-validation](/docs/linter/openapi/rules/openapi-json-schema-validation) | error | | [operation-description-defined](/docs/linter/openapi/rules/operation-description-defined) | error | | [operation-document-not-primitive](/docs/linter/openapi/rules/operation-document-not-primitive) | warning | | [operation-id-defined](/docs/linter/openapi/rules/operation-id-defined) | error | | [operation-id-unique](/docs/linter/openapi/rules/operation-id-unique) | error | | [operation-rate-limiting-defined](/docs/linter/openapi/rules/operation-rate-limiting-defined) | warning | | [operation-security-defined](/docs/linter/openapi/rules/operation-security-defined) | error | | [operation-success-response](/docs/linter/openapi/rules/operation-success-response) | error | | [operation-tags-declared](/docs/linter/openapi/rules/operation-tags-declared) | error | | [operation-tags-defined](/docs/linter/openapi/rules/operation-tags-defined) | error | | [parameter-description-defined](/docs/linter/openapi/rules/parameter-description-defined) | error | | [parameter-naming](/docs/linter/openapi/rules/parameter-naming) | error | | [parameters-unique](/docs/linter/openapi/rules/parameters-unique) | error | | [patch-request-body-partial](/docs/linter/openapi/rules/patch-request-body-partial) | error | | [path-parameters-defined](/docs/linter/openapi/rules/path-parameters-defined) | error | | [path-parameters-on-items](/docs/linter/openapi/rules/path-parameters-on-items) | error | | [paths-max-count](/docs/linter/openapi/rules/paths-max-count) | error | | [paths-max-depth](/docs/linter/openapi/rules/paths-max-depth) | error | | [paths-sorted](/docs/linter/openapi/rules/paths-sorted) | error | | [paths-unique](/docs/linter/openapi/rules/paths-unique) | error | | [paths-well-formed](/docs/linter/openapi/rules/paths-well-formed) | error | | [ref-no-siblings](/docs/linter/openapi/rules/ref-no-siblings) | error | | [safe-markdown](/docs/linter/openapi/rules/safe-markdown) | error | | [schema-conditional-effective](/docs/linter/openapi/rules/schema-conditional-effective) | error | | [schema-constraints](/docs/linter/openapi/rules/schema-constraints) | warning | | [schema-datetime-suffix](/docs/linter/openapi/rules/schema-datetime-suffix) | error | | [schema-discriminator-defined](/docs/linter/openapi/rules/schema-discriminator-defined) | error | | [schema-enum-naming](/docs/linter/openapi/rules/schema-enum-naming) | error | | [schema-enum-no-duplicates](/docs/linter/openapi/rules/schema-enum-no-duplicates) | error | | [schema-enum-types](/docs/linter/openapi/rules/schema-enum-types) | error | | [schema-example-defined](/docs/linter/openapi/rules/schema-example-defined) | error | | [schema-format-defined](/docs/linter/openapi/rules/schema-format-defined) | error | | [schema-format-deprecated](/docs/linter/openapi/rules/schema-format-deprecated) | warning | | [schema-format-type-mismatch](/docs/linter/openapi/rules/schema-format-type-mismatch) | error | | [schema-format-unknown](/docs/linter/openapi/rules/schema-format-unknown) | warning | | [schema-keyword-support](/docs/linter/openapi/rules/schema-keyword-support) | warning | | [schema-no-additional-properties](/docs/linter/openapi/rules/schema-no-additional-properties) | error | | [schema-no-contradictions](/docs/linter/openapi/rules/schema-no-contradictions) | error | | [schema-no-optional-nullable-properties](/docs/linter/openapi/rules/schema-no-optional-nullable-properties) | error | | [schema-oneof-no-overlap](/docs/linter/openapi/rules/schema-oneof-no-overlap) | error | | [schema-property-naming](/docs/linter/openapi/rules/schema-property-naming) | error | | [schema-required-properties-defined](/docs/linter/openapi/rules/schema-required-properties-defined) | error | | [server-urls](/docs/linter/openapi/rules/server-urls) | error | | [server-urls-no-trailing-slash](/docs/linter/openapi/rules/server-urls-no-trailing-slash) | error | | [servers-defined](/docs/linter/openapi/rules/servers-defined) | error | | [spell-check](/docs/linter/openapi/rules/spell-check) | warning | | [standard-media-types](/docs/linter/openapi/rules/standard-media-types) | error | | [standard-response-codes](/docs/linter/openapi/rules/standard-response-codes) | error | | [standard-response-errors](/docs/linter/openapi/rules/standard-response-errors) | warning | | [tag-description-defined](/docs/linter/openapi/rules/tag-description-defined) | warning | | [tags-sorted](/docs/linter/openapi/rules/tags-sorted) | error | | [tags-unique](/docs/linter/openapi/rules/tags-unique) | error | | [unambiguous-response-codes](/docs/linter/openapi/rules/unambiguous-response-codes) | error | | [unused-request-body](/docs/linter/openapi/rules/unused-request-body) | error | | [unused-shared-component](/docs/linter/openapi/rules/unused-shared-component) | error | --- # JsonApi ruleset (OpenAPI) Source: https://apigenie.pl/docs/linter/openapi/rulesets/json-api See also: [OpenAPI linter rules](https://apigenie.pl/docs/linter/openapi.md), [Recommended ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/recommended.md), [Strict ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/strict.md), [All ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/all.md), [Privacy ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/privacy.md). ## Rules | Name | Severity | | ---- | -------- | | [json-api/content-type](/docs/linter/openapi/rules/json-api-content-type) | error | | [json-api/resource-type-unique](/docs/linter/openapi/rules/json-api-resource-type-unique) | error | | [json-api/schema-validation](/docs/linter/openapi/rules/json-api-schema-validation) | error | --- # Privacy ruleset (OpenAPI) Source: https://apigenie.pl/docs/linter/openapi/rulesets/privacy See also: [OpenAPI linter rules](https://apigenie.pl/docs/linter/openapi.md), [Recommended ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/recommended.md), [Strict ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/strict.md), [All ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/all.md), [JsonApi ruleset](https://apigenie.pl/docs/linter/openapi/rulesets/json-api.md). Security and data-protection checks of the data an API exposes: credentials and personal data (GDPR Art. 4(1), Art. 9) should never travel in URLs, which end up in server and proxy logs, browser history and `Referer` headers (OWASP API Security Top 10 API2:2023, CWE-598, GDPR Art. 5(1)(f), 25 and 32). The ruleset, in the CLI since 0.11.0, is not part of `all`; add it next to another ruleset: ```yaml commands: lint: extends: [recommended, privacy] ``` ## Rules | Name | Severity | | ---- | -------- | | [privacy/no-credentials-in-url](/docs/linter/openapi/rules/privacy-no-credentials-in-url) | error | | [privacy/no-personal-data-in-url](/docs/linter/openapi/rules/privacy-no-personal-data-in-url) | warning | --- # AsyncAPI linter rules Source: https://apigenie.pl/docs/linter/asyncapi See also: [Linter rules](https://apigenie.pl/docs/linter.md), [Recommended ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/recommended.md), [Strict ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/strict.md), [All ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/all.md), [CloudEvents ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/cloudevents.md). The linter reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. ## Rulesets - [Recommended ruleset](/docs/linter/asyncapi/rulesets/recommended.md) - [Strict ruleset](/docs/linter/asyncapi/rulesets/strict.md) - [All ruleset](/docs/linter/asyncapi/rulesets/all.md) - [CloudEvents ruleset](/docs/linter/asyncapi/rulesets/cloudevents.md) ## Rules | Rule | What it checks | Since | | --- | --- | --- | | [`audience-defined`](/docs/linter/asyncapi/rules/audience-defined.md) | This rule checks whether the intended audience of an API is declared in the `#/info/x-audience` extension of an AsyncAPI document. | 0.9.0 | | [`channel-address-no-query`](/docs/linter/asyncapi/rules/channel-address-no-query.md) | This rule checks that no channel address contains a query (`?`) or a fragment (`#`). | 0.12.0 | | [`channel-addresses-unique`](/docs/linter/asyncapi/rules/channel-addresses-unique.md) | This rule checks that no two channels of an AsyncAPI document share the same address, including addresses that differ only by the names of their parameters. | 0.9.0 | | [`channel-parameters-defined`](/docs/linter/asyncapi/rules/channel-parameters-defined.md) | This rule checks that the parameters used in a channel address are declared in the channel's `parameters` map, and that the map declares no parameters the address does not use. | 0.9.0 | | [`channel-servers-in-servers`](/docs/linter/asyncapi/rules/channel-servers-in-servers.md) | This rule checks that the servers of a channel under the root `channels` are references to servers under the root `servers`. | 0.12.0 | | [`cloudevents/attribute-schemas`](/docs/linter/asyncapi/rules/cloudevents-attribute-schemas.md) | This rule checks that the schemas of CloudEvents attributes say what the specification says of them. | 0.12.0 | | [`cloudevents/binding-headers`](/docs/linter/asyncapi/rules/cloudevents-binding-headers.md) | This rule checks that the attribute headers of binary-mode CloudEvents use the prefix of the protocol their channel is served over. | 0.12.0 | | [`cloudevents/required-attributes`](/docs/linter/asyncapi/rules/cloudevents-required-attributes.md) | This rule checks that every CloudEvents message declares and requires the four attributes every event has: `id`, `source`, `specversion` and `type`. | 0.12.0 | | [`contact-defined`](/docs/linter/asyncapi/rules/contact-defined.md) | This rule checks whether complete contact information is present in an AsyncAPI document. | 0.9.0 | | [`id-defined`](/docs/linter/asyncapi/rules/id-defined.md) | This rule checks whether the application identifier (the root `id` field) is present in an AsyncAPI document, and whether its value matches the expected format. | 0.9.0 | | [`info-defined`](/docs/linter/asyncapi/rules/info-defined.md) | This rule checks whether the info object of an AsyncAPI document provides a description and a version. | 0.9.0 | | [`latest-version`](/docs/linter/asyncapi/rules/latest-version.md) | This rule suggests the latest version of AsyncAPI, 3.1.0, to a document that declares an older one. | 0.12.0 | | [`license-defined`](/docs/linter/asyncapi/rules/license-defined.md) | This rule checks whether the licensing information is present in an AsyncAPI document. | 0.9.0 | | [`operation-channel-in-channels`](/docs/linter/asyncapi/rules/operation-channel-in-channels.md) | This rule checks that the channel of an operation under the root `operations` is a reference to a channel under the root `channels`. | 0.12.0 | | [`operation-description-defined`](/docs/linter/asyncapi/rules/operation-description-defined.md) | This rule checks whether every operation of an AsyncAPI document has a meaningful description. | 0.9.0 | | [`operation-messages-from-channel`](/docs/linter/asyncapi/rules/operation-messages-from-channel.md) | This rule checks that the messages of an operation, and of its reply, are references to messages of the channel that the operation, or the reply, references. | 0.12.0 | | [`operation-security-defined`](/docs/linter/asyncapi/rules/operation-security-defined.md) | This rule checks whether every operation of an AsyncAPI document is protected by a security requirement. | 0.9.0 | | [`operation-tags-defined`](/docs/linter/asyncapi/rules/operation-tags-defined.md) | This rule checks whether every operation of an AsyncAPI document has at least one tag assigned. | 0.9.0 | | [`parameter-description-defined`](/docs/linter/asyncapi/rules/parameter-description-defined.md) | This rule checks whether every channel parameter of an AsyncAPI document has a meaningful description. | 0.9.0 | | [`parameter-naming`](/docs/linter/asyncapi/rules/parameter-naming.md) | This rule checks all channel parameters in an AsyncAPI document and warns if their names do not adhere to the specified naming convention. | 0.9.0 | | [`safe-markdown`](/docs/linter/asyncapi/rules/safe-markdown.md) | This rule ensures that Markdown strings (descriptions) do not contain unsafe constructs like script tags or `eval()` calls. | 0.9.0 | | [`schema-constraints`](/docs/linter/asyncapi/rules/schema-constraints.md) | This rule ensures that schema objects define constraints restricting the size of the underlying data. | 0.9.0 | | [`schema-datetime-suffix`](/docs/linter/asyncapi/rules/schema-datetime-suffix.md) | This rule ensures that the names of date and time properties end with a common suffix. | 0.9.0 | | [`schema-enum-naming`](/docs/linter/asyncapi/rules/schema-enum-naming.md) | This rule ensures that all string values defined in the `enum` properties of schema objects adhere to a predefined naming convention. | 0.9.0 | | [`schema-enum-no-duplicates`](/docs/linter/asyncapi/rules/schema-enum-no-duplicates.md) | This rule ensures that the `enum` lists of schema objects contain no duplicate values. | 0.9.0 | | [`schema-enum-types`](/docs/linter/asyncapi/rules/schema-enum-types.md) | This rule ensures that the values listed in the `enum` of a schema are allowed by the schema's `type`. | 0.9.0 | | [`schema-example-defined`](/docs/linter/asyncapi/rules/schema-example-defined.md) | This rule ensures that top-level schemas of an AsyncAPI document provide examples. | 0.9.0 | | [`schema-format-defined`](/docs/linter/asyncapi/rules/schema-format-defined.md) | This rule ensures that numeric schemas specify the precision of their values with a `format`. | 0.9.0 | | [`schema-format-deprecated`](/docs/linter/asyncapi/rules/schema-format-deprecated.md) | This rule reports the formats which the OpenAPI format registry marks as deprecated from OpenAPI 3.1, and names what replaces them. | 0.10.0 | | [`schema-format-type-mismatch`](/docs/linter/asyncapi/rules/schema-format-type-mismatch.md) | This rule ensures that the `format` of a schema is consistent with its `type`. | 0.9.0 | | [`schema-format-unknown`](/docs/linter/asyncapi/rules/schema-format-unknown.md) | This rule reports a `format` of an AsyncAPI document which is neither in the OpenAPI format registry nor declared in `openapi.custom_formats` of the configuration file. | 0.10.0 | | [`schema-keyword-support`](/docs/linter/asyncapi/rules/schema-keyword-support.md) | This rule reports schema keywords that the tools consuming the document are unlikely to support, and suggests the rewrite where one exists. | 0.11.0 | | [`schema-no-additional-properties`](/docs/linter/asyncapi/rules/schema-no-additional-properties.md) | This rule ensures that object schemas explicitly disallow additional properties. | 0.9.0 | | [`schema-property-naming`](/docs/linter/asyncapi/rules/schema-property-naming.md) | This rule ensures that the names of schema properties adhere to a predefined naming convention. | 0.9.0 | | [`server-hosts`](/docs/linter/asyncapi/rules/server-hosts.md) | This rule checks that the servers of an AsyncAPI document have well-formed hosts and protocols, and that they use secure protocols. | 0.9.0 | | [`servers-defined`](/docs/linter/asyncapi/rules/servers-defined.md) | This rule checks whether at least one server is defined in an AsyncAPI document. | 0.9.0 | | [`spell-check`](/docs/linter/asyncapi/rules/spell-check.md) | This rule checks the spelling of the texts written for humans: titles, summaries and descriptions. | 0.9.0 | | [`standard-media-types`](/docs/linter/asyncapi/rules/standard-media-types.md) | This rule checks whether messages use only standard media types. | 0.9.0 | | [`tag-description-defined`](/docs/linter/asyncapi/rules/tag-description-defined.md) | This rule checks whether every tag of an AsyncAPI document has a meaningful description. | 0.9.0 | | [`tags-sorted`](/docs/linter/asyncapi/rules/tags-sorted.md) | This rule checks whether the tags listed in `info.tags` are sorted by their names. | 0.9.0 | | [`tags-unique`](/docs/linter/asyncapi/rules/tags-unique.md) | This rule checks whether the names of the tags listed in `info.tags` are unique. | 0.9.0 | | [`unused-shared-component`](/docs/linter/asyncapi/rules/unused-shared-component.md) | This rule checks whether every shared component of an AsyncAPI document is actually used. | 0.9.0 | --- # Recommended ruleset (AsyncAPI) Source: https://apigenie.pl/docs/linter/asyncapi/rulesets/recommended See also: [AsyncAPI linter rules](https://apigenie.pl/docs/linter/asyncapi.md), [Strict ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/strict.md), [All ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/all.md), [CloudEvents ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/cloudevents.md). ## Rules | Name | Severity | | ---- | -------- | | [channel-address-no-query](/docs/linter/asyncapi/rules/channel-address-no-query) | error | | [channel-parameters-defined](/docs/linter/asyncapi/rules/channel-parameters-defined) | error | | [channel-servers-in-servers](/docs/linter/asyncapi/rules/channel-servers-in-servers) | error | | [info-defined](/docs/linter/asyncapi/rules/info-defined) | error | | [operation-channel-in-channels](/docs/linter/asyncapi/rules/operation-channel-in-channels) | error | | [operation-description-defined](/docs/linter/asyncapi/rules/operation-description-defined) | error | | [operation-messages-from-channel](/docs/linter/asyncapi/rules/operation-messages-from-channel) | error | | [operation-security-defined](/docs/linter/asyncapi/rules/operation-security-defined) | warning | | [operation-tags-defined](/docs/linter/asyncapi/rules/operation-tags-defined) | warning | | [parameter-description-defined](/docs/linter/asyncapi/rules/parameter-description-defined) | warning | | [parameter-naming](/docs/linter/asyncapi/rules/parameter-naming) | warning | | [safe-markdown](/docs/linter/asyncapi/rules/safe-markdown) | warning | | [schema-constraints](/docs/linter/asyncapi/rules/schema-constraints) | warning | | [schema-datetime-suffix](/docs/linter/asyncapi/rules/schema-datetime-suffix) | warning | | [schema-enum-no-duplicates](/docs/linter/asyncapi/rules/schema-enum-no-duplicates) | error | | [schema-enum-types](/docs/linter/asyncapi/rules/schema-enum-types) | error | | [schema-example-defined](/docs/linter/asyncapi/rules/schema-example-defined) | warning | | [schema-format-defined](/docs/linter/asyncapi/rules/schema-format-defined) | error | | [schema-format-deprecated](/docs/linter/asyncapi/rules/schema-format-deprecated) | warning | | [schema-format-type-mismatch](/docs/linter/asyncapi/rules/schema-format-type-mismatch) | error | | [schema-no-additional-properties](/docs/linter/asyncapi/rules/schema-no-additional-properties) | error | | [server-hosts](/docs/linter/asyncapi/rules/server-hosts) | warning | | [servers-defined](/docs/linter/asyncapi/rules/servers-defined) | warning | | [standard-media-types](/docs/linter/asyncapi/rules/standard-media-types) | warning | | [tag-description-defined](/docs/linter/asyncapi/rules/tag-description-defined) | warning | | [tags-unique](/docs/linter/asyncapi/rules/tags-unique) | warning | | [unused-shared-component](/docs/linter/asyncapi/rules/unused-shared-component) | warning | --- # Strict ruleset (AsyncAPI) Source: https://apigenie.pl/docs/linter/asyncapi/rulesets/strict See also: [AsyncAPI linter rules](https://apigenie.pl/docs/linter/asyncapi.md), [Recommended ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/recommended.md), [All ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/all.md), [CloudEvents ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/cloudevents.md). ## Rules | Name | Severity | | ---- | -------- | | [audience-defined](/docs/linter/asyncapi/rules/audience-defined) | error | | [channel-address-no-query](/docs/linter/asyncapi/rules/channel-address-no-query) | error | | [channel-addresses-unique](/docs/linter/asyncapi/rules/channel-addresses-unique) | error | | [channel-parameters-defined](/docs/linter/asyncapi/rules/channel-parameters-defined) | error | | [channel-servers-in-servers](/docs/linter/asyncapi/rules/channel-servers-in-servers) | error | | [contact-defined](/docs/linter/asyncapi/rules/contact-defined) | error | | [id-defined](/docs/linter/asyncapi/rules/id-defined) | error | | [info-defined](/docs/linter/asyncapi/rules/info-defined) | error | | [latest-version](/docs/linter/asyncapi/rules/latest-version) | hint | | [license-defined](/docs/linter/asyncapi/rules/license-defined) | error | | [operation-channel-in-channels](/docs/linter/asyncapi/rules/operation-channel-in-channels) | error | | [operation-description-defined](/docs/linter/asyncapi/rules/operation-description-defined) | error | | [operation-messages-from-channel](/docs/linter/asyncapi/rules/operation-messages-from-channel) | error | | [operation-security-defined](/docs/linter/asyncapi/rules/operation-security-defined) | warning | | [operation-tags-defined](/docs/linter/asyncapi/rules/operation-tags-defined) | warning | | [parameter-description-defined](/docs/linter/asyncapi/rules/parameter-description-defined) | warning | | [parameter-naming](/docs/linter/asyncapi/rules/parameter-naming) | warning | | [safe-markdown](/docs/linter/asyncapi/rules/safe-markdown) | error | | [schema-constraints](/docs/linter/asyncapi/rules/schema-constraints) | warning | | [schema-datetime-suffix](/docs/linter/asyncapi/rules/schema-datetime-suffix) | error | | [schema-enum-naming](/docs/linter/asyncapi/rules/schema-enum-naming) | error | | [schema-enum-no-duplicates](/docs/linter/asyncapi/rules/schema-enum-no-duplicates) | error | | [schema-enum-types](/docs/linter/asyncapi/rules/schema-enum-types) | error | | [schema-example-defined](/docs/linter/asyncapi/rules/schema-example-defined) | error | | [schema-format-defined](/docs/linter/asyncapi/rules/schema-format-defined) | error | | [schema-format-deprecated](/docs/linter/asyncapi/rules/schema-format-deprecated) | warning | | [schema-format-type-mismatch](/docs/linter/asyncapi/rules/schema-format-type-mismatch) | error | | [schema-format-unknown](/docs/linter/asyncapi/rules/schema-format-unknown) | warning | | [schema-no-additional-properties](/docs/linter/asyncapi/rules/schema-no-additional-properties) | error | | [schema-property-naming](/docs/linter/asyncapi/rules/schema-property-naming) | error | | [server-hosts](/docs/linter/asyncapi/rules/server-hosts) | error | | [servers-defined](/docs/linter/asyncapi/rules/servers-defined) | error | | [spell-check](/docs/linter/asyncapi/rules/spell-check) | warning | | [standard-media-types](/docs/linter/asyncapi/rules/standard-media-types) | error | | [tag-description-defined](/docs/linter/asyncapi/rules/tag-description-defined) | warning | | [tags-sorted](/docs/linter/asyncapi/rules/tags-sorted) | error | | [tags-unique](/docs/linter/asyncapi/rules/tags-unique) | error | | [unused-shared-component](/docs/linter/asyncapi/rules/unused-shared-component) | error | --- # All ruleset (AsyncAPI) Source: https://apigenie.pl/docs/linter/asyncapi/rulesets/all See also: [AsyncAPI linter rules](https://apigenie.pl/docs/linter/asyncapi.md), [Recommended ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/recommended.md), [Strict ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/strict.md), [CloudEvents ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/cloudevents.md). ## Rules | Name | Severity | | ---- | -------- | | [audience-defined](/docs/linter/asyncapi/rules/audience-defined) | error | | [channel-address-no-query](/docs/linter/asyncapi/rules/channel-address-no-query) | error | | [channel-addresses-unique](/docs/linter/asyncapi/rules/channel-addresses-unique) | error | | [channel-parameters-defined](/docs/linter/asyncapi/rules/channel-parameters-defined) | error | | [channel-servers-in-servers](/docs/linter/asyncapi/rules/channel-servers-in-servers) | error | | [contact-defined](/docs/linter/asyncapi/rules/contact-defined) | error | | [id-defined](/docs/linter/asyncapi/rules/id-defined) | error | | [info-defined](/docs/linter/asyncapi/rules/info-defined) | error | | [latest-version](/docs/linter/asyncapi/rules/latest-version) | hint | | [license-defined](/docs/linter/asyncapi/rules/license-defined) | error | | [operation-channel-in-channels](/docs/linter/asyncapi/rules/operation-channel-in-channels) | error | | [operation-description-defined](/docs/linter/asyncapi/rules/operation-description-defined) | error | | [operation-messages-from-channel](/docs/linter/asyncapi/rules/operation-messages-from-channel) | error | | [operation-security-defined](/docs/linter/asyncapi/rules/operation-security-defined) | error | | [operation-tags-defined](/docs/linter/asyncapi/rules/operation-tags-defined) | error | | [parameter-description-defined](/docs/linter/asyncapi/rules/parameter-description-defined) | error | | [parameter-naming](/docs/linter/asyncapi/rules/parameter-naming) | error | | [safe-markdown](/docs/linter/asyncapi/rules/safe-markdown) | error | | [schema-constraints](/docs/linter/asyncapi/rules/schema-constraints) | warning | | [schema-datetime-suffix](/docs/linter/asyncapi/rules/schema-datetime-suffix) | error | | [schema-enum-naming](/docs/linter/asyncapi/rules/schema-enum-naming) | error | | [schema-enum-no-duplicates](/docs/linter/asyncapi/rules/schema-enum-no-duplicates) | error | | [schema-enum-types](/docs/linter/asyncapi/rules/schema-enum-types) | error | | [schema-example-defined](/docs/linter/asyncapi/rules/schema-example-defined) | error | | [schema-format-defined](/docs/linter/asyncapi/rules/schema-format-defined) | error | | [schema-format-deprecated](/docs/linter/asyncapi/rules/schema-format-deprecated) | warning | | [schema-format-type-mismatch](/docs/linter/asyncapi/rules/schema-format-type-mismatch) | error | | [schema-format-unknown](/docs/linter/asyncapi/rules/schema-format-unknown) | warning | | [schema-keyword-support](/docs/linter/asyncapi/rules/schema-keyword-support) | warning | | [schema-no-additional-properties](/docs/linter/asyncapi/rules/schema-no-additional-properties) | error | | [schema-property-naming](/docs/linter/asyncapi/rules/schema-property-naming) | error | | [server-hosts](/docs/linter/asyncapi/rules/server-hosts) | error | | [servers-defined](/docs/linter/asyncapi/rules/servers-defined) | error | | [spell-check](/docs/linter/asyncapi/rules/spell-check) | warning | | [standard-media-types](/docs/linter/asyncapi/rules/standard-media-types) | error | | [tag-description-defined](/docs/linter/asyncapi/rules/tag-description-defined) | warning | | [tags-sorted](/docs/linter/asyncapi/rules/tags-sorted) | error | | [tags-unique](/docs/linter/asyncapi/rules/tags-unique) | error | | [unused-shared-component](/docs/linter/asyncapi/rules/unused-shared-component) | error | --- # CloudEvents ruleset (AsyncAPI) Source: https://apigenie.pl/docs/linter/asyncapi/rulesets/cloudevents See also: [AsyncAPI linter rules](https://apigenie.pl/docs/linter/asyncapi.md), [Recommended ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/recommended.md), [Strict ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/strict.md), [All ruleset](https://apigenie.pl/docs/linter/asyncapi/rulesets/all.md). The rules of messages that are [CloudEvents](https://cloudevents.io): add the ruleset to another one (`extends: [recommended, cloudevents]`). A message is a CloudEvent in structured mode when its content type (its own, its traits', or `defaultContentType`) is `application/cloudevents+json`, and in binary mode when a header carries a context attribute with the prefix of a protocol binding (`ce_specversion`, `ce-id`, `cloudEvents:type`). ## Rules | Name | Severity | | ---- | -------- | | [cloudevents/attribute-schemas](/docs/linter/asyncapi/rules/cloudevents-attribute-schemas) | warning | | [cloudevents/binding-headers](/docs/linter/asyncapi/rules/cloudevents-binding-headers) | error | | [cloudevents/required-attributes](/docs/linter/asyncapi/rules/cloudevents-required-attributes) | error | --- # Swagger 2.0 linter rules Source: https://apigenie.pl/docs/linter/swagger See also: [Linter rules](https://apigenie.pl/docs/linter.md), [Recommended ruleset](https://apigenie.pl/docs/linter/swagger/rulesets/recommended.md), [Strict ruleset](https://apigenie.pl/docs/linter/swagger/rulesets/strict.md), [All ruleset](https://apigenie.pl/docs/linter/swagger/rulesets/all.md). The linter reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. ## Rulesets - [Recommended ruleset](/docs/linter/swagger/rulesets/recommended.md) - [Strict ruleset](/docs/linter/swagger/rulesets/strict.md) - [All ruleset](/docs/linter/swagger/rulesets/all.md) ## Rules | Rule | What it checks | Since | | --- | --- | --- | | [`audience-defined`](/docs/linter/swagger/rules/audience-defined.md) | This rule checks whether the intended audience of an API is declared in the `x-audience` extension of the info object of a Swagger 2.0 document. | 0.9.0 | | [`contact-defined`](/docs/linter/swagger/rules/contact-defined.md) | This rule checks whether complete contact information is present in a Swagger 2.0 document. | 0.9.0 | | [`host-defined`](/docs/linter/swagger/rules/host-defined.md) | This rule checks whether a Swagger 2.0 document declares the host that serves the API. | 0.9.0 | | [`id-defined`](/docs/linter/swagger/rules/id-defined.md) | This rule checks whether the info object of a Swagger 2.0 document has an identifier extension (`x-id` by default), and whether its value has the expected format (a UUID by default). | 0.9.0 | | [`info-defined`](/docs/linter/swagger/rules/info-defined.md) | This rule checks whether the info object of a Swagger 2.0 document provides a description and a version. | 0.9.0 | | [`license-defined`](/docs/linter/swagger/rules/license-defined.md) | This rule checks whether the licensing information is present in a Swagger 2.0 document. | 0.9.0 | | [`media-types-defined`](/docs/linter/swagger/rules/media-types-defined.md) | This rule checks whether the operations of a Swagger 2.0 document that send or receive a body declare its media types. | 0.9.0 | | [`no-content-response-defined`](/docs/linter/swagger/rules/no-content-response-defined.md) | This rule checks whether `204 No Content` responses of a Swagger 2.0 document declare a body. | 0.9.0 | | [`operation-description-defined`](/docs/linter/swagger/rules/operation-description-defined.md) | This rule checks whether every operation of a Swagger 2.0 document has a meaningful description. | 0.9.0 | | [`operation-id-defined`](/docs/linter/swagger/rules/operation-id-defined.md) | This rule checks whether every operation of a Swagger 2.0 document has an operation ID. | 0.9.0 | | [`operation-id-unique`](/docs/linter/swagger/rules/operation-id-unique.md) | This rule checks whether the operation IDs of a Swagger 2.0 document are unique. | 0.9.0 | | [`operation-rate-limiting-defined`](/docs/linter/swagger/rules/operation-rate-limiting-defined.md) | This rule checks whether the responses of Swagger 2.0 operations declare rate limiting headers. | 0.9.0 | | [`operation-security-defined`](/docs/linter/swagger/rules/operation-security-defined.md) | This rule checks whether every operation of a Swagger 2.0 document is covered by a security requirement. | 0.9.0 | | [`operation-success-response`](/docs/linter/swagger/rules/operation-success-response.md) | This rule checks whether every operation of a Swagger 2.0 document declares at least one success response. | 0.9.0 | | [`operation-tags-defined`](/docs/linter/swagger/rules/operation-tags-defined.md) | This rule checks whether every operation of a Swagger 2.0 document has at least one tag. | 0.9.0 | | [`parameter-description-defined`](/docs/linter/swagger/rules/parameter-description-defined.md) | This rule checks whether every parameter of a Swagger 2.0 document has a meaningful description. | 0.9.0 | | [`parameter-naming`](/docs/linter/swagger/rules/parameter-naming.md) | This rule checks whether parameter names of a Swagger 2.0 document follow a naming convention. | 0.9.0 | | [`parameters-unique`](/docs/linter/swagger/rules/parameters-unique.md) | This rule checks whether the parameter lists of a Swagger 2.0 document contain duplicates. | 0.9.0 | | [`path-parameters-defined`](/docs/linter/swagger/rules/path-parameters-defined.md) | This rule checks whether every parameter of a path template is declared as a path parameter. | 0.9.0 | | [`path-parameters-on-items`](/docs/linter/swagger/rules/path-parameters-on-items.md) | This rule checks whether path parameters are declared on path items rather than on individual operations. | 0.9.0 | | [`paths-max-count`](/docs/linter/swagger/rules/paths-max-count.md) | This rule checks whether a Swagger 2.0 document defines more paths than a configured maximum. | 0.9.0 | | [`paths-max-depth`](/docs/linter/swagger/rules/paths-max-depth.md) | This rule checks whether the paths of a Swagger 2.0 document are nested deeper than a configured maximum. | 0.9.0 | | [`paths-sorted`](/docs/linter/swagger/rules/paths-sorted.md) | This rule checks whether the paths of a Swagger 2.0 document are sorted. | 0.9.0 | | [`paths-unique`](/docs/linter/swagger/rules/paths-unique.md) | This rule checks whether a Swagger 2.0 document defines paths that are equivalent to each other. | 0.9.0 | | [`paths-well-formed`](/docs/linter/swagger/rules/paths-well-formed.md) | This rule checks whether the paths of a Swagger 2.0 document are well-formed. | 0.9.0 | | [`safe-markdown`](/docs/linter/swagger/rules/safe-markdown.md) | This rule ensures that the GFM descriptions of a Swagger 2.0 document do not contain unsafe constructs like `script` elements or `eval()` calls. | 0.9.0 | | [`schema-constraints`](/docs/linter/swagger/rules/schema-constraints.md) | This rule ensures that typed objects of a Swagger 2.0 document define constraints restricting the size of the underlying data. | 0.9.0 | | [`schema-datetime-suffix`](/docs/linter/swagger/rules/schema-datetime-suffix.md) | This rule ensures that the names of date and date-time properties end with a common suffix. | 0.9.0 | | [`schema-enum-naming`](/docs/linter/swagger/rules/schema-enum-naming.md) | This rule ensures that the string values of `enum` lists adhere to a predefined naming convention. | 0.9.0 | | [`schema-enum-no-duplicates`](/docs/linter/swagger/rules/schema-enum-no-duplicates.md) | This rule ensures that `enum` lists do not contain duplicate values. | 0.9.0 | | [`schema-enum-types`](/docs/linter/swagger/rules/schema-enum-types.md) | This rule ensures that all values of an `enum` list match the declared `type`. | 0.9.0 | | [`schema-example-defined`](/docs/linter/swagger/rules/schema-example-defined.md) | This rule ensures that the schemas of a Swagger 2.0 document provide examples. | 0.9.0 | | [`schema-format-defined`](/docs/linter/swagger/rules/schema-format-defined.md) | This rule ensures that numeric objects declare the size of their values with a `format`. | 0.9.0 | | [`schema-format-deprecated`](/docs/linter/swagger/rules/schema-format-deprecated.md) | This rule reports the formats which the OpenAPI format registry marks as deprecated from OpenAPI 3.1, and names what replaces them. | 0.10.0 | | [`schema-format-type-mismatch`](/docs/linter/swagger/rules/schema-format-type-mismatch.md) | This rule ensures that the `format` of an object is one that applies to its `type`. | 0.9.0 | | [`schema-format-unknown`](/docs/linter/swagger/rules/schema-format-unknown.md) | This rule reports a `format` of a Swagger 2.0 document which is neither in the OpenAPI format registry nor declared in `openapi.custom_formats` of the configuration file. | 0.10.0 | | [`schema-no-additional-properties`](/docs/linter/swagger/rules/schema-no-additional-properties.md) | This rule ensures that object schemas do not accept arbitrary additional properties. | 0.9.0 | | [`schema-property-naming`](/docs/linter/swagger/rules/schema-property-naming.md) | This rule ensures that the names of schema properties adhere to a predefined naming convention. | 0.9.0 | | [`schema-required-properties-defined`](/docs/linter/swagger/rules/schema-required-properties-defined.md) | This rule checks that every name listed in `required` is declared in `properties`. | 0.9.0 | | [`schemes-secure`](/docs/linter/swagger/rules/schemes-secure.md) | This rule checks whether a Swagger 2.0 document serves its API over secure transfer protocols only, and whether its host is written in lower case. | 0.9.0 | | [`spell-check`](/docs/linter/swagger/rules/spell-check.md) | This rule checks the spelling of the texts of a Swagger 2.0 document written for humans: titles, summaries and descriptions. | 0.9.0 | | [`standard-media-types`](/docs/linter/swagger/rules/standard-media-types.md) | This rule checks whether a Swagger 2.0 document uses only well-known media types. | 0.9.0 | | [`swagger-validation`](/docs/linter/swagger/rules/swagger-validation.md) | This rule reports violations of the Swagger 2.0 specification that span several objects, and therefore cannot be detected while a single object is read. | 0.9.0 | | [`tag-description-defined`](/docs/linter/swagger/rules/tag-description-defined.md) | This rule checks whether each tag declared in the root `tags` array of a Swagger 2.0 document has a meaningful description. | 0.9.0 | | [`tags-sorted`](/docs/linter/swagger/rules/tags-sorted.md) | This rule checks whether the tags in the root `tags` array of a Swagger 2.0 document are sorted by name. | 0.9.0 | | [`tags-unique`](/docs/linter/swagger/rules/tags-unique.md) | This rule checks whether the tags in the root `tags` array of a Swagger 2.0 document have unique names, comparing names case-insensitively. | 0.9.0 | | [`unused-request-body`](/docs/linter/swagger/rules/unused-request-body.md) | This rule checks whether `GET` and `HEAD` operations of a Swagger 2.0 document declare a request body. | 0.9.0 | | [`unused-shared-component`](/docs/linter/swagger/rules/unused-shared-component.md) | This rule checks whether every shared object of a Swagger 2.0 document is actually used. | 0.9.0 | --- # Recommended ruleset (Swagger 2.0) Source: https://apigenie.pl/docs/linter/swagger/rulesets/recommended See also: [Swagger 2.0 linter rules](https://apigenie.pl/docs/linter/swagger.md), [Strict ruleset](https://apigenie.pl/docs/linter/swagger/rulesets/strict.md), [All ruleset](https://apigenie.pl/docs/linter/swagger/rulesets/all.md). ## Rules | Name | Severity | | ---- | -------- | | [host-defined](/docs/linter/swagger/rules/host-defined) | warning | | [info-defined](/docs/linter/swagger/rules/info-defined) | error | | [media-types-defined](/docs/linter/swagger/rules/media-types-defined) | warning | | [no-content-response-defined](/docs/linter/swagger/rules/no-content-response-defined) | error | | [operation-description-defined](/docs/linter/swagger/rules/operation-description-defined) | error | | [operation-id-defined](/docs/linter/swagger/rules/operation-id-defined) | error | | [operation-id-unique](/docs/linter/swagger/rules/operation-id-unique) | error | | [operation-rate-limiting-defined](/docs/linter/swagger/rules/operation-rate-limiting-defined) | warning | | [operation-security-defined](/docs/linter/swagger/rules/operation-security-defined) | warning | | [operation-success-response](/docs/linter/swagger/rules/operation-success-response) | error | | [operation-tags-defined](/docs/linter/swagger/rules/operation-tags-defined) | warning | | [parameter-description-defined](/docs/linter/swagger/rules/parameter-description-defined) | warning | | [parameter-naming](/docs/linter/swagger/rules/parameter-naming) | warning | | [parameters-unique](/docs/linter/swagger/rules/parameters-unique) | error | | [path-parameters-defined](/docs/linter/swagger/rules/path-parameters-defined) | error | | [path-parameters-on-items](/docs/linter/swagger/rules/path-parameters-on-items) | warning | | [paths-max-count](/docs/linter/swagger/rules/paths-max-count) | warning | | [paths-max-depth](/docs/linter/swagger/rules/paths-max-depth) | warning | | [paths-well-formed](/docs/linter/swagger/rules/paths-well-formed) | warning | | [safe-markdown](/docs/linter/swagger/rules/safe-markdown) | warning | | [schema-constraints](/docs/linter/swagger/rules/schema-constraints) | warning | | [schema-datetime-suffix](/docs/linter/swagger/rules/schema-datetime-suffix) | warning | | [schema-enum-no-duplicates](/docs/linter/swagger/rules/schema-enum-no-duplicates) | error | | [schema-enum-types](/docs/linter/swagger/rules/schema-enum-types) | error | | [schema-example-defined](/docs/linter/swagger/rules/schema-example-defined) | warning | | [schema-format-defined](/docs/linter/swagger/rules/schema-format-defined) | error | | [schema-format-deprecated](/docs/linter/swagger/rules/schema-format-deprecated) | warning | | [schema-format-type-mismatch](/docs/linter/swagger/rules/schema-format-type-mismatch) | error | | [schema-no-additional-properties](/docs/linter/swagger/rules/schema-no-additional-properties) | error | | [schema-required-properties-defined](/docs/linter/swagger/rules/schema-required-properties-defined) | warning | | [schemes-secure](/docs/linter/swagger/rules/schemes-secure) | warning | | [standard-media-types](/docs/linter/swagger/rules/standard-media-types) | warning | | [swagger-validation](/docs/linter/swagger/rules/swagger-validation) | error | | [tag-description-defined](/docs/linter/swagger/rules/tag-description-defined) | warning | | [tags-unique](/docs/linter/swagger/rules/tags-unique) | warning | | [unused-request-body](/docs/linter/swagger/rules/unused-request-body) | warning | | [unused-shared-component](/docs/linter/swagger/rules/unused-shared-component) | warning | --- # Strict ruleset (Swagger 2.0) Source: https://apigenie.pl/docs/linter/swagger/rulesets/strict See also: [Swagger 2.0 linter rules](https://apigenie.pl/docs/linter/swagger.md), [Recommended ruleset](https://apigenie.pl/docs/linter/swagger/rulesets/recommended.md), [All ruleset](https://apigenie.pl/docs/linter/swagger/rulesets/all.md). ## Rules | Name | Severity | | ---- | -------- | | [audience-defined](/docs/linter/swagger/rules/audience-defined) | error | | [contact-defined](/docs/linter/swagger/rules/contact-defined) | error | | [host-defined](/docs/linter/swagger/rules/host-defined) | error | | [id-defined](/docs/linter/swagger/rules/id-defined) | error | | [info-defined](/docs/linter/swagger/rules/info-defined) | error | | [license-defined](/docs/linter/swagger/rules/license-defined) | error | | [media-types-defined](/docs/linter/swagger/rules/media-types-defined) | error | | [no-content-response-defined](/docs/linter/swagger/rules/no-content-response-defined) | error | | [operation-description-defined](/docs/linter/swagger/rules/operation-description-defined) | error | | [operation-id-defined](/docs/linter/swagger/rules/operation-id-defined) | error | | [operation-id-unique](/docs/linter/swagger/rules/operation-id-unique) | error | | [operation-rate-limiting-defined](/docs/linter/swagger/rules/operation-rate-limiting-defined) | warning | | [operation-security-defined](/docs/linter/swagger/rules/operation-security-defined) | warning | | [operation-success-response](/docs/linter/swagger/rules/operation-success-response) | error | | [operation-tags-defined](/docs/linter/swagger/rules/operation-tags-defined) | warning | | [parameter-description-defined](/docs/linter/swagger/rules/parameter-description-defined) | warning | | [parameter-naming](/docs/linter/swagger/rules/parameter-naming) | warning | | [parameters-unique](/docs/linter/swagger/rules/parameters-unique) | error | | [path-parameters-defined](/docs/linter/swagger/rules/path-parameters-defined) | error | | [path-parameters-on-items](/docs/linter/swagger/rules/path-parameters-on-items) | warning | | [paths-max-count](/docs/linter/swagger/rules/paths-max-count) | warning | | [paths-max-depth](/docs/linter/swagger/rules/paths-max-depth) | warning | | [paths-sorted](/docs/linter/swagger/rules/paths-sorted) | error | | [paths-unique](/docs/linter/swagger/rules/paths-unique) | error | | [paths-well-formed](/docs/linter/swagger/rules/paths-well-formed) | error | | [safe-markdown](/docs/linter/swagger/rules/safe-markdown) | error | | [schema-constraints](/docs/linter/swagger/rules/schema-constraints) | warning | | [schema-datetime-suffix](/docs/linter/swagger/rules/schema-datetime-suffix) | error | | [schema-enum-naming](/docs/linter/swagger/rules/schema-enum-naming) | error | | [schema-enum-no-duplicates](/docs/linter/swagger/rules/schema-enum-no-duplicates) | error | | [schema-enum-types](/docs/linter/swagger/rules/schema-enum-types) | error | | [schema-example-defined](/docs/linter/swagger/rules/schema-example-defined) | error | | [schema-format-defined](/docs/linter/swagger/rules/schema-format-defined) | error | | [schema-format-deprecated](/docs/linter/swagger/rules/schema-format-deprecated) | warning | | [schema-format-type-mismatch](/docs/linter/swagger/rules/schema-format-type-mismatch) | error | | [schema-format-unknown](/docs/linter/swagger/rules/schema-format-unknown) | warning | | [schema-no-additional-properties](/docs/linter/swagger/rules/schema-no-additional-properties) | error | | [schema-property-naming](/docs/linter/swagger/rules/schema-property-naming) | error | | [schema-required-properties-defined](/docs/linter/swagger/rules/schema-required-properties-defined) | error | | [schemes-secure](/docs/linter/swagger/rules/schemes-secure) | error | | [spell-check](/docs/linter/swagger/rules/spell-check) | warning | | [standard-media-types](/docs/linter/swagger/rules/standard-media-types) | error | | [swagger-validation](/docs/linter/swagger/rules/swagger-validation) | error | | [tag-description-defined](/docs/linter/swagger/rules/tag-description-defined) | warning | | [tags-sorted](/docs/linter/swagger/rules/tags-sorted) | error | | [tags-unique](/docs/linter/swagger/rules/tags-unique) | error | | [unused-request-body](/docs/linter/swagger/rules/unused-request-body) | error | | [unused-shared-component](/docs/linter/swagger/rules/unused-shared-component) | error | --- # All ruleset (Swagger 2.0) Source: https://apigenie.pl/docs/linter/swagger/rulesets/all See also: [Swagger 2.0 linter rules](https://apigenie.pl/docs/linter/swagger.md), [Recommended ruleset](https://apigenie.pl/docs/linter/swagger/rulesets/recommended.md), [Strict ruleset](https://apigenie.pl/docs/linter/swagger/rulesets/strict.md). ## Rules | Name | Severity | | ---- | -------- | | [audience-defined](/docs/linter/swagger/rules/audience-defined) | error | | [contact-defined](/docs/linter/swagger/rules/contact-defined) | error | | [host-defined](/docs/linter/swagger/rules/host-defined) | error | | [id-defined](/docs/linter/swagger/rules/id-defined) | error | | [info-defined](/docs/linter/swagger/rules/info-defined) | error | | [license-defined](/docs/linter/swagger/rules/license-defined) | error | | [media-types-defined](/docs/linter/swagger/rules/media-types-defined) | error | | [no-content-response-defined](/docs/linter/swagger/rules/no-content-response-defined) | error | | [operation-description-defined](/docs/linter/swagger/rules/operation-description-defined) | error | | [operation-id-defined](/docs/linter/swagger/rules/operation-id-defined) | error | | [operation-id-unique](/docs/linter/swagger/rules/operation-id-unique) | error | | [operation-rate-limiting-defined](/docs/linter/swagger/rules/operation-rate-limiting-defined) | error | | [operation-security-defined](/docs/linter/swagger/rules/operation-security-defined) | error | | [operation-success-response](/docs/linter/swagger/rules/operation-success-response) | error | | [operation-tags-defined](/docs/linter/swagger/rules/operation-tags-defined) | error | | [parameter-description-defined](/docs/linter/swagger/rules/parameter-description-defined) | error | | [parameter-naming](/docs/linter/swagger/rules/parameter-naming) | error | | [parameters-unique](/docs/linter/swagger/rules/parameters-unique) | error | | [path-parameters-defined](/docs/linter/swagger/rules/path-parameters-defined) | error | | [path-parameters-on-items](/docs/linter/swagger/rules/path-parameters-on-items) | error | | [paths-max-count](/docs/linter/swagger/rules/paths-max-count) | error | | [paths-max-depth](/docs/linter/swagger/rules/paths-max-depth) | error | | [paths-sorted](/docs/linter/swagger/rules/paths-sorted) | error | | [paths-unique](/docs/linter/swagger/rules/paths-unique) | error | | [paths-well-formed](/docs/linter/swagger/rules/paths-well-formed) | error | | [safe-markdown](/docs/linter/swagger/rules/safe-markdown) | error | | [schema-constraints](/docs/linter/swagger/rules/schema-constraints) | warning | | [schema-datetime-suffix](/docs/linter/swagger/rules/schema-datetime-suffix) | error | | [schema-enum-naming](/docs/linter/swagger/rules/schema-enum-naming) | error | | [schema-enum-no-duplicates](/docs/linter/swagger/rules/schema-enum-no-duplicates) | error | | [schema-enum-types](/docs/linter/swagger/rules/schema-enum-types) | error | | [schema-example-defined](/docs/linter/swagger/rules/schema-example-defined) | error | | [schema-format-defined](/docs/linter/swagger/rules/schema-format-defined) | error | | [schema-format-deprecated](/docs/linter/swagger/rules/schema-format-deprecated) | warning | | [schema-format-type-mismatch](/docs/linter/swagger/rules/schema-format-type-mismatch) | error | | [schema-format-unknown](/docs/linter/swagger/rules/schema-format-unknown) | warning | | [schema-no-additional-properties](/docs/linter/swagger/rules/schema-no-additional-properties) | error | | [schema-property-naming](/docs/linter/swagger/rules/schema-property-naming) | error | | [schema-required-properties-defined](/docs/linter/swagger/rules/schema-required-properties-defined) | error | | [schemes-secure](/docs/linter/swagger/rules/schemes-secure) | error | | [spell-check](/docs/linter/swagger/rules/spell-check) | warning | | [standard-media-types](/docs/linter/swagger/rules/standard-media-types) | error | | [swagger-validation](/docs/linter/swagger/rules/swagger-validation) | error | | [tag-description-defined](/docs/linter/swagger/rules/tag-description-defined) | warning | | [tags-sorted](/docs/linter/swagger/rules/tags-sorted) | error | | [tags-unique](/docs/linter/swagger/rules/tags-unique) | error | | [unused-request-body](/docs/linter/swagger/rules/unused-request-body) | error | | [unused-shared-component](/docs/linter/swagger/rules/unused-shared-component) | error | --- # GraphQL linter rules Source: https://apigenie.pl/docs/linter/graphql See also: [Linter rules](https://apigenie.pl/docs/linter.md), [Recommended ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/recommended.md), [Strict ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/strict.md), [All ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/all.md), [Relay ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/relay.md). The linter reads GraphQL schemas and operations. ## Rulesets - [Recommended ruleset](/docs/linter/graphql/rulesets/recommended.md) - [Strict ruleset](/docs/linter/graphql/rulesets/strict.md) - [All ruleset](/docs/linter/graphql/rulesets/all.md) - [Relay ruleset](/docs/linter/graphql/rulesets/relay.md) ## Rules | Rule | What it checks | Since | | --- | --- | --- | | [`argument-description-defined`](/docs/linter/graphql/rules/argument-description-defined.md) | This rule checks that the arguments of fields and directives have a description. | 0.9.0 | | [`argument-naming`](/docs/linter/graphql/rules/argument-naming.md) | This rule checks that the argument names follow a naming convention, camelCase by default. | 0.9.0 | | [`arguments-sorted`](/docs/linter/graphql/rules/arguments-sorted.md) | This rule checks that the arguments of field and directive definitions are in alphabetical order. | 0.9.0 | | [`custom-scalar-specified-by`](/docs/linter/graphql/rules/custom-scalar-specified-by.md) | This rule checks that custom scalars link their specification with `@specifiedBy`. | 0.9.0 | | [`deprecation-date-defined`](/docs/linter/graphql/rules/deprecation-date-defined.md) | This rule checks that `@deprecated` directives have a deletion date that has not passed. | 0.9.0 | | [`deprecation-reason-defined`](/docs/linter/graphql/rules/deprecation-reason-defined.md) | This rule checks that `@deprecated` directives have a reason. | 0.9.0 | | [`description-capitalized`](/docs/linter/graphql/rules/description-capitalized.md) | This rule checks that descriptions start with a capital letter. | 0.9.0 | | [`description-style`](/docs/linter/graphql/rules/description-style.md) | This rule checks that descriptions are written as block strings, or as single-line strings. | 0.9.0 | | [`directive-description-defined`](/docs/linter/graphql/rules/directive-description-defined.md) | This rule checks that directive definitions have a description. | 0.9.0 | | [`directive-naming`](/docs/linter/graphql/rules/directive-naming.md) | This rule checks that directive names follow a naming convention, camelCase by default. | 0.9.0 | | [`enum-value-description-defined`](/docs/linter/graphql/rules/enum-value-description-defined.md) | This rule checks that enum values have a description. | 0.9.0 | | [`enum-value-naming`](/docs/linter/graphql/rules/enum-value-naming.md) | This rule checks that enum value names follow a naming convention, CONST_CASE by default. | 0.9.0 | | [`enum-values-sorted`](/docs/linter/graphql/rules/enum-values-sorted.md) | This rule checks that the values of each enum type definition and extension are in alphabetical order. | 0.9.0 | | [`field-description-defined`](/docs/linter/graphql/rules/field-description-defined.md) | This rule checks that the fields of object and interface types have a description. | 0.9.0 | | [`field-naming`](/docs/linter/graphql/rules/field-naming.md) | This rule checks that the field names follow a naming convention, camelCase by default. | 0.9.0 | | [`fields-on-correct-type`](/docs/linter/graphql/rules/fields-on-correct-type.md) | This rule checks that the fields selected by operations are defined by their parent types. | 0.9.0 | | [`fields-sorted`](/docs/linter/graphql/rules/fields-sorted.md) | This rule checks that the fields of each object and interface type definition and extension are in alphabetical order. | 0.9.0 | | [`fragment-naming`](/docs/linter/graphql/rules/fragment-naming.md) | This rule checks that fragment names follow a naming convention, PascalCase by default. | 0.9.0 | | [`input-field-description-defined`](/docs/linter/graphql/rules/input-field-description-defined.md) | This rule checks that the fields of input object types have a description. | 0.9.0 | | [`input-field-naming`](/docs/linter/graphql/rules/input-field-naming.md) | This rule checks that the input field names follow a naming convention, camelCase by default. | 0.9.0 | | [`input-fields-sorted`](/docs/linter/graphql/rules/input-fields-sorted.md) | This rule checks that the fields of each input object type definition and extension are in alphabetical order. | 0.9.0 | | [`input-no-circular-non-null`](/docs/linter/graphql/rules/input-no-circular-non-null.md) | This rule checks that input object types don't reference themselves through non-null fields. | 0.9.0 | | [`input-output-types`](/docs/linter/graphql/rules/input-output-types.md) | This rule checks that arguments and input fields have input types, and fields have output types, as the GraphQL specification requires. | 0.9.0 | | [`input-type-suffix`](/docs/linter/graphql/rules/input-type-suffix.md) | This rule checks that input object type names end with a suffix, `Input` by default. | 0.9.0 | | [`interface-implementation`](/docs/linter/graphql/rules/interface-implementation.md) | This rule checks that object and interface types implement their interfaces with all their fields, compatible field types and matching arguments, as the GraphQL specification requires. | 0.9.0 | | [`known-argument-names`](/docs/linter/graphql/rules/known-argument-names.md) | This rule checks that the arguments given to fields and directives are defined by them. | 0.9.0 | | [`known-directive-locations`](/docs/linter/graphql/rules/known-directive-locations.md) | This rule checks that directives are used at one of the locations of their definition, as the GraphQL specification requires. | 0.9.0 | | [`known-fragment-names`](/docs/linter/graphql/rules/known-fragment-names.md) | This rule checks that fragment spreads name fragments of the document, as the GraphQL specification requires. | 0.9.0 | | [`known-types`](/docs/linter/graphql/rules/known-types.md) | This rule checks that the types referenced by type system definitions are built-in scalars or defined in the document, as the GraphQL specification requires. | 0.9.0 | | [`lone-anonymous-operation`](/docs/linter/graphql/rules/lone-anonymous-operation.md) | This rule checks that an anonymous operation is the only operation of the document, as the GraphQL specification requires. | 0.9.0 | | [`lone-executable-definition`](/docs/linter/graphql/rules/lone-executable-definition.md) | This rule checks that a document holds a single operation or fragment. | 0.9.0 | | [`lone-schema-definition`](/docs/linter/graphql/rules/lone-schema-definition.md) | This rule checks that a document has at most one schema definition, as the GraphQL specification requires. | 0.9.0 | | [`match-document-filename`](/docs/linter/graphql/rules/match-document-filename.md) | This rule checks that the file name of a document with one operation or fragment is the name of the definition. | 0.9.0 | | [`mutation-input-argument`](/docs/linter/graphql/rules/mutation-input-argument.md) | This rule checks that mutation fields take a single argument, `input`, of a non-null input object type. | 0.9.0 | | [`mutation-payload-suffix`](/docs/linter/graphql/rules/mutation-payload-suffix.md) | This rule checks that the result types of mutation fields end with a suffix, `Payload` by default. | 0.9.0 | | [`no-deprecated`](/docs/linter/graphql/rules/no-deprecated.md) | This rule checks that operations don't use deprecated fields, arguments and enum values. | 0.9.0 | | [`no-deprecated-required-argument`](/docs/linter/graphql/rules/no-deprecated-required-argument.md) | This rule checks that required arguments and input fields are not deprecated. | 0.9.0 | | [`no-fragment-cycles`](/docs/linter/graphql/rules/no-fragment-cycles.md) | This rule checks that fragments don't spread themselves, directly or indirectly, as the GraphQL specification requires. | 0.9.0 | | [`no-get-prefix-on-query-fields`](/docs/linter/graphql/rules/no-get-prefix-on-query-fields.md) | This rule checks that the fields of the query root type are not named `getSomething`. | 0.9.0 | | [`no-hashtag-description`](/docs/linter/graphql/rules/no-hashtag-description.md) | This rule checks that definitions are documented with descriptions rather than with `#` comments. | 0.9.0 | | [`no-mixed-definitions`](/docs/linter/graphql/rules/no-mixed-definitions.md) | This rule checks that a document holds either a schema or operations, not both. | 0.9.0 | | [`no-one-place-fragments`](/docs/linter/graphql/rules/no-one-place-fragments.md) | This rule checks that fragments are spread more than once in the document. | 0.9.0 | | [`no-root-type`](/docs/linter/graphql/rules/no-root-type.md) | This rule checks that the schema doesn't have the root operation types the configuration disallows. | 0.9.0 | | [`no-scalar-result-on-mutation`](/docs/linter/graphql/rules/no-scalar-result-on-mutation.md) | This rule checks that mutation fields return object types rather than scalars. | 0.9.0 | | [`no-type-suffix`](/docs/linter/graphql/rules/no-type-suffix.md) | This rule checks that type names don't end with a redundant suffix such as `Type` or `Enum`. | 0.9.0 | | [`no-typename-prefix`](/docs/linter/graphql/rules/no-typename-prefix.md) | This rule checks that field names don't start with the name of their type, as in `User.userId`. | 0.9.0 | | [`no-undefined-variables`](/docs/linter/graphql/rules/no-undefined-variables.md) | This rule checks that the variables used by an operation, including in the fragments it spreads, are defined by the operation, as the GraphQL specification requires. | 0.9.0 | | [`no-unused-fragments`](/docs/linter/graphql/rules/no-unused-fragments.md) | This rule checks that every fragment is spread by an operation, directly or through other fragments, as the GraphQL specification requires. | 0.9.0 | | [`no-unused-variables`](/docs/linter/graphql/rules/no-unused-variables.md) | This rule checks that the variables defined by an operation are used, as the GraphQL specification requires. | 0.9.0 | | [`one-field-subscriptions`](/docs/linter/graphql/rules/one-field-subscriptions.md) | This rule checks that subscriptions select a single root field, as the specification requires. | 0.9.0 | | [`oneof-fields-nullable`](/docs/linter/graphql/rules/oneof-fields-nullable.md) | This rule checks that the fields of `@oneOf` input object types are nullable and have no default value. | 0.9.0 | | [`operation-known-types`](/docs/linter/graphql/rules/operation-known-types.md) | This rule checks that the types of variables and the type conditions of fragments are types of the schema. | 0.9.0 | | [`operation-name-defined`](/docs/linter/graphql/rules/operation-name-defined.md) | This rule checks that operations have names. | 0.9.0 | | [`operation-name-suffix`](/docs/linter/graphql/rules/operation-name-suffix.md) | This rule checks that operation and fragment names don't end with a redundant suffix. | 0.9.0 | | [`operation-naming`](/docs/linter/graphql/rules/operation-naming.md) | This rule checks that operation names follow a naming convention, PascalCase by default. | 0.9.0 | | [`possible-type-extensions`](/docs/linter/graphql/rules/possible-type-extensions.md) | This rule checks that extended types have the same kind as their definition, as the GraphQL specification requires. | 0.9.0 | | [`query-root-defined`](/docs/linter/graphql/rules/query-root-defined.md) | This rule checks that the schema has a query root operation type. | 0.9.0 | | [`relay-arguments`](/docs/linter/graphql/rules/relay-arguments.md) | This rule checks that fields returning connections take the pagination arguments of the Relay Cursor Connections specification. | 0.9.0 | | [`relay-connection-types`](/docs/linter/graphql/rules/relay-connection-types.md) | This rule checks that connection types follow the Relay Cursor Connections specification. | 0.9.0 | | [`relay-edge-types`](/docs/linter/graphql/rules/relay-edge-types.md) | This rule checks that the edge types of connections follow the Relay Cursor Connections specification. | 0.9.0 | | [`relay-page-info`](/docs/linter/graphql/rules/relay-page-info.md) | This rule checks that a schema with connections has a `PageInfo` type as the Relay Cursor Connections specification defines it. | 0.9.0 | | [`require-selections`](/docs/linter/graphql/rules/require-selections.md) | This rule checks that selections of objects with an identifier select it. | 0.9.0 | | [`required-arguments-provided`](/docs/linter/graphql/rules/required-arguments-provided.md) | This rule checks that the required arguments of fields and directives are given. | 0.9.0 | | [`reserved-names`](/docs/linter/graphql/rules/reserved-names.md) | This rule checks that the names of types, fields, arguments, enum values and directives don't start with "__", as the GraphQL specification requires. | 0.9.0 | | [`root-fields-nullable`](/docs/linter/graphql/rules/root-fields-nullable.md) | This rule checks that the fields of the query and mutation root types are nullable. | 0.9.0 | | [`selection-set-depth`](/docs/linter/graphql/rules/selection-set-depth.md) | This rule checks that selection sets are nested at most 7 levels deep. | 0.9.0 | | [`selections-sorted`](/docs/linter/graphql/rules/selections-sorted.md) | This rule checks that the fields of each selection set of operations and fragments are in alphabetical order. | 0.9.0 | | [`spell-check`](/docs/linter/graphql/rules/spell-check.md) | This rule checks the spelling of descriptions and comments. | 0.9.0 | | [`strict-id-in-types`](/docs/linter/graphql/rules/strict-id-in-types.md) | This rule checks that object types have exactly one non-null identifier field, `id: ID!` by default. | 0.9.0 | | [`type-description-defined`](/docs/linter/graphql/rules/type-description-defined.md) | This rule checks that type definitions have a description. | 0.9.0 | | [`type-naming`](/docs/linter/graphql/rules/type-naming.md) | This rule checks that type names follow a naming convention, PascalCase by default. | 0.9.0 | | [`types-sorted`](/docs/linter/graphql/rules/types-sorted.md) | This rule checks that the type definitions of a document, and its directive definitions are in alphabetical order. | 0.9.0 | | [`unique-argument-definition-names`](/docs/linter/graphql/rules/unique-argument-definition-names.md) | This rule checks that the argument names of a field or directive definition are unique, as the GraphQL specification requires. | 0.9.0 | | [`unique-argument-names`](/docs/linter/graphql/rules/unique-argument-names.md) | This rule checks that the argument names of a field or directive are unique, as the GraphQL specification requires. | 0.9.0 | | [`unique-directive-names`](/docs/linter/graphql/rules/unique-directive-names.md) | This rule checks that directive names are unique, as the GraphQL specification requires. | 0.9.0 | | [`unique-directives-per-location`](/docs/linter/graphql/rules/unique-directives-per-location.md) | This rule checks that non-repeatable directives are used once per location, as the GraphQL specification requires. | 0.9.0 | | [`unique-enum-value-names`](/docs/linter/graphql/rules/unique-enum-value-names.md) | This rule checks that the values of an enum are unique across the enum and its extensions, as the GraphQL specification requires. | 0.9.0 | | [`unique-field-definition-names`](/docs/linter/graphql/rules/unique-field-definition-names.md) | This rule checks that the field names of a type are unique across the type and its extensions, as the GraphQL specification requires. | 0.9.0 | | [`unique-fragment-names`](/docs/linter/graphql/rules/unique-fragment-names.md) | This rule checks that fragment names are unique, as the GraphQL specification requires. | 0.9.0 | | [`unique-input-field-names`](/docs/linter/graphql/rules/unique-input-field-names.md) | This rule checks that the field names of an object value are unique, as the GraphQL specification requires. | 0.9.0 | | [`unique-operation-names`](/docs/linter/graphql/rules/unique-operation-names.md) | This rule checks that operation names are unique, as the GraphQL specification requires. | 0.9.0 | | [`unique-operation-types`](/docs/linter/graphql/rules/unique-operation-types.md) | This rule checks that each root operation type is defined once across the schema definition and its extensions, as the GraphQL specification requires. | 0.9.0 | | [`unique-type-names`](/docs/linter/graphql/rules/unique-type-names.md) | This rule checks that type names are unique, as the GraphQL specification requires. | 0.9.0 | | [`unique-variable-names`](/docs/linter/graphql/rules/unique-variable-names.md) | This rule checks that the variable names of an operation are unique, as the GraphQL specification requires. | 0.9.0 | | [`unreachable-types`](/docs/linter/graphql/rules/unreachable-types.md) | This rule checks that every type is reachable from the root operation types. | 0.9.0 | | [`unused-directive-definition`](/docs/linter/graphql/rules/unused-directive-definition.md) | This rule checks that the directives defined for schemas are applied in the document. | 0.9.0 | | [`variables-sorted`](/docs/linter/graphql/rules/variables-sorted.md) | This rule checks that the variable definitions of each operation are in alphabetical order. | 0.9.0 | --- # Recommended ruleset (GraphQL) Source: https://apigenie.pl/docs/linter/graphql/rulesets/recommended See also: [GraphQL linter rules](https://apigenie.pl/docs/linter/graphql.md), [Strict ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/strict.md), [All ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/all.md), [Relay ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/relay.md). The default ruleset of the GraphQL linter: the rules of the specification and the checks of operations against the schema are errors, naming and documentation conventions are warnings. It leaves out the rules that misfire on schemas split across files. ## Rules | Name | Severity | | ---- | -------- | | [argument-naming](/docs/linter/graphql/rules/argument-naming) | warning | | [deprecation-reason-defined](/docs/linter/graphql/rules/deprecation-reason-defined) | warning | | [directive-naming](/docs/linter/graphql/rules/directive-naming) | warning | | [enum-value-naming](/docs/linter/graphql/rules/enum-value-naming) | warning | | [field-naming](/docs/linter/graphql/rules/field-naming) | warning | | [fields-on-correct-type](/docs/linter/graphql/rules/fields-on-correct-type) | error | | [fragment-naming](/docs/linter/graphql/rules/fragment-naming) | warning | | [input-field-naming](/docs/linter/graphql/rules/input-field-naming) | warning | | [input-no-circular-non-null](/docs/linter/graphql/rules/input-no-circular-non-null) | error | | [input-output-types](/docs/linter/graphql/rules/input-output-types) | error | | [input-type-suffix](/docs/linter/graphql/rules/input-type-suffix) | warning | | [interface-implementation](/docs/linter/graphql/rules/interface-implementation) | error | | [known-argument-names](/docs/linter/graphql/rules/known-argument-names) | error | | [known-directive-locations](/docs/linter/graphql/rules/known-directive-locations) | error | | [known-fragment-names](/docs/linter/graphql/rules/known-fragment-names) | error | | [known-types](/docs/linter/graphql/rules/known-types) | error | | [lone-anonymous-operation](/docs/linter/graphql/rules/lone-anonymous-operation) | error | | [lone-schema-definition](/docs/linter/graphql/rules/lone-schema-definition) | error | | [no-deprecated](/docs/linter/graphql/rules/no-deprecated) | error | | [no-deprecated-required-argument](/docs/linter/graphql/rules/no-deprecated-required-argument) | error | | [no-fragment-cycles](/docs/linter/graphql/rules/no-fragment-cycles) | error | | [no-hashtag-description](/docs/linter/graphql/rules/no-hashtag-description) | warning | | [no-mixed-definitions](/docs/linter/graphql/rules/no-mixed-definitions) | error | | [no-typename-prefix](/docs/linter/graphql/rules/no-typename-prefix) | warning | | [no-undefined-variables](/docs/linter/graphql/rules/no-undefined-variables) | error | | [no-unused-fragments](/docs/linter/graphql/rules/no-unused-fragments) | error | | [no-unused-variables](/docs/linter/graphql/rules/no-unused-variables) | error | | [one-field-subscriptions](/docs/linter/graphql/rules/one-field-subscriptions) | error | | [oneof-fields-nullable](/docs/linter/graphql/rules/oneof-fields-nullable) | error | | [operation-known-types](/docs/linter/graphql/rules/operation-known-types) | error | | [operation-name-defined](/docs/linter/graphql/rules/operation-name-defined) | error | | [operation-naming](/docs/linter/graphql/rules/operation-naming) | warning | | [possible-type-extensions](/docs/linter/graphql/rules/possible-type-extensions) | error | | [required-arguments-provided](/docs/linter/graphql/rules/required-arguments-provided) | error | | [reserved-names](/docs/linter/graphql/rules/reserved-names) | error | | [selection-set-depth](/docs/linter/graphql/rules/selection-set-depth) | warning | | [type-naming](/docs/linter/graphql/rules/type-naming) | warning | | [unique-argument-definition-names](/docs/linter/graphql/rules/unique-argument-definition-names) | error | | [unique-argument-names](/docs/linter/graphql/rules/unique-argument-names) | error | | [unique-directive-names](/docs/linter/graphql/rules/unique-directive-names) | error | | [unique-directives-per-location](/docs/linter/graphql/rules/unique-directives-per-location) | error | | [unique-enum-value-names](/docs/linter/graphql/rules/unique-enum-value-names) | error | | [unique-field-definition-names](/docs/linter/graphql/rules/unique-field-definition-names) | error | | [unique-fragment-names](/docs/linter/graphql/rules/unique-fragment-names) | error | | [unique-input-field-names](/docs/linter/graphql/rules/unique-input-field-names) | error | | [unique-operation-names](/docs/linter/graphql/rules/unique-operation-names) | error | | [unique-operation-types](/docs/linter/graphql/rules/unique-operation-types) | error | | [unique-type-names](/docs/linter/graphql/rules/unique-type-names) | error | | [unique-variable-names](/docs/linter/graphql/rules/unique-variable-names) | error | --- # Strict ruleset (GraphQL) Source: https://apigenie.pl/docs/linter/graphql/rulesets/strict See also: [GraphQL linter rules](https://apigenie.pl/docs/linter/graphql.md), [Recommended ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/recommended.md), [All ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/all.md), [Relay ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/relay.md). Every recommended rule as an error, with descriptions, schema design, identifiers and spelling. ## Rules | Name | Severity | | ---- | -------- | | [argument-description-defined](/docs/linter/graphql/rules/argument-description-defined) | error | | [argument-naming](/docs/linter/graphql/rules/argument-naming) | error | | [custom-scalar-specified-by](/docs/linter/graphql/rules/custom-scalar-specified-by) | error | | [deprecation-reason-defined](/docs/linter/graphql/rules/deprecation-reason-defined) | error | | [description-capitalized](/docs/linter/graphql/rules/description-capitalized) | error | | [description-style](/docs/linter/graphql/rules/description-style) | error | | [directive-description-defined](/docs/linter/graphql/rules/directive-description-defined) | error | | [directive-naming](/docs/linter/graphql/rules/directive-naming) | error | | [enum-value-description-defined](/docs/linter/graphql/rules/enum-value-description-defined) | error | | [enum-value-naming](/docs/linter/graphql/rules/enum-value-naming) | error | | [field-description-defined](/docs/linter/graphql/rules/field-description-defined) | error | | [field-naming](/docs/linter/graphql/rules/field-naming) | error | | [fields-on-correct-type](/docs/linter/graphql/rules/fields-on-correct-type) | error | | [fragment-naming](/docs/linter/graphql/rules/fragment-naming) | error | | [input-field-description-defined](/docs/linter/graphql/rules/input-field-description-defined) | error | | [input-field-naming](/docs/linter/graphql/rules/input-field-naming) | error | | [input-no-circular-non-null](/docs/linter/graphql/rules/input-no-circular-non-null) | error | | [input-output-types](/docs/linter/graphql/rules/input-output-types) | error | | [input-type-suffix](/docs/linter/graphql/rules/input-type-suffix) | error | | [interface-implementation](/docs/linter/graphql/rules/interface-implementation) | error | | [known-argument-names](/docs/linter/graphql/rules/known-argument-names) | error | | [known-directive-locations](/docs/linter/graphql/rules/known-directive-locations) | error | | [known-fragment-names](/docs/linter/graphql/rules/known-fragment-names) | error | | [known-types](/docs/linter/graphql/rules/known-types) | error | | [lone-anonymous-operation](/docs/linter/graphql/rules/lone-anonymous-operation) | error | | [lone-schema-definition](/docs/linter/graphql/rules/lone-schema-definition) | error | | [mutation-input-argument](/docs/linter/graphql/rules/mutation-input-argument) | error | | [mutation-payload-suffix](/docs/linter/graphql/rules/mutation-payload-suffix) | error | | [no-deprecated](/docs/linter/graphql/rules/no-deprecated) | error | | [no-deprecated-required-argument](/docs/linter/graphql/rules/no-deprecated-required-argument) | error | | [no-fragment-cycles](/docs/linter/graphql/rules/no-fragment-cycles) | error | | [no-get-prefix-on-query-fields](/docs/linter/graphql/rules/no-get-prefix-on-query-fields) | error | | [no-hashtag-description](/docs/linter/graphql/rules/no-hashtag-description) | error | | [no-mixed-definitions](/docs/linter/graphql/rules/no-mixed-definitions) | error | | [no-scalar-result-on-mutation](/docs/linter/graphql/rules/no-scalar-result-on-mutation) | error | | [no-type-suffix](/docs/linter/graphql/rules/no-type-suffix) | error | | [no-typename-prefix](/docs/linter/graphql/rules/no-typename-prefix) | error | | [no-undefined-variables](/docs/linter/graphql/rules/no-undefined-variables) | error | | [no-unused-fragments](/docs/linter/graphql/rules/no-unused-fragments) | error | | [no-unused-variables](/docs/linter/graphql/rules/no-unused-variables) | error | | [one-field-subscriptions](/docs/linter/graphql/rules/one-field-subscriptions) | error | | [oneof-fields-nullable](/docs/linter/graphql/rules/oneof-fields-nullable) | error | | [operation-known-types](/docs/linter/graphql/rules/operation-known-types) | error | | [operation-name-defined](/docs/linter/graphql/rules/operation-name-defined) | error | | [operation-name-suffix](/docs/linter/graphql/rules/operation-name-suffix) | error | | [operation-naming](/docs/linter/graphql/rules/operation-naming) | error | | [possible-type-extensions](/docs/linter/graphql/rules/possible-type-extensions) | error | | [query-root-defined](/docs/linter/graphql/rules/query-root-defined) | error | | [require-selections](/docs/linter/graphql/rules/require-selections) | error | | [required-arguments-provided](/docs/linter/graphql/rules/required-arguments-provided) | error | | [reserved-names](/docs/linter/graphql/rules/reserved-names) | error | | [root-fields-nullable](/docs/linter/graphql/rules/root-fields-nullable) | error | | [selection-set-depth](/docs/linter/graphql/rules/selection-set-depth) | error | | [spell-check](/docs/linter/graphql/rules/spell-check) | warning | | [strict-id-in-types](/docs/linter/graphql/rules/strict-id-in-types) | error | | [type-description-defined](/docs/linter/graphql/rules/type-description-defined) | error | | [type-naming](/docs/linter/graphql/rules/type-naming) | error | | [unique-argument-definition-names](/docs/linter/graphql/rules/unique-argument-definition-names) | error | | [unique-argument-names](/docs/linter/graphql/rules/unique-argument-names) | error | | [unique-directive-names](/docs/linter/graphql/rules/unique-directive-names) | error | | [unique-directives-per-location](/docs/linter/graphql/rules/unique-directives-per-location) | error | | [unique-enum-value-names](/docs/linter/graphql/rules/unique-enum-value-names) | error | | [unique-field-definition-names](/docs/linter/graphql/rules/unique-field-definition-names) | error | | [unique-fragment-names](/docs/linter/graphql/rules/unique-fragment-names) | error | | [unique-input-field-names](/docs/linter/graphql/rules/unique-input-field-names) | error | | [unique-operation-names](/docs/linter/graphql/rules/unique-operation-names) | error | | [unique-operation-types](/docs/linter/graphql/rules/unique-operation-types) | error | | [unique-type-names](/docs/linter/graphql/rules/unique-type-names) | error | | [unique-variable-names](/docs/linter/graphql/rules/unique-variable-names) | error | | [unreachable-types](/docs/linter/graphql/rules/unreachable-types) | error | | [unused-directive-definition](/docs/linter/graphql/rules/unused-directive-definition) | error | --- # All ruleset (GraphQL) Source: https://apigenie.pl/docs/linter/graphql/rulesets/all See also: [GraphQL linter rules](https://apigenie.pl/docs/linter/graphql.md), [Recommended ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/recommended.md), [Strict ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/strict.md), [Relay ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/relay.md). Every rule of the GraphQL linter, as errors, except `spell-check` as a warning. Some rules report nothing until configured, e.g. `no-root-type`. ## Rules | Name | Severity | | ---- | -------- | | [argument-description-defined](/docs/linter/graphql/rules/argument-description-defined) | error | | [argument-naming](/docs/linter/graphql/rules/argument-naming) | error | | [arguments-sorted](/docs/linter/graphql/rules/arguments-sorted) | error | | [custom-scalar-specified-by](/docs/linter/graphql/rules/custom-scalar-specified-by) | error | | [deprecation-date-defined](/docs/linter/graphql/rules/deprecation-date-defined) | error | | [deprecation-reason-defined](/docs/linter/graphql/rules/deprecation-reason-defined) | error | | [description-capitalized](/docs/linter/graphql/rules/description-capitalized) | error | | [description-style](/docs/linter/graphql/rules/description-style) | error | | [directive-description-defined](/docs/linter/graphql/rules/directive-description-defined) | error | | [directive-naming](/docs/linter/graphql/rules/directive-naming) | error | | [enum-value-description-defined](/docs/linter/graphql/rules/enum-value-description-defined) | error | | [enum-value-naming](/docs/linter/graphql/rules/enum-value-naming) | error | | [enum-values-sorted](/docs/linter/graphql/rules/enum-values-sorted) | error | | [field-description-defined](/docs/linter/graphql/rules/field-description-defined) | error | | [field-naming](/docs/linter/graphql/rules/field-naming) | error | | [fields-on-correct-type](/docs/linter/graphql/rules/fields-on-correct-type) | error | | [fields-sorted](/docs/linter/graphql/rules/fields-sorted) | error | | [fragment-naming](/docs/linter/graphql/rules/fragment-naming) | error | | [input-field-description-defined](/docs/linter/graphql/rules/input-field-description-defined) | error | | [input-field-naming](/docs/linter/graphql/rules/input-field-naming) | error | | [input-fields-sorted](/docs/linter/graphql/rules/input-fields-sorted) | error | | [input-no-circular-non-null](/docs/linter/graphql/rules/input-no-circular-non-null) | error | | [input-output-types](/docs/linter/graphql/rules/input-output-types) | error | | [input-type-suffix](/docs/linter/graphql/rules/input-type-suffix) | error | | [interface-implementation](/docs/linter/graphql/rules/interface-implementation) | error | | [known-argument-names](/docs/linter/graphql/rules/known-argument-names) | error | | [known-directive-locations](/docs/linter/graphql/rules/known-directive-locations) | error | | [known-fragment-names](/docs/linter/graphql/rules/known-fragment-names) | error | | [known-types](/docs/linter/graphql/rules/known-types) | error | | [lone-anonymous-operation](/docs/linter/graphql/rules/lone-anonymous-operation) | error | | [lone-executable-definition](/docs/linter/graphql/rules/lone-executable-definition) | error | | [lone-schema-definition](/docs/linter/graphql/rules/lone-schema-definition) | error | | [match-document-filename](/docs/linter/graphql/rules/match-document-filename) | error | | [mutation-input-argument](/docs/linter/graphql/rules/mutation-input-argument) | error | | [mutation-payload-suffix](/docs/linter/graphql/rules/mutation-payload-suffix) | error | | [no-deprecated](/docs/linter/graphql/rules/no-deprecated) | error | | [no-deprecated-required-argument](/docs/linter/graphql/rules/no-deprecated-required-argument) | error | | [no-fragment-cycles](/docs/linter/graphql/rules/no-fragment-cycles) | error | | [no-get-prefix-on-query-fields](/docs/linter/graphql/rules/no-get-prefix-on-query-fields) | error | | [no-hashtag-description](/docs/linter/graphql/rules/no-hashtag-description) | error | | [no-mixed-definitions](/docs/linter/graphql/rules/no-mixed-definitions) | error | | [no-one-place-fragments](/docs/linter/graphql/rules/no-one-place-fragments) | error | | [no-root-type](/docs/linter/graphql/rules/no-root-type) | error | | [no-scalar-result-on-mutation](/docs/linter/graphql/rules/no-scalar-result-on-mutation) | error | | [no-type-suffix](/docs/linter/graphql/rules/no-type-suffix) | error | | [no-typename-prefix](/docs/linter/graphql/rules/no-typename-prefix) | error | | [no-undefined-variables](/docs/linter/graphql/rules/no-undefined-variables) | error | | [no-unused-fragments](/docs/linter/graphql/rules/no-unused-fragments) | error | | [no-unused-variables](/docs/linter/graphql/rules/no-unused-variables) | error | | [one-field-subscriptions](/docs/linter/graphql/rules/one-field-subscriptions) | error | | [oneof-fields-nullable](/docs/linter/graphql/rules/oneof-fields-nullable) | error | | [operation-known-types](/docs/linter/graphql/rules/operation-known-types) | error | | [operation-name-defined](/docs/linter/graphql/rules/operation-name-defined) | error | | [operation-name-suffix](/docs/linter/graphql/rules/operation-name-suffix) | error | | [operation-naming](/docs/linter/graphql/rules/operation-naming) | error | | [possible-type-extensions](/docs/linter/graphql/rules/possible-type-extensions) | error | | [query-root-defined](/docs/linter/graphql/rules/query-root-defined) | error | | [relay-arguments](/docs/linter/graphql/rules/relay-arguments) | error | | [relay-connection-types](/docs/linter/graphql/rules/relay-connection-types) | error | | [relay-edge-types](/docs/linter/graphql/rules/relay-edge-types) | error | | [relay-page-info](/docs/linter/graphql/rules/relay-page-info) | error | | [require-selections](/docs/linter/graphql/rules/require-selections) | error | | [required-arguments-provided](/docs/linter/graphql/rules/required-arguments-provided) | error | | [reserved-names](/docs/linter/graphql/rules/reserved-names) | error | | [root-fields-nullable](/docs/linter/graphql/rules/root-fields-nullable) | error | | [selection-set-depth](/docs/linter/graphql/rules/selection-set-depth) | error | | [selections-sorted](/docs/linter/graphql/rules/selections-sorted) | error | | [spell-check](/docs/linter/graphql/rules/spell-check) | warning | | [strict-id-in-types](/docs/linter/graphql/rules/strict-id-in-types) | error | | [type-description-defined](/docs/linter/graphql/rules/type-description-defined) | error | | [type-naming](/docs/linter/graphql/rules/type-naming) | error | | [types-sorted](/docs/linter/graphql/rules/types-sorted) | error | | [unique-argument-definition-names](/docs/linter/graphql/rules/unique-argument-definition-names) | error | | [unique-argument-names](/docs/linter/graphql/rules/unique-argument-names) | error | | [unique-directive-names](/docs/linter/graphql/rules/unique-directive-names) | error | | [unique-directives-per-location](/docs/linter/graphql/rules/unique-directives-per-location) | error | | [unique-enum-value-names](/docs/linter/graphql/rules/unique-enum-value-names) | error | | [unique-field-definition-names](/docs/linter/graphql/rules/unique-field-definition-names) | error | | [unique-fragment-names](/docs/linter/graphql/rules/unique-fragment-names) | error | | [unique-input-field-names](/docs/linter/graphql/rules/unique-input-field-names) | error | | [unique-operation-names](/docs/linter/graphql/rules/unique-operation-names) | error | | [unique-operation-types](/docs/linter/graphql/rules/unique-operation-types) | error | | [unique-type-names](/docs/linter/graphql/rules/unique-type-names) | error | | [unique-variable-names](/docs/linter/graphql/rules/unique-variable-names) | error | | [unreachable-types](/docs/linter/graphql/rules/unreachable-types) | error | | [unused-directive-definition](/docs/linter/graphql/rules/unused-directive-definition) | error | | [variables-sorted](/docs/linter/graphql/rules/variables-sorted) | error | --- # Relay ruleset (GraphQL) Source: https://apigenie.pl/docs/linter/graphql/rulesets/relay See also: [GraphQL linter rules](https://apigenie.pl/docs/linter/graphql.md), [Recommended ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/recommended.md), [Strict ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/strict.md), [All ruleset](https://apigenie.pl/docs/linter/graphql/rulesets/all.md). The rules of the Relay Cursor Connections specification. Use it with another ruleset, e.g. `extends: [recommended, relay]`. ## Rules | Name | Severity | | ---- | -------- | | [relay-arguments](/docs/linter/graphql/rules/relay-arguments) | error | | [relay-connection-types](/docs/linter/graphql/rules/relay-connection-types) | error | | [relay-edge-types](/docs/linter/graphql/rules/relay-edge-types) | error | | [relay-page-info](/docs/linter/graphql/rules/relay-page-info) | error | --- # Protobuf linter rules Source: https://apigenie.pl/docs/linter/protobuf See also: [Linter rules](https://apigenie.pl/docs/linter.md), [Recommended ruleset](https://apigenie.pl/docs/linter/protobuf/rulesets/recommended.md), [Strict ruleset](https://apigenie.pl/docs/linter/protobuf/rulesets/strict.md), [All ruleset](https://apigenie.pl/docs/linter/protobuf/rulesets/all.md). The linter reads proto3 files; the reader rejects proto2 and editions files. ## Rulesets - [Recommended ruleset](/docs/linter/protobuf/rulesets/recommended.md) - [Strict ruleset](/docs/linter/protobuf/rulesets/strict.md) - [All ruleset](/docs/linter/protobuf/rulesets/all.md) ## Rules | Rule | What it checks | Since | | --- | --- | --- | | [`directory-same-package`](/docs/linter/protobuf/rules/directory-same-package.md) | This rule checks whether all the `.proto` files of a directory declare the same package. | 0.9.0 | | [`enum-comment-defined`](/docs/linter/protobuf/rules/enum-comment-defined.md) | This rule checks whether every enum of a Protobuf file has a leading comment. | 0.9.0 | | [`enum-naming`](/docs/linter/protobuf/rules/enum-naming.md) | This rule checks whether the name of every enum of a Protobuf file is in `PascalCase`. | 0.9.0 | | [`enum-no-allow-alias`](/docs/linter/protobuf/rules/enum-no-allow-alias.md) | This rule checks whether any enum sets the `allow_alias` option. | 0.9.0 | | [`enum-value-comment-defined`](/docs/linter/protobuf/rules/enum-value-comment-defined.md) | This rule checks whether every enum value of a Protobuf file has a leading comment. | 0.9.0 | | [`enum-value-naming`](/docs/linter/protobuf/rules/enum-value-naming.md) | This rule checks whether the name of every enum value of a Protobuf file is in `UPPER_SNAKE_CASE`. | 0.9.0 | | [`enum-value-prefix`](/docs/linter/protobuf/rules/enum-value-prefix.md) | This rule checks whether the names of the values of every enum start with the name of the enum in `UPPER_SNAKE_CASE`, for example `PET_KIND_DOG` in the enum `PetKind`. | 0.9.0 | | [`enum-zero-value-suffix`](/docs/linter/protobuf/rules/enum-zero-value-suffix.md) | This rule checks whether the zero value of every enum ends with a suffix, `_UNSPECIFIED` by default. | 0.9.0 | | [`field-comment-defined`](/docs/linter/protobuf/rules/field-comment-defined.md) | This rule checks whether every field of a Protobuf file has a leading comment. | 0.9.0 | | [`field-naming`](/docs/linter/protobuf/rules/field-naming.md) | This rule checks whether the name of every field of a Protobuf file is in `lower_snake_case`. | 0.9.0 | | [`file-naming`](/docs/linter/protobuf/rules/file-naming.md) | This rule checks whether the name of every Protobuf file is in `lower_snake_case`, with the `.proto` extension. | 0.9.0 | | [`import-no-cycle`](/docs/linter/protobuf/rules/import-no-cycle.md) | This rule checks whether Protobuf files import each other in a cycle. | 0.9.0 | | [`import-no-public`](/docs/linter/protobuf/rules/import-no-public.md) | This rule checks whether a Protobuf file uses `import public`. | 0.9.0 | | [`import-no-weak`](/docs/linter/protobuf/rules/import-no-weak.md) | This rule checks whether a Protobuf file uses `import weak`. | 0.9.0 | | [`import-resolved`](/docs/linter/protobuf/rules/import-resolved.md) | This rule checks whether every file imported by a Protobuf file can be found. | 0.9.0 | | [`import-used`](/docs/linter/protobuf/rules/import-used.md) | This rule checks whether every file imported by a Protobuf file is actually used. | 0.9.0 | | [`imports-sorted`](/docs/linter/protobuf/rules/imports-sorted.md) | This rule checks whether the import statements of a Protobuf file are sorted by path. | 0.9.0 | | [`message-comment-defined`](/docs/linter/protobuf/rules/message-comment-defined.md) | This rule checks whether every message of a Protobuf file has a leading comment. | 0.9.0 | | [`message-naming`](/docs/linter/protobuf/rules/message-naming.md) | This rule checks whether the name of every message of a Protobuf file is in `PascalCase`. | 0.9.0 | | [`oneof-comment-defined`](/docs/linter/protobuf/rules/oneof-comment-defined.md) | This rule checks whether every oneof of a Protobuf file has a leading comment. | 0.9.0 | | [`oneof-naming`](/docs/linter/protobuf/rules/oneof-naming.md) | This rule checks whether the name of every oneof of a Protobuf file is in `lower_snake_case`. | 0.9.0 | | [`package-defined`](/docs/linter/protobuf/rules/package-defined.md) | This rule checks whether every Protobuf file declares a package. | 0.9.0 | | [`package-directory-match`](/docs/linter/protobuf/rules/package-directory-match.md) | This rule checks whether every Protobuf file is in the directory that corresponds to its package, for example `acme/pets/v1` for the package `acme.pets.v1`. | 0.9.0 | | [`package-naming`](/docs/linter/protobuf/rules/package-naming.md) | This rule checks whether the package name of a Protobuf file consists of `lower_snake_case` components separated by dots. | 0.9.0 | | [`package-no-import-cycle`](/docs/linter/protobuf/rules/package-no-import-cycle.md) | This rule checks whether packages import each other in a cycle. | 0.9.0 | | [`package-options-consistent`](/docs/linter/protobuf/rules/package-options-consistent.md) | This rule checks whether the files of a package set the same language-specific file options, such as `go_package` and `java_package`. | 0.9.0 | | [`package-same-directory`](/docs/linter/protobuf/rules/package-same-directory.md) | This rule checks whether all the files of a package are in the same directory. | 0.9.0 | | [`package-version-suffix`](/docs/linter/protobuf/rules/package-version-suffix.md) | This rule checks whether the last component of the package name of a Protobuf file is a version, such as `v1` or `v1beta2`. | 0.9.0 | | [`rpc-comment-defined`](/docs/linter/protobuf/rules/rpc-comment-defined.md) | This rule checks whether every RPC of a Protobuf file has a leading comment. | 0.9.0 | | [`rpc-naming`](/docs/linter/protobuf/rules/rpc-naming.md) | This rule checks whether the name of every RPC of a Protobuf file is in `PascalCase`. | 0.9.0 | | [`rpc-no-client-streaming`](/docs/linter/protobuf/rules/rpc-no-client-streaming.md) | This rule checks whether any RPC uses client streaming. | 0.9.0 | | [`rpc-no-server-streaming`](/docs/linter/protobuf/rules/rpc-no-server-streaming.md) | This rule checks whether any RPC uses server streaming. | 0.9.0 | | [`rpc-request-response-unique`](/docs/linter/protobuf/rules/rpc-request-response-unique.md) | This rule checks whether every message is used as the request or the response of a single RPC. | 0.9.0 | | [`rpc-request-standard-name`](/docs/linter/protobuf/rules/rpc-request-standard-name.md) | This rule checks whether the request type of every RPC is named after the RPC, for example `GetPetRequest` for the RPC `GetPet`. | 0.9.0 | | [`rpc-response-standard-name`](/docs/linter/protobuf/rules/rpc-response-standard-name.md) | This rule checks whether the response type of every RPC is named after the RPC, for example `GetPetResponse` for the RPC `GetPet`. | 0.9.0 | | [`service-comment-defined`](/docs/linter/protobuf/rules/service-comment-defined.md) | This rule checks whether every service of a Protobuf file has a leading comment. | 0.9.0 | | [`service-naming`](/docs/linter/protobuf/rules/service-naming.md) | This rule checks whether the name of every service of a Protobuf file is in `PascalCase`. | 0.9.0 | | [`service-suffix`](/docs/linter/protobuf/rules/service-suffix.md) | This rule checks whether the name of every service ends with a suffix, `Service` by default. | 0.9.0 | | [`spell-check`](/docs/linter/protobuf/rules/spell-check.md) | This rule checks the spelling of the comments of a Protobuf file. | 0.9.0 | --- # Recommended ruleset (Protobuf) Source: https://apigenie.pl/docs/linter/protobuf/rulesets/recommended See also: [Protobuf linter rules](https://apigenie.pl/docs/linter/protobuf.md), [Strict ruleset](https://apigenie.pl/docs/linter/protobuf/rulesets/strict.md), [All ruleset](https://apigenie.pl/docs/linter/protobuf/rulesets/all.md). The default ruleset of the Protobuf linter: structural problems are errors, style problems are warnings. ## Rules | Name | Severity | | ---- | -------- | | [directory-same-package](/docs/linter/protobuf/rules/directory-same-package) | error | | [enum-naming](/docs/linter/protobuf/rules/enum-naming) | warning | | [enum-no-allow-alias](/docs/linter/protobuf/rules/enum-no-allow-alias) | warning | | [enum-value-naming](/docs/linter/protobuf/rules/enum-value-naming) | warning | | [enum-value-prefix](/docs/linter/protobuf/rules/enum-value-prefix) | warning | | [enum-zero-value-suffix](/docs/linter/protobuf/rules/enum-zero-value-suffix) | warning | | [field-naming](/docs/linter/protobuf/rules/field-naming) | warning | | [file-naming](/docs/linter/protobuf/rules/file-naming) | warning | | [import-no-cycle](/docs/linter/protobuf/rules/import-no-cycle) | error | | [import-no-public](/docs/linter/protobuf/rules/import-no-public) | warning | | [import-no-weak](/docs/linter/protobuf/rules/import-no-weak) | warning | | [import-resolved](/docs/linter/protobuf/rules/import-resolved) | warning | | [import-used](/docs/linter/protobuf/rules/import-used) | warning | | [message-naming](/docs/linter/protobuf/rules/message-naming) | warning | | [oneof-naming](/docs/linter/protobuf/rules/oneof-naming) | warning | | [package-defined](/docs/linter/protobuf/rules/package-defined) | error | | [package-directory-match](/docs/linter/protobuf/rules/package-directory-match) | warning | | [package-naming](/docs/linter/protobuf/rules/package-naming) | warning | | [package-no-import-cycle](/docs/linter/protobuf/rules/package-no-import-cycle) | error | | [package-options-consistent](/docs/linter/protobuf/rules/package-options-consistent) | error | | [package-same-directory](/docs/linter/protobuf/rules/package-same-directory) | warning | | [rpc-comment-defined](/docs/linter/protobuf/rules/rpc-comment-defined) | warning | | [rpc-naming](/docs/linter/protobuf/rules/rpc-naming) | warning | | [rpc-request-response-unique](/docs/linter/protobuf/rules/rpc-request-response-unique) | warning | | [rpc-request-standard-name](/docs/linter/protobuf/rules/rpc-request-standard-name) | warning | | [rpc-response-standard-name](/docs/linter/protobuf/rules/rpc-response-standard-name) | warning | | [service-comment-defined](/docs/linter/protobuf/rules/service-comment-defined) | warning | | [service-naming](/docs/linter/protobuf/rules/service-naming) | warning | | [service-suffix](/docs/linter/protobuf/rules/service-suffix) | warning | --- # Strict ruleset (Protobuf) Source: https://apigenie.pl/docs/linter/protobuf/rulesets/strict See also: [Protobuf linter rules](https://apigenie.pl/docs/linter/protobuf.md), [Recommended ruleset](https://apigenie.pl/docs/linter/protobuf/rulesets/recommended.md), [All ruleset](https://apigenie.pl/docs/linter/protobuf/rulesets/all.md). The recommended rules as errors, plus versioned packages, sorted imports, comments on messages and enums, and spell checking of comments. ## Rules | Name | Severity | | ---- | -------- | | [directory-same-package](/docs/linter/protobuf/rules/directory-same-package) | error | | [enum-comment-defined](/docs/linter/protobuf/rules/enum-comment-defined) | error | | [enum-naming](/docs/linter/protobuf/rules/enum-naming) | error | | [enum-no-allow-alias](/docs/linter/protobuf/rules/enum-no-allow-alias) | error | | [enum-value-naming](/docs/linter/protobuf/rules/enum-value-naming) | error | | [enum-value-prefix](/docs/linter/protobuf/rules/enum-value-prefix) | error | | [enum-zero-value-suffix](/docs/linter/protobuf/rules/enum-zero-value-suffix) | error | | [field-naming](/docs/linter/protobuf/rules/field-naming) | error | | [file-naming](/docs/linter/protobuf/rules/file-naming) | error | | [import-no-cycle](/docs/linter/protobuf/rules/import-no-cycle) | error | | [import-no-public](/docs/linter/protobuf/rules/import-no-public) | error | | [import-no-weak](/docs/linter/protobuf/rules/import-no-weak) | error | | [import-resolved](/docs/linter/protobuf/rules/import-resolved) | error | | [import-used](/docs/linter/protobuf/rules/import-used) | error | | [imports-sorted](/docs/linter/protobuf/rules/imports-sorted) | error | | [message-comment-defined](/docs/linter/protobuf/rules/message-comment-defined) | error | | [message-naming](/docs/linter/protobuf/rules/message-naming) | error | | [oneof-naming](/docs/linter/protobuf/rules/oneof-naming) | error | | [package-defined](/docs/linter/protobuf/rules/package-defined) | error | | [package-directory-match](/docs/linter/protobuf/rules/package-directory-match) | error | | [package-naming](/docs/linter/protobuf/rules/package-naming) | error | | [package-no-import-cycle](/docs/linter/protobuf/rules/package-no-import-cycle) | error | | [package-options-consistent](/docs/linter/protobuf/rules/package-options-consistent) | error | | [package-same-directory](/docs/linter/protobuf/rules/package-same-directory) | error | | [package-version-suffix](/docs/linter/protobuf/rules/package-version-suffix) | error | | [rpc-comment-defined](/docs/linter/protobuf/rules/rpc-comment-defined) | error | | [rpc-naming](/docs/linter/protobuf/rules/rpc-naming) | error | | [rpc-request-response-unique](/docs/linter/protobuf/rules/rpc-request-response-unique) | error | | [rpc-request-standard-name](/docs/linter/protobuf/rules/rpc-request-standard-name) | error | | [rpc-response-standard-name](/docs/linter/protobuf/rules/rpc-response-standard-name) | error | | [service-comment-defined](/docs/linter/protobuf/rules/service-comment-defined) | error | | [service-naming](/docs/linter/protobuf/rules/service-naming) | error | | [service-suffix](/docs/linter/protobuf/rules/service-suffix) | error | | [spell-check](/docs/linter/protobuf/rules/spell-check) | warning | --- # All ruleset (Protobuf) Source: https://apigenie.pl/docs/linter/protobuf/rulesets/all See also: [Protobuf linter rules](https://apigenie.pl/docs/linter/protobuf.md), [Recommended ruleset](https://apigenie.pl/docs/linter/protobuf/rulesets/recommended.md), [Strict ruleset](https://apigenie.pl/docs/linter/protobuf/rulesets/strict.md). Every rule of the Protobuf linter. ## Rules | Name | Severity | | ---- | -------- | | [directory-same-package](/docs/linter/protobuf/rules/directory-same-package) | error | | [enum-comment-defined](/docs/linter/protobuf/rules/enum-comment-defined) | error | | [enum-naming](/docs/linter/protobuf/rules/enum-naming) | error | | [enum-no-allow-alias](/docs/linter/protobuf/rules/enum-no-allow-alias) | error | | [enum-value-comment-defined](/docs/linter/protobuf/rules/enum-value-comment-defined) | error | | [enum-value-naming](/docs/linter/protobuf/rules/enum-value-naming) | error | | [enum-value-prefix](/docs/linter/protobuf/rules/enum-value-prefix) | error | | [enum-zero-value-suffix](/docs/linter/protobuf/rules/enum-zero-value-suffix) | error | | [field-comment-defined](/docs/linter/protobuf/rules/field-comment-defined) | error | | [field-naming](/docs/linter/protobuf/rules/field-naming) | error | | [file-naming](/docs/linter/protobuf/rules/file-naming) | error | | [import-no-cycle](/docs/linter/protobuf/rules/import-no-cycle) | error | | [import-no-public](/docs/linter/protobuf/rules/import-no-public) | error | | [import-no-weak](/docs/linter/protobuf/rules/import-no-weak) | error | | [import-resolved](/docs/linter/protobuf/rules/import-resolved) | error | | [import-used](/docs/linter/protobuf/rules/import-used) | error | | [imports-sorted](/docs/linter/protobuf/rules/imports-sorted) | error | | [message-comment-defined](/docs/linter/protobuf/rules/message-comment-defined) | error | | [message-naming](/docs/linter/protobuf/rules/message-naming) | error | | [oneof-comment-defined](/docs/linter/protobuf/rules/oneof-comment-defined) | error | | [oneof-naming](/docs/linter/protobuf/rules/oneof-naming) | error | | [package-defined](/docs/linter/protobuf/rules/package-defined) | error | | [package-directory-match](/docs/linter/protobuf/rules/package-directory-match) | error | | [package-naming](/docs/linter/protobuf/rules/package-naming) | error | | [package-no-import-cycle](/docs/linter/protobuf/rules/package-no-import-cycle) | error | | [package-options-consistent](/docs/linter/protobuf/rules/package-options-consistent) | error | | [package-same-directory](/docs/linter/protobuf/rules/package-same-directory) | error | | [package-version-suffix](/docs/linter/protobuf/rules/package-version-suffix) | error | | [rpc-comment-defined](/docs/linter/protobuf/rules/rpc-comment-defined) | error | | [rpc-naming](/docs/linter/protobuf/rules/rpc-naming) | error | | [rpc-no-client-streaming](/docs/linter/protobuf/rules/rpc-no-client-streaming) | error | | [rpc-no-server-streaming](/docs/linter/protobuf/rules/rpc-no-server-streaming) | error | | [rpc-request-response-unique](/docs/linter/protobuf/rules/rpc-request-response-unique) | error | | [rpc-request-standard-name](/docs/linter/protobuf/rules/rpc-request-standard-name) | error | | [rpc-response-standard-name](/docs/linter/protobuf/rules/rpc-response-standard-name) | error | | [service-comment-defined](/docs/linter/protobuf/rules/service-comment-defined) | error | | [service-naming](/docs/linter/protobuf/rules/service-naming) | error | | [service-suffix](/docs/linter/protobuf/rules/service-suffix) | error | | [spell-check](/docs/linter/protobuf/rules/spell-check) | warning | --- # audience-defined Source: https://apigenie.pl/docs/linter/openapi/rules/audience-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Strict at error, All at error. This rule checks that `info` has an `x-audience` field, and that its value is one of `internal-team`, `internal-company`, `partner` and `public`. ## Rule details Who an API is for decides how much design review, documentation and lifecycle care it gets: an API shared with partners or published to everyone is held to a higher standard than one used by a single team. The audience has no place in the OpenAPI specification, so the rule looks for the `x-audience` extension of the info object. The rule reports `API audience (x-audience) is missing` when the field is absent, and `API audience (x-audience) has invalid value (...)` when it is not one of the four values: - `internal-team`: used by the team that owns it. - `internal-company`: used across the company. - `partner`: used by selected external clients. - `public`: available to everyone. ## Examples **Good**. The API says it is public. ```yaml openapi: 3.0.3 info: title: Orders version: 1.2.3 x-audience: public paths: {} ``` **Bad**. The value is not one of the four. ```yaml openapi: 3.0.3 info: title: Orders version: 1.2.3 x-audience: external paths: {} ``` --- # contact-defined Source: https://apigenie.pl/docs/linter/openapi/rules/contact-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Strict at error, All at error. This rule checks that `info.contact` is present, with a `name` and a `url` or an `email`. ## Rule details A client that hits a problem needs to know whom to ask. The contact object is where the OpenAPI specification puts that information, and a name alone is not enough to reach anyone. The rule reports `Contact object is missing`, `Contact name is missing or empty`, and, when neither is present, `Contact email is missing` and `Contact URL is missing`. Turn it off when the point of contact is known to every client and does not change. ## Examples **Good**. A team name and its Slack channel. ```yaml openapi: 3.1.0 info: title: Inventory version: 12.4.0 contact: name: team-one url: https://your-company.slack.com/archives/C0278047U8G paths: {} ``` **Bad**. Nobody to contact. ```yaml openapi: 3.1.0 info: title: Inventory version: 0.2.0 paths: {} ``` --- # id-defined Source: https://apigenie.pl/docs/linter/openapi/rules/id-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Strict at error, All at error. This rule checks that `info` has an identifier field, `x-id` by default, whose value is a UUID or matches a pattern of your own. ## Rule details Titles change, files move and two teams can call their API `Payments`. An identifier that never changes keeps an API traceable across versions and catalogs, and the OpenAPI specification has no field for one, so the rule looks for an extension of the info object. The rule reports `API identifier (x-id) is missing` when the field is absent or empty, and an issue when the value does not match the pattern. ## Configuration An object with two properties, both required when the object is given: - `attribute`: the name of the field; it has to start with `x-`. `x-id` by default. - `pattern`: `uuid`, or an ECMAScript regular expression the value has to match. `uuid` by default. **Configuration example**. The identifier is `x-ident`, a word of lower-case letters. ```yaml commands: lint: rules: id-defined: - error - attribute: x-ident pattern: "[a-z]+" ``` ## Examples **Good**. The file can be renamed, versioned or copied and the API stays the same one. ```yaml openapi: 3.0.3 info: title: Payments version: 1.2.8 x-id: 123e4567-e89b-12d3-a456-426614174000 paths: {} ``` **Bad**. No identifier. ```yaml openapi: 3.0.3 info: title: Payments version: 1.2.4 paths: {} ``` **Bad**. The value is not a UUID. ```yaml openapi: 3.0.3 info: title: Payments version: 1.2.8 x-id: 237849128738 paths: {} ``` ## Automatic fixes With the `uuid` pattern, `--fix` writes a new UUID v4 into a missing or invalid field. With a pattern of your own, nothing is fixed. --- # info-defined Source: https://apigenie.pl/docs/linter/openapi/rules/info-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that `info` has a non-empty `summary`, `description` and `version`. ## Rule details The info object is the first thing a reader of the document or of the generated documentation sees: the summary says what the API is in a line, the description says what it does and for whom, and the version says which contract the reader holds. The OpenAPI specification requires only `title` and `version`. The rule reports `Info summary is missing or empty`, `Info description is missing or empty` and `Info version is empty`. ## Examples **Good**. All three fields are present and say something. ```yaml openapi: 3.1.0 info: title: Orders summary: Orders of the web shop description: Creates, lists and cancels the orders placed in the web shop. version: 2.1.0 paths: {} ``` **Bad**. Only what the specification requires. ```yaml openapi: 3.1.0 info: title: Orders version: 2.1.0 paths: {} ``` --- # json-api/content-type Source: https://apigenie.pl/docs/linter/openapi/rules/json-api-content-type A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: JsonApi at error. This rule checks that every request body and response of the document declares the `application/vnd.api+json` media type. ## Rule details JSON:API clients and servers negotiate with the `application/vnd.api+json` media type; a document that declares `application/json` describes the same bytes, but hides that the API follows JSON:API from the tools that read it, and from the clients that send the `Accept` and `Content-Type` headers the specification requires. The rule reports `Request body media type is not application/vnd.api+json` and `Response media type is not application/vnd.api+json`. It is part of the `json-api` ruleset and meant for APIs that follow JSON:API; turn it off for the others. ## Examples **Good**. The response says it is a JSON:API document. ```yaml openapi: 3.1.0 info: title: Users version: 1.0.0 paths: /users: get: responses: "200": description: A list of users. content: application/vnd.api+json: schema: $ref: "#/components/schemas/UserListResponse" ``` **Bad**. A JSON:API document declared as plain JSON. ```yaml openapi: 3.1.0 info: title: Users version: 1.0.0 paths: /users: get: responses: "200": description: A list of users. content: application/json: schema: $ref: "#/components/schemas/UserListResponse" ``` ## Automatic fixes `--fix` renames a `content` entry that is the only one and is `application/json` to `application/vnd.api+json`, keeping the rest of the media type. A `content` map with several entries is left for you to decide. --- # json-api/resource-type-unique Source: https://apigenie.pl/docs/linter/openapi/rules/json-api-resource-type-unique A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: JsonApi at error. This rule checks that every resource object schema of the JSON:API responses declares its `type` as a `const` or a one-value `enum`, and that no two of them declare the same type. ## Rule details In JSON:API, a resource is identified by its `type` and `id`, so two resource schemas with the same type are the same resource to every client, and a client cannot tell which of the two shapes it receives. The rule reads the `data` and `included` members of every `application/vnd.api+json` response: the schema of the member, the items of an array and the branches of `anyOf` and `oneOf`, after references; a schema counts as a resource object when it declares properties. It reports `Resource object schema does not declare its type as a const or a one-value enum` and `Resource type '...' is the type of another resource object schema too`, the second on every schema after the first with that type. Request bodies are left out: the resource a client creates or updates is usually a schema of its own, without `id` or with fewer attributes, under the type of the resource the server returns. A resource object without a `type` property is left to [json-api/schema-validation](/docs/linter/openapi/rules/json-api-schema-validation). ## Examples **Good**. Two resources with distinct types, one as `const`, one as `enum`. ```yaml paths: /users: get: responses: "200": description: The users and their employers. content: application/vnd.api+json: schema: type: object properties: data: type: array items: $ref: "#/components/schemas/User" included: type: array items: $ref: "#/components/schemas/Employer" components: schemas: User: type: object properties: type: type: string const: user id: type: string Employer: type: object properties: type: type: string enum: [employer] id: type: string ``` **Bad**. With the same response, both resource schemas declare the type `person`. ```yaml components: schemas: User: type: object properties: type: type: string const: person id: type: string Employer: type: object properties: type: type: string enum: [person] id: type: string ``` --- # json-api/schema-validation Source: https://apigenie.pl/docs/linter/openapi/rules/json-api-schema-validation A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: JsonApi at error. This rule checks that the schemas of the JSON:API request bodies and responses describe JSON:API documents: a top-level object with `data`, `errors` or `meta`, and resource objects with `type` and `id`. ## Rule details A JSON:API document has a fixed shape, and a schema that departs from it (a bare array, a string) produces clients that cannot be JSON:API clients. The rule reads the schema of every `application/vnd.api+json` request body and response, with references followed and the parts of an `allOf` taken together, and reports: - `JSON:API document schema is not an object` when its `type` does not allow an object; - `JSON:API document schema declares none of data, errors and meta`, when it declares properties; - `JSON:API document schema declares member '...', which is not a top-level member of JSON:API` for a property other than `data`, `errors`, `meta`, `jsonapi`, `links` and `included`; - `JSON:API document schema requires both data and errors`; - `JSON:API errors member is not an array`; - `JSON:API resource object schema does not declare type` and, in responses and in `included`, `... does not declare id`, for each resource object of `data` and `included` (the schema of the member, the items of an array, the branches of `anyOf` and `oneOf`) that declares properties; - `JSON:API resource object schema declares member '...' outside attributes and relationships` for a property other than `type`, `id`, `lid`, `attributes`, `relationships`, `links` and `meta`. A property with a colon, the namespaced member of a JSON:API extension, is accepted everywhere. A schema without properties, such as a bare `type: object`, describes no members and passes. A schema shared by several operations is reported once. The rule is part of the `json-api` ruleset. ## Examples **Good**. The smallest document schema JSON:API allows. ```yaml paths: /users/current: get: responses: "200": description: The current user. content: application/vnd.api+json: schema: type: object properties: jsonapi: type: object data: type: object ``` **Bad**. A string is not a JSON:API document. ```yaml paths: /users/current: get: responses: "200": description: The current user. content: application/vnd.api+json: schema: type: string ``` --- # json-schema-validation Source: https://apigenie.pl/docs/linter/openapi/rules/json-schema-validation A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.5.0. In no ruleset. This rule validates the document against API Genie's own meta-schema of OpenAPI 3.0 or 3.1 and reports every violation the validator finds. ## Rule details The rule predates [openapi-json-schema-validation](/docs/linter/openapi/rules/openapi-json-schema-validation), which validates the document against the schemas published by the OpenAPI Initiative for OpenAPI 3.0, 3.1 and 3.2 and is in the `recommended` ruleset. This rule is in no ruleset and reports the issues of its validator as they come, without positions of its own; turn it on when you want a second opinion on a 3.0 or 3.1 document. ## Examples **Good**. A valid document. ```yaml openapi: 3.0.3 info: title: Sample API version: 1.0.0 paths: {} ``` **Bad**. `paths` is misspelled, so the document does not match the meta-schema. ```yaml openapi: 3.0.3 info: title: Sample API version: 1.0.0 path: {} ``` --- # license-defined Source: https://apigenie.pl/docs/linter/openapi/rules/license-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Strict at error, All at error. This rule checks that `info.license` is present, with a `name` and a `url` or an SPDX `identifier`. ## Rule details The license says on which terms the API and its description may be used, and a client that cannot find it has to ask. The OpenAPI specification makes the whole object optional. The rule reports `License object is missing`, `License name is empty`, `Both the license URL and identifier are missing or empty` and `License identifier is not a valid SPDX identifier`. Turn it off for APIs that never leave the team. ## Examples **Good**. A name and a link to the text. ```yaml openapi: 3.1.0 info: title: Inventory version: 1.0.0 license: name: Apache 2.0 url: https://your-company.com/api/LICENSE paths: {} ``` **Good**. A name and an SPDX identifier (OpenAPI 3.1 and later). ```yaml openapi: 3.1.0 info: title: Inventory version: 1.0.0 license: name: Apache 2.0 identifier: Apache-2.0 paths: {} ``` **Bad**. No license. ```yaml openapi: 3.1.0 info: title: Inventory version: 1.0.0 paths: {} ``` --- # no-content-response-defined Source: https://apigenie.pl/docs/linter/openapi/rules/no-content-response-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that no `204` response declares `content`. ## Rule details A 204 response has no body, by the HTTP specification. A document that gives one a schema promises clients something the server never sends, and generated clients wait for a body that does not come. The rule reports `204 response may not have a body defined`. ## Examples **Good**. The response says only what happened. ```yaml paths: /users/{id}: delete: responses: "204": description: User deleted. ``` **Bad**. A body on a 204 response. ```yaml paths: /users/{id}: delete: responses: "204": description: User deleted. content: application/json: schema: type: object ``` ## Automatic fixes `--fix` removes `content` from the `204` responses the rule reports. --- # openapi-json-schema-validation Source: https://apigenie.pl/docs/linter/openapi/rules/openapi-json-schema-validation A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at error, Strict at error, All at error. This rule validates the document against the JSON Schema the OpenAPI Initiative publishes for its version: OpenAPI 3.0, 3.1 or 3.2. ## Rule details A document that does not match the schema of its version has a typo, a field in the wrong place or a value of the wrong type, and every tool that reads it, this linter included, guesses at what was meant. The rule reports each violation at its position, with the message of the validator. Parts the reader skips, such as unknown properties, are checked too, also when they nest very deep or hold recursive YAML aliases. It also reports a schema's local `$ref` when its target does not exist. JSON Pointer fragments are resolved within the document, or within the nearest schema resource with an `$id`; named fragments use that resource's `$anchor` or `$dynamicAnchor`. Recursive references are valid. References in example values, defaults and extensions are data and are not checked. External references are not fetched or checked by this rule. ## Examples **Good**. The smallest valid document. ```yaml openapi: 3.0.0 info: title: Sample API version: 1.0.0 paths: {} ``` **Bad**. `path` is not a field of the OpenAPI object; `paths` was meant. ```yaml openapi: 3.0.0 info: title: Sample API version: 1.0.0 path: {} ``` --- # operation-description-defined Source: https://apigenie.pl/docs/linter/openapi/rules/operation-description-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that every operation has a `description` of at least 10 characters. ## Rule details The description is where an operation says what it does beyond its method and path: what the list is filtered by, what a delete does to related resources, which errors to expect. Generated documentation and clients show it; without it, the reader guesses. A placeholder such as `TBD` is shorter than the minimum and reported too. The rule reports `Operation has no meaningful description`. ## Configuration A positive integer: the minimal length of a description. 10 by default. **Configuration example**. Descriptions of at least 20 characters. ```yaml commands: lint: rules: operation-description-defined: - warning - 20 ``` ## Examples **Good**. The description says what the list holds and what can be done with it. ```yaml paths: /users: get: description: Returns a paged list of users, filtered and sorted by the query parameters. responses: "200": description: A page of users. ``` **Bad**. No description. ```yaml paths: /users: get: responses: "200": description: A page of users. ``` **Bad**. A placeholder. ```yaml paths: /users: get: description: TBD responses: "200": description: A page of users. ``` --- # operation-document-not-primitive Source: https://apigenie.pl/docs/linter/openapi/rules/operation-document-not-primitive A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Strict at warning, All at warning. This rule checks that every request body and response body is an object or an array, not a string, a number or a boolean. ## Rule details A primitive body cannot grow: a response that is a bare string has nowhere to put a second field when one is needed, so the change breaks every client. An object or an array names what it holds, takes new fields without a new version, and leaves room for an error shape next to the data. The rule looks at the schema of every media type of a request body or a response and reports `Operation request or response body is not an object or array` when the schema is missing or has neither `object` nor `array` among its types. The rule is in the `strict` and `all` rulesets. ## Examples **Good**. The body is an array of users. ```yaml paths: /users: get: responses: "200": description: A list of users. content: application/json: schema: type: array items: $ref: "#/components/schemas/User" ``` **Bad**. A string: a name, a message, or both? ```yaml paths: /users: get: responses: "200": description: A list of users. content: application/json: schema: type: string ``` --- # operation-id-defined Source: https://apigenie.pl/docs/linter/openapi/rules/operation-id-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that every operation has a non-empty `operationId`: those of paths, webhooks and the path items under `components`, and those of callbacks. ## Rule details The operation ID is the name of the operation everywhere outside the document: the function a generated client exposes, the handler a generated server asks you to implement, the anchor of the documentation, the key of a mock scenario. An operation without one gets a name made up by each tool, and the names differ. The rule reports `Operation ID is not defined`. An operation that several paths, webhooks, callbacks or components share through a `$ref` is one operation: it is reported once, and `--fix` names it after the first path that uses it, else the first webhook, else the first callback, else the component. ## Configuration An object with one optional property, `nonPathNaming`, which decides how `--fix` names the operations of webhooks, of callbacks and of the path items under `components`: `scope-prefix` (the default, `Webhook/...`), `path-like` (as for a path) or `scope-suffix` (`.../Webhook`). A callback operation is named after its callback, not after the runtime expression of its URL: the `post` of a callback `onEvent` becomes `postCallbackOnEvent`, `postOnEvent` or `postOnEventCallback`. Two callbacks of the same name, of different operations, are told apart by the numeric suffix below. ## Examples **Good**. The name says what the operation does. ```yaml paths: /users: get: operationId: listUsers responses: "200": description: A page of users. ``` **Bad**. No name; a client would call it `delete` and the path. ```yaml paths: /reservations/{id}: delete: responses: "204": description: The reservation is cancelled. ``` ## Automatic fixes `--fix` writes an ID made of the method and the path, with each placeholder as `By` and its name: `GET /users/{id}` becomes `getUsersById`. IDs already in the document are kept, and a generated ID that would repeat one gets a numeric suffix. --- # operation-id-unique Source: https://apigenie.pl/docs/linter/openapi/rules/operation-id-unique A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that no two operations share an `operationId`, callback operations included: the specification requires the ID to be unique among all operations of the API. Empty IDs are left to [operation-id-defined](/docs/linter/openapi/rules/operation-id-defined). ## Rule details Generated clients, servers, documentation and mocks address an operation by its ID; two operations with the same one collide in all of them, and a reader of the document cannot tell which of the two a reference means. The rule reports `Operation ID is not unique ...` on each repeat. An operation that several paths, webhooks, callbacks or components share through a `$ref` is one operation, not a repeat. ## Configuration An object with one optional property, `nonPathNaming`, which decides how `--fix` names the operations of webhooks, of callbacks and of the path items under `components`: `scope-prefix` (the default), `path-like` or `scope-suffix`, as in [operation-id-defined](/docs/linter/openapi/rules/operation-id-defined). ## Examples **Good**. Each operation has a name of its own. ```yaml paths: /users: get: operationId: listUsers responses: "200": description: A page of users. /users/{id}: get: operationId: getUser responses: "200": description: One user. ``` **Bad**. Two operations called `cancelDownload`. ```yaml paths: /downloads/{id}: patch: operationId: cancelDownload responses: "200": description: The download, now cancelled. delete: operationId: cancelDownload responses: "204": description: The download is removed. ``` ## Automatic fixes `--fix` keeps the first operation with the ID and gives the later ones an ID generated from their method and path, the way `operation-id-defined` does. --- # operation-rate-limiting-defined Source: https://apigenie.pl/docs/linter/openapi/rules/operation-rate-limiting-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at warning, All at warning. This rule checks that the responses of every operation declare the rate-limiting headers: `RateLimit-Limit`, `X-RateLimit-Limit` or `X-Rate-Limit-Limit` on every 2xx and 4xx response, and `Retry-After` on the `429` and `503` responses. ## Rule details A client that knows its quota and when to retry stays below the limit; one that does not learns about it from errors. Declaring the headers in the document tells client authors what to read and lets generated clients expose them. The rule reports `Missing rate limiting header` and `Missing Retry-After header` on the response. It is in no ruleset: turn it on when the API limits its clients. ## Examples **Good**. The quota on the success response, the delay on the `429` response. ```yaml paths: /users: get: responses: "200": description: A page of users. headers: RateLimit-Limit: description: Requests allowed per hour. schema: type: integer "429": description: Too many requests. headers: Retry-After: description: Seconds to wait before the next request. schema: type: integer ``` **Bad**. Nothing tells the client about the limit. ```yaml paths: /users: get: responses: "200": description: A page of users. ``` --- # operation-security-defined Source: https://apigenie.pl/docs/linter/openapi/rules/operation-security-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks that every operation has security requirements, its own or the document's. ## Rule details The security requirements tell a client how to authenticate, and generated clients, mocks and the validating proxy what to send and check. An operation with none is public as far as every tool is concerned, which is rarely what the server does. The rule reports `Security requirement is not defined` on an operation without `security` when the document has no top-level `security` either. An operation that resets the document's requirements with `security: []` is taken as meant public and is not reported. Turn the rule off for an API that restricts nothing. ## Examples **Good**. The operation inherits the document's requirement. ```yaml paths: /users: get: responses: "200": description: A page of users. security: - api_key: [] components: securitySchemes: api_key: type: apiKey in: header name: X-Api-Key ``` **Good**. The operation has a requirement of its own. ```yaml paths: /users: get: security: - api_key: [] responses: "200": description: A page of users. components: securitySchemes: api_key: type: apiKey in: header name: X-Api-Key ``` **Bad**. Neither the document nor the operation says how to authenticate. ```yaml paths: /users: get: responses: "200": description: A page of users. ``` --- # operation-success-response Source: https://apigenie.pl/docs/linter/openapi/rules/operation-success-response A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that every operation declares at least one 2xx or 3xx response, as a status code or as the `2XX` or `3XX` range. ## Rule details The success response is the one clients are written for: its status, its body and its headers are what a generated client returns and what a mock answers. An operation that declares only errors leaves the main case to guesswork. The rule reports `Operation must have at least one success response`. ## Examples **Good**. A status code. ```yaml paths: /users: get: responses: "200": description: A page of users. ``` **Good**. A range. ```yaml paths: /users: get: responses: 2XX: description: A page of users. ``` **Bad**. Only an error. ```yaml paths: /users: get: responses: "400": description: The query is invalid. ``` --- # operation-tags-declared Source: https://apigenie.pl/docs/linter/openapi/rules/operation-tags-declared A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.12.0. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that every tag an operation uses is declared in the document's `tags`. ## Rule details The top-level `tags` give each tag its description, its external docs and its place in the order; an undeclared tag has none of these. A tag that an operation uses and the document doesn't declare is often a typo of a declared tag. The rule reports `Tag "<name>" is not declared in the document's tags` on each operation, once for each entry of its `tags` that is not declared. A document without top-level `tags` gets a report for each tag of each operation. Turn the rule off for an API that does not declare its tags. ## Examples **Good**. The tag is declared. ```yaml tags: - name: pets description: Everything about your pets paths: /pets: get: tags: [pets] ``` **Bad**. `store` is used but not declared. ```yaml tags: - name: pets paths: /pets: get: tags: [pets, store] ``` ## Automatic fixes `--fix` adds each undeclared tag to `tags` by name only, once, in the order the operations use them, and creates `tags` when the document has none. `tag-description-defined` then reports each added tag until it has a description. When `tags-sorted` is on, the added tags go after the declared ones, so a second `--fix` sorts them. --- # operation-tags-defined Source: https://apigenie.pl/docs/linter/openapi/rules/operation-tags-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks that every operation has at least one tag. ## Rule details Tags group the operations of an API: documentation renders one section per tag, and generated clients put the operations of a tag in one class. An operation without a tag lands in a group of its own, named by each tool. The rule reports `Operation has no tags defined` when `tags` is missing or empty. Turn it off for an API that does not use tags. ## Examples **Good**. The operation belongs to the `Users` group. ```yaml paths: /users: get: tags: - Users responses: "200": description: A list of users. tags: - name: Users ``` **Bad**. The operation belongs to no group. ```yaml paths: /users: get: responses: "200": description: A list of users. tags: - name: Users ``` --- # parameter-description-defined Source: https://apigenie.pl/docs/linter/openapi/rules/parameter-description-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks that every parameter has a description of at least 10 characters that is not a placeholder. ## Rule details The name and the type of a parameter say what it holds; the description says what it does: which values are special, whether a filter is exact or prefix, how two parameters interact. Generated documentation shows it next to the parameter, and a client author reads it instead of trying. The rule reports `Parameter '...' has no meaningful description` when the description is missing, shorter than the minimum, white space only, or one of `TBD`, `TODO` and `FIXME`. ## Configuration A positive integer: the minimal length of a description. 10 by default. **Configuration example**. Descriptions of at least 20 characters. ```yaml commands: lint: rules: parameter-description-defined: - warning - 20 ``` ## Examples **Good**. The description says what the name does not. ```yaml paths: /users/{id}: get: parameters: - name: id in: path description: | The ID of the user, or `self` for the user the request is authenticated as. required: true schema: type: string ``` **Bad**. Nothing says that `self` is accepted. ```yaml paths: /users/{id}: get: parameters: - name: id in: path required: true schema: type: string ``` --- # parameter-naming Source: https://apigenie.pl/docs/linter/openapi/rules/parameter-naming A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks that parameter names follow one naming convention per location: `kebab-case` for query parameters, `Header-Case` for header parameters and `snake_case` for the others, unless configured otherwise. ## Rule details A client author who has seen one parameter should be able to spell the next: `page-size` and `pageSize` in the same API cost a lookup each time. The conventions the rule knows: - `CONST_CASE` (also `UPPER_CASE` and `SCREAMING_SNAKE_CASE`): `THIS_IS_CONST_CASE` - `camelCase`: `thisIsCamelCase`, acronyms allowed (`userID`) - `camelCaseStrict`: `thisIsCamelCase`, no two capitals in a row (`userId`) - `kebab-case`: `this-is-kebab-case` - `PascalCase`: `ThisIsPascalCase`, acronyms allowed (`HTTPServer`) - `PascalCaseStrict`: `ThisIsPascalCase`, no two capitals in a row (`HttpServer`) - `Header-Case`: `This-Is-Header-Case` - `snake_case`: `this_is_snake_case` The rule reports `Parameter should be named ...` with the name in the expected convention. ## Configuration A convention name, used for every location, or an object with a `default` convention and any of `path`, `query`, `header` and `cookie` overriding it. **Configuration example 1**. The two are the same: `PascalCase` everywhere. ```yaml commands: lint: rules: parameter-naming: - warning - PascalCase ``` ```yaml commands: lint: rules: parameter-naming: - warning - default: PascalCase ``` **Configuration example 2**. `snake_case` by default, `kebab-case` in the query string and `Header-Case` in headers. ```yaml commands: lint: rules: parameter-naming: - warning - default: snake_case query: kebab-case header: Header-Case ``` ## Examples **Good**. With the default configuration. ```yaml paths: /users/{user_id}: get: parameters: - name: user_id in: path required: true schema: type: string - name: page-size in: query schema: type: integer - name: X-Request-Id in: header schema: type: string ``` **Bad**. A query parameter in camel case. ```yaml paths: /users: get: parameters: - name: pageSize in: query schema: type: integer ``` --- # parameters-unique Source: https://apigenie.pl/docs/linter/openapi/rules/parameters-unique A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that no path item or operation declares two parameters with the same name and location. ## Rule details A name and a location identify a parameter: two declarations of `id` in the path are one parameter with two definitions, and each tool picks one of them. The same name in two locations, `id` in the path and `id` in the query, is two parameters and is allowed. The rule reports `Duplicate parameter name '...' in location '...'` on the later declaration. ## Examples **Good**. Two parameters, two names. ```yaml paths: /users/{id}: get: parameters: - name: id in: path description: The ID of the user to retrieve. required: true schema: type: string - name: with-relations in: query description: If true, also returns related resources. required: false schema: type: boolean ``` **Good**. The same name in two locations. ```yaml paths: /users/{id}: get: parameters: - name: id in: path description: The ID of the user to retrieve. required: true schema: type: string - name: id in: query description: Confusing, but allowed. required: false schema: type: boolean ``` **Bad**. `id` in the path twice, with two types. ```yaml paths: /users/{id}: get: parameters: - name: id in: path description: The ID of the user to retrieve. required: true schema: type: string - name: id in: path description: The ID of the user to retrieve. required: true schema: type: boolean ``` ## Automatic fixes `--fix` removes a later duplicate when its definition is identical to the first one. Duplicates that differ stay for you to merge. --- # patch-request-body-partial Source: https://apigenie.pl/docs/linter/openapi/rules/patch-request-body-partial A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that `PATCH` request bodies do not require properties. ## Rule details `PATCH` applies a partial modification to a resource (RFC 5789). With a merge patch (RFC 7396) the client sends only the properties to change, so none of them should be required. A `PATCH` body with required properties forces clients to resend values they do not want to change, which is what `PUT` is for. The rule checks object schemas of `PATCH` request bodies, including the properties required by their `allOf` members. `application/json-patch+json` bodies are skipped: they are arrays of operations, whose properties are rightly required. The rule reports `PATCH request body requires ...; partial updates should not require properties`. Many APIs use `PATCH` for an update whose only field is required, such as the body of a comment: list those properties in `allowedRequired`, or turn the rule off when `PATCH` does not mean a partial update in your API. ## Configuration An object with one optional property: - `allowedRequired`: names of properties which may be required, for example a version used for optimistic locking. Defaults to none. ```yaml commands: lint: rules: patch-request-body-partial: - warning - allowedRequired: [version] ``` ## Examples **Good**. Every property is optional. ```yaml paths: /users/{id}: patch: requestBody: content: application/merge-patch+json: schema: type: object properties: name: type: string email: type: string ``` **Bad**. Clients must send `name` even to change only `email`. ```yaml paths: /users/{id}: patch: requestBody: content: application/json: schema: type: object required: [name] properties: name: type: string email: type: string ``` --- # path-parameters-defined Source: https://apigenie.pl/docs/linter/openapi/rules/path-parameters-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that every `{placeholder}` of a path has a parameter with `in: path` and that name, on the path item or on each of its operations. ## Rule details A placeholder without a parameter has no type, no description and no `required: true`: generated clients cannot fill it, and generated servers and mocks cannot validate it. The rule reports `One or more path parameters are missing` on the path item or the operation. ## Configuration An object with one optional property, `defaultType`: the schema type `--fix` gives the parameters it adds, `string` by default. `null` turns the fix off. ## Examples **Good**. The placeholder has its parameter on the path item. ```yaml paths: /users/{userId}: parameters: - name: userId in: path required: true schema: type: string get: summary: Get a user by ID ``` **Bad**. `userId` is declared nowhere. ```yaml paths: /users/{userId}: get: summary: Get a user by ID ``` ## Automatic fixes `--fix` adds the missing parameters to the path item, with `in: path`, `required: true` and a schema of the configured type. --- # path-parameters-on-items Source: https://apigenie.pl/docs/linter/openapi/rules/path-parameters-on-items A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks that path parameters are declared on the path item, not repeated on each of its operations. ## Rule details A placeholder belongs to the path, so its parameter belongs to the path item: declared once, it applies to every operation, and a change to its type or description happens in one place. Declared on the operations, the copies drift apart. The rule reports `One or more path parameters are missing or not defined in path item`. ## Examples **Good**. One declaration for every operation of the path. ```yaml paths: /users/{userId}: parameters: - name: userId in: path required: true schema: type: string get: summary: Get a user by ID delete: summary: Delete a user by ID ``` **Bad**. The same parameter, once per operation. ```yaml paths: /users/{userId}: get: summary: Get a user by ID parameters: - name: userId in: path required: true schema: type: string delete: summary: Delete a user by ID parameters: - name: userId in: path required: true schema: type: string ``` --- # paths-max-count Source: https://apigenie.pl/docs/linter/openapi/rules/paths-max-count A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks that a document declares at most 8 paths, or the number configured. ## Rule details A document with many paths is several APIs in one file: a reader cannot keep it in view, and a change to one part is a release of all of them. The limit is a prompt to split the document along the lines of the resources, not a property of the server. The rule reports `Too many paths found (...), maximum number is ...` once, on the document. The default of 8 is low on purpose; set the limit that fits the API, or turn the rule off for an API that is one document by design. ## Configuration A positive integer: the number of paths allowed. 8 by default. **Configuration example**. Up to 20 paths. ```yaml commands: lint: rules: paths-max-count: - warning - 20 ``` ## Examples **Good**. Eight paths. ```yaml paths: /users: get: summary: Get all users /users/{userId}: get: summary: Get a user by ID /users/{userId}/posts: get: summary: Get a user's posts /posts: get: summary: Get all posts /posts/{postId}: get: summary: Get a post by ID /posts/{postId}/comments: get: summary: Get a post's comments /comments: get: summary: Get all comments /comments/{commentId}: get: summary: Get a comment by ID ``` **Bad**. Ten paths with the default limit. ```yaml paths: /users: get: summary: Get all users /users/{userId}: get: summary: Get a user by ID /users/{userId}/posts: get: summary: Get a user's posts /posts: get: summary: Get all posts /posts/{postId}: get: summary: Get a post by ID /posts/{postId}/comments: get: summary: Get a post's comments /comments: get: summary: Get all comments /comments/{commentId}: get: summary: Get a comment by ID /tags: get: summary: Get all tags /tags/{tagId}: get: summary: Get a tag by ID ``` --- # paths-max-depth Source: https://apigenie.pl/docs/linter/openapi/rules/paths-max-depth A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks that no path has more than 4 segments, or the number configured. A segment is the text between two slashes; `/users/{userId}/posts` has three. ## Rule details A path of six segments spells out a chain of ownership that the client must walk on every request, `/users/{userId}/posts/{postId}/comments/{commentId}`, when the last identifier alone names the resource. Shorter paths are easier to read, to route and to keep when the ownership changes. The rule reports `Path URL is too much nested (...)` on each path over the limit. ## Configuration A positive integer: the number of segments allowed. 4 by default. **Configuration example**. Up to 6 segments. ```yaml commands: lint: rules: paths-max-depth: - warning - 6 ``` ## Examples **Good**. Two segments. ```yaml paths: /users/{userId}: get: summary: Get a user by ID ``` **Bad**. Six segments with the default limit. ```yaml paths: /users/{userId}/posts/{postId}/comments/{commentId}: get: summary: Get a comment of a post of a user ``` --- # paths-sorted Source: https://apigenie.pl/docs/linter/openapi/rules/paths-sorted A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Strict at error, All at error. This rule checks that the paths of a document are in alphabetical order. ## Rule details A sorted `paths` section is a table of contents: the reader finds `/users/{id}` next to `/users` and sees at a glance which resources the API has. In the order of a byte comparison, a literal segment such as `/users/self` comes before a placeholder such as `/users/{id}`, which is also the order in which most routers try the routes. The rule reports `Paths are not sorted: ...` on each path that comes before its predecessor. ## Examples **Good**. `/products` before `/users`. ```yaml paths: /products: get: responses: "200": description: A list of products. /users: get: responses: "200": description: A list of users. ``` **Good**. The literal `/users/self` before the placeholder `/users/{id}`. ```yaml paths: /users/self: get: responses: "200": description: The current user. /users/{id}: get: responses: "200": description: The user with the given ID. ``` **Bad**. `/users/self` after `/users/{id}`. ```yaml paths: /users/{id}: get: responses: "200": description: The user with the given ID. /users/self: get: responses: "200": description: The current user. ``` ## Automatic fixes `--fix` reorders the path items. Nothing inside a path item changes. --- # paths-unique Source: https://apigenie.pl/docs/linter/openapi/rules/paths-unique A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Strict at error, All at error. This rule checks that no two paths match the same requests. Paths that differ only in the names of their placeholders, `/users/{id}` and `/users/{userId}`, are the same path. ## Rule details Two path items for one path are two sets of operations for the same requests: a router takes one of them, a documentation tool shows both, and a reader cannot tell which one the server runs. The rule reports `Duplicate path found` on the later path item. ## Examples **Good**. Two paths. ```yaml paths: /users/{userId}: get: summary: Get a user by ID /users/{userId}/posts: get: summary: Get a user's posts ``` **Bad**. The same path with two placeholder names. ```yaml paths: /users/{userId}: get: summary: Get a user by ID /users/{id}: get: summary: Get a user by ID ``` --- # paths-well-formed Source: https://apigenie.pl/docs/linter/openapi/rules/paths-well-formed A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that every path starts with one slash, ends without one, has no empty segment (`//`), no empty placeholder (`{}`) and no upper-case letter outside the placeholders. ## Rule details A path that breaks one of these joins badly with the server URL or matches nothing: `//users` is an absolute URL to a host called `users` in some clients, `/users/` and `/users` are two routes in most servers, and `{}` is a placeholder no parameter can declare. The rule reports `Path is not well-formed ...` on each such path. ## Examples **Good**. ```yaml paths: /users/{userId}: get: summary: Get a user by ID ``` **Bad**. A double slash, an empty placeholder and a trailing slash. ```yaml paths: //users/{}/: get: summary: Get a user by ID ``` ## Automatic fixes `--fix` adds the leading slash, collapses repeated slashes, removes the trailing slash and the empty placeholders, and lowercases the path outside the placeholders. --- # privacy/no-credentials-in-url Source: https://apigenie.pl/docs/linter/openapi/rules/privacy-no-credentials-in-url A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.11.0. In the rulesets: Privacy at error. This rule reports passwords, tokens, API keys and other credentials passed in path or query parameters, and API keys that a security scheme sends in the query string. ## Rule details URLs are not secret. Servers, load balancers and proxies log them, browsers keep them in their history and bookmarks, and they leak to other sites in the `Referer` header. A credential in a URL is a credential in all of these places (OWASP API Security Top 10 API2:2023 Broken Authentication, CWE-598). The rule looks at every `in: path` and `in: query` parameter, including the parameters of `components.parameters`, and reports: - a parameter whose name contains a credential term, in any naming convention: `password`, `passwd`, `secret`, `token` (`access_token`, `resetToken`, ...), `api key`, `private key`, `session id`, `auth`, `credentials`, `otp`, `pin`, `cvv`, and a few more; - a parameter whose schema has `format: password`; - an object parameter (`style: form`, `deepObject` or `content`) with such a property, since the serialization puts property names and values in the URL; - an `apiKey` security scheme with `in: query`. A term matches whole words of the name: `nextPageToken`, `continuation_token` and `author` are not reported, `pinCode` is. Names that describe a credential instead of holding it, where the term is followed by `id`, `name`, `type`, `status`, `count`, `expiry` and the like (`secret_name`, `signing_key_id`, `token_type_hint`), are not reported; `session_id` is. The OAuth 2.0 `authorization_code`, which the redirect carries in the query by design, is not reported either. When a URL is meant to be a short-lived capability (a pre-signed download link, a password reset link sent by e-mail), turn the rule off on that parameter with `x-apigenie-lint-disable`. The rule is in the `privacy` ruleset. ## Configuration An object with two optional properties: - `allow`: parameter and property names that are never reported, compared case-insensitively. - `terms`: more names to report, in any naming convention (`magicLink` also finds `magic_link`). ```yaml commands: lint: rules: privacy/no-credentials-in-url: - error - allow: [token] terms: [magicLink] ``` ## Examples **Good**. The token travels in the `Authorization` header. ```yaml components: securitySchemes: bearer: type: http scheme: bearer ``` **Bad**. Every request URL contains the key. ```yaml paths: /reports: get: parameters: - name: api_key in: query schema: type: string ``` --- # privacy/no-personal-data-in-url Source: https://apigenie.pl/docs/linter/openapi/rules/privacy-no-personal-data-in-url A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.11.0. In the rulesets: Privacy at warning. This rule reports personal data, such as e-mail addresses, names, dates of birth, phone numbers and national identification numbers, passed in path or query parameters. ## Rule details Personal data in a URL is copied to every access log, proxy, analytics tool and browser history on its way, mostly outside the retention and access controls that protect the data store. That works against data minimisation and integrity and confidentiality (GDPR Art. 5(1)(c) and (f)), data protection by design (Art. 25) and the security of processing (Art. 32), and makes erasure requests (Art. 17) hard to honour. The rule looks at every `in: path` and `in: query` parameter, including the parameters of `components.parameters`, and reports: - a parameter whose name contains a personal data term, in any naming convention: `email`, `phone`, `msisdn`, `first name`, `last name`, `surname`, `date of birth`, `dob`, `ssn`, `national id`, `tax id`, `passport`, `iban`, `card number`, `street address`, `ip address`, and more; - special categories of personal data (Art. 9) and criminal records (Art. 10): `health`, `diagnosis`, `religion`, `ethnicity`, `sexual orientation`, `biometric`, `genetic`, `criminal record`; - a parameter whose schema has `format: email` or `format: idn-email`; - an object parameter (`style: form`, `deepObject` or `content`) with such a property. A term matches whole words of the name, so `name` or `country` alone are not reported, while `customerEmail` and `LAST_NAME` are. A term followed by `type`, `status`, `verified`, `count` or `format` describes the data rather than holding it (`email_verified`) and is not reported. Credentials are reported by `privacy/no-credentials-in-url`. In a path, identify the resource by an opaque identifier (`/customers/{customerId}`, not `/customers/{email}`). For a search by personal data, send the criteria in the body of a `POST` (`POST /customers/search`) or, where the API supports it, of a `QUERY` request. For data that the API publishes on purpose (a public author directory), allow the names or turn the rule off on the parameter with `x-apigenie-lint-disable`. The rule is in the `privacy` ruleset. ## Configuration An object with two optional properties: - `allow`: parameter and property names that are never reported, compared case-insensitively. - `terms`: more names to report, in any naming convention (`loyalty card` also finds `loyaltyCardNo`). ```yaml commands: lint: rules: privacy/no-personal-data-in-url: - warning - allow: [phone] terms: [loyalty card] ``` ## Examples **Good**. The search criteria are in the request body. ```yaml paths: /customers/search: post: requestBody: content: application/json: schema: type: object properties: email: type: string format: email ``` **Bad**. The e-mail address is part of the URL. ```yaml paths: /customers: get: parameters: - name: email in: query schema: type: string ``` --- # ref-no-siblings Source: https://apigenie.pl/docs/linter/openapi/rules/ref-no-siblings A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.12.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that, in an OpenAPI 3.0 document, no property other than an extension sits next to the `$ref` of a Reference Object. ## Rule details In OpenAPI 3.0, an object with `$ref` is replaced by the object it refers to: any other property next to `$ref` is ignored. A `description` or a `nullable: true` next to `$ref` does not apply: the specification says to ignore it, and tools that follow it do so without a message. OpenAPI 3.1 allows a `summary` and a `description` next to `$ref` in a Reference Object, and any keyword next to `$ref` in a schema. The rule checks 3.0 documents only: in 3.1 and 3.2 it does not report the other keys a Reference Object ignores. The rule reports `"<property>" next to $ref is ignored in OpenAPI 3.0` on each such property. Specification extensions (`x-...`) are not reported. A Path Item Object's `$ref` is not checked: OpenAPI 3.0 allows fields next to it. A `$ref` key in data is not a reference. Data are the values of `example`, `default` and `enum`, of a schema's `examples` list, of an Example Object's `value`, of a Link Object's `parameters` and `requestBody`, and of extensions. A YAML alias is checked where its anchor stands, once. Turn the rule off when every tool that reads the document applies the properties next to `$ref`. To keep a description with a reference in 3.0, wrap the reference in `allOf`: ```yaml Pet: description: A pet allOf: - $ref: '#/components/schemas/Animal' ``` ## Examples **Good**. ```yaml openapi: 3.0.3 components: schemas: Pet: $ref: '#/components/schemas/Animal' ``` **Bad**. The description is ignored. ```yaml openapi: 3.0.3 components: schemas: Pet: $ref: '#/components/schemas/Animal' description: A pet ``` --- # safe-markdown Source: https://apigenie.pl/docs/linter/openapi/rules/safe-markdown A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that no description contains a `<script>` tag or an `eval()` call. ## Rule details Descriptions are CommonMark, and CommonMark allows raw HTML, so a description is rendered as-is by every documentation page built from the document. A script in it runs in the browser of every reader of that page, with the page's cookies and origin. The rule reports `Markdown contains <script> tag` and `Markdown contains eval() function` on the object whose description has them. ## Examples **Good**. Prose. ```yaml components: schemas: User: type: object description: A user of the system. ``` **Bad**. A script in the description. ```yaml components: schemas: User: type: object description: "A user of the system. <script>alert('Unsafe')</script>" ``` ## Automatic fixes `--fix` escapes the delimiters of the script elements and `eval()` calls it finds, so they render as text. Code spans and fenced code blocks are left as they are, and so is the rest of the Markdown. --- # schema-conditional-effective Source: https://apigenie.pl/docs/linter/openapi/rules/schema-conditional-effective A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that `if`, `then` and `else` in schemas have an effect. ## Rule details JSON Schema applies `then` to values matching `if` and `else` to the other values. Several combinations silently do nothing, usually because of a typo or a keyword placed at the wrong level: - `then` or `else` without `if` is ignored. - `if` without `then` and `else` has no effect. - `else` never applies when `if` accepts every value, e.g. `if: {}` or an `if` with only a `description`; `then` never applies when `if` is `false`. - `then` or `else` accepting every value (e.g. `{}`) has no effect. References are followed, so `if: {$ref: ...}` is checked against the referenced schema. The rule applies to OpenAPI 3.1 and later, where `if`, `then` and `else` are schema keywords; OpenAPI 3.0 documents are skipped. ## Examples **Good**. Card payments require a card number, the others an IBAN. ```yaml components: schemas: Payment: type: object if: properties: kind: const: card then: required: [cardNumber] else: required: [iban] ``` **Bad**. `then` is ignored because the schema has no `if`. ```yaml components: schemas: Payment: type: object then: required: [cardNumber] ``` --- # schema-constraints Source: https://apigenie.pl/docs/linter/openapi/rules/schema-constraints A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at warning, All at warning. This rule checks that every schema bounds the size of its values: a minimum and a maximum for integers and numbers, a length, format, pattern or enum for strings, a maximum size for arrays, a maximum number of properties or `additionalProperties: false` for objects. ## Rule details A schema without bounds accepts a 2 GB string in a name and an array of a million items in a request: the server that stores them is the first to find out. Bounds in the document are checked by validators and mocks, and generated clients and servers pick the right types. The rule reports, by type: - `Integer schema does not define constraints restricting its range` and `Numeric schema does not define constraints restricting its range`: no `minimum` or `exclusiveMinimum`, or no `maximum` or `exclusiveMaximum`. - `String schema does not define constraints restricting its length`: no `maxLength`, `format`, `pattern` or `enum`. - `Array schema does not define constraints restricting its size`: no `maxItems`. - `Object schema does not define constraints restricting its size`: no `maxProperties` and no `additionalProperties: false`. ## Configuration An object whose properties are the types to check, `integer`, `number`, `string`, `array` and `object`, each `true` or `false`. At least one must be `true`. Every type is checked by default. **Configuration example**. Arrays and objects only. ```yaml commands: lint: rules: schema-constraints: - warning - array: true object: true ``` ## Examples **Good**. Every value is bounded. ```yaml components: schemas: User: type: object properties: username: type: string maxLength: 20 pattern: "^[a-z0-9_-]{3,16}$" roles: type: array items: type: string maxItems: 5 age: type: integer minimum: 18 maximum: 100 maxProperties: 3 ``` **Bad**. A username of any length, any number of roles, any age. ```yaml components: schemas: User: type: object properties: username: type: string roles: type: array items: type: string age: type: integer ``` --- # schema-datetime-suffix Source: https://apigenie.pl/docs/linter/openapi/rules/schema-datetime-suffix A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that the name of every property with the `date`, `date-time` or `time` format ends with `_at`, or with the suffix configured. ## Rule details A reader of `created_at` knows it is a point in time without looking at the schema, and knows that `created` next to it is something else, a flag perhaps. One suffix for every date and time in the API makes the names say their type. The rule looks at the properties of object schemas and reports `Property name ... should end with ...`. ## Configuration A non-empty string: the suffix. `_at` by default. Pick the suffix that fits the naming convention of your properties: `At` for camel case (`createdAt`), `_at` for snake case. **Configuration example**. Camel-case properties. ```yaml commands: lint: rules: schema-datetime-suffix: - warning - At ``` ## Examples **Good**. With the default suffix. ```yaml components: schemas: User: type: object properties: created_at: type: string format: date-time ``` **Bad**. Nothing in the name says it is a date. ```yaml components: schemas: User: type: object properties: creation: type: string format: date-time ``` --- # schema-discriminator-defined Source: https://apigenie.pl/docs/linter/openapi/rules/schema-discriminator-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that every schema with `oneOf` has a `discriminator`. ## Rule details Without a discriminator, a tool that reads a value against `oneOf` validates it against every alternative and keeps the one that matches, which is slow, which fails when two alternatives match, and which generated code in most languages cannot do at all. With `discriminator`, one property names the alternative, and a generated client deserializes into the right type. The rule reports `Schema with oneOf clause does not have a discriminator`. ## Examples **Good**. `petType` names the alternative. ```yaml components: schemas: Pet: type: object discriminator: propertyName: petType oneOf: - $ref: "#/components/schemas/Cat" - $ref: "#/components/schemas/Dog" ``` **Bad**. Whether a pet is a cat or a dog is found by trial. ```yaml components: schemas: Pet: type: object oneOf: - $ref: "#/components/schemas/Cat" - $ref: "#/components/schemas/Dog" ``` ## Automatic fixes `--fix` adds `discriminator.propertyName` when every alternative of the `oneOf` has one property in common with a distinct `const` value in each. Every other case stays for you to decide. --- # schema-enum-naming Source: https://apigenie.pl/docs/linter/openapi/rules/schema-enum-naming A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Strict at error, All at error. This rule checks that the string values of `enum` and `const` follow one naming convention, `CONST_CASE` (`ACTIVE_USER`) unless configured otherwise. ## Rule details Enum values are spelled by clients, in code and in requests, so a client author who has seen one should be able to spell the next. `activeStatus` next to `inactive_status` and `BLOCKED_STATUS` needs a lookup for each. The conventions the rule knows: - `CONST_CASE` (also `UPPER_CASE` and `SCREAMING_SNAKE_CASE`): `THIS_IS_CONST_CASE` - `camelCase`: `thisIsCamelCase`, acronyms allowed (`userID`) - `camelCaseStrict`: `thisIsCamelCase`, no two capitals in a row (`userId`) - `kebab-case`: `this-is-kebab-case` - `PascalCase`: `ThisIsPascalCase`, acronyms allowed (`HTTPServer`) - `PascalCaseStrict`: `ThisIsPascalCase`, no two capitals in a row (`HttpServer`) - `Header-Case`: `This-Is-Header-Case` - `snake_case`: `this_is_snake_case` The rule reports `Schema enum value '...' is not in the '...' convention`. It is in the `strict` and `all` rulesets. ## Configuration A convention name. `CONST_CASE` by default. **Configuration example**. Kebab-case values. ```yaml commands: lint: rules: schema-enum-naming: - warning - kebab-case ``` ## Examples **Good**. With the default convention. ```yaml components: schemas: UserStatus: type: string enum: - ACTIVE - INACTIVE - BLOCKED ``` **Bad**. Three conventions in one enum. ```yaml components: schemas: UserStatus: type: string enum: - activeStatus - inactive_status - BLOCKED_STATUS ``` --- # schema-enum-no-duplicates Source: https://apigenie.pl/docs/linter/openapi/rules/schema-enum-no-duplicates A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that no value appears twice in an `enum`. ## Rule details A repeated value is a copy-and-paste mistake, often of a value that was meant to be another one: `active, active` where `active, archived` was intended. Generated code for the enum then has one member fewer than the API has values, or does not compile. The rule reports `Duplicate enum value` on the schema. ## Examples **Good**. ```yaml components: schemas: UserStatus: type: string enum: - active - inactive ``` **Bad**. `active` twice. ```yaml components: schemas: UserStatus: type: string enum: - active - active ``` --- # schema-enum-types Source: https://apigenie.pl/docs/linter/openapi/rules/schema-enum-types A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the values of `enum` and `const` have the type the schema declares. ## Rule details A `type: string` with the values `1` and `2` accepts nothing: a value that is one of the numbers is not a string, and a string is not one of the values. Validators reject every value, and a generated enum type takes the values or the type, not both. The rule reports `Enum value type is not in the schema type` on the schema. ## Examples **Good**. Strings in a string schema. ```yaml components: schemas: UserStatus: type: string enum: - active - inactive ``` **Bad**. Numbers in a string schema. ```yaml components: schemas: UserStatus: type: string enum: - 1 - 2 ``` ## Automatic fixes `--fix` sets the type of the schema to the type of the values when all the values have one JSON type and the schema has no `format`. Enums with values of several types stay for you to resolve. --- # schema-example-defined Source: https://apigenie.pl/docs/linter/openapi/rules/schema-example-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that every schema that is not trivial, an object, an array or a string with a `pattern`, has an example. ## Rule details An example shows what a schema describes faster than the schema does, and documentation, mock servers and generated tests use it in place of a value they would have to make up: a `pattern` tells the reader less than one string that matches it. The rule checks the schemas a document names or uses directly: the entries of `components/schemas` and the inline schemas of media types, parameters and headers. A schema passes with an `example` or `examples` of its own, and an inline schema also with an `example` or `examples` of the media type, parameter or header that holds it. A schema combined with `allOf` counts as an object when one of its parts is. The properties and items of a schema are not checked on their own, since the example of the schema shows them, and a `$ref` is checked where its target is defined. The rule reports `Schema has no example`. ## Examples **Good**. The example shows a username that matches the pattern. ```yaml components: schemas: User: type: object properties: username: type: string pattern: "^[a-z0-9_-]{3,16}$" example: username: "john_doe" ``` **Bad**. The reader works out a valid username from the pattern. ```yaml components: schemas: User: type: object properties: username: type: string pattern: "^[a-z0-9_-]{3,16}$" ``` --- # schema-format-defined Source: https://apigenie.pl/docs/linter/openapi/rules/schema-format-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that every `integer` and `number` schema has a `format` that says its size: `int32`, `int64` or another integer format for integers, `float`, `double`, `decimal` or another number format for numbers. ## Rule details A bare `integer` is a 32-bit `int` in one generated client and a 64-bit one in another, and a bare `number` is a `float` in one and a `double` in the next; an ID that fits one and not the other is a bug found in production. The format names the size, and every generator picks the same type. The rule accepts, for `integer`, the integer formats of the [OpenAPI format registry](/docs/reference/cli/formats) (`int8` to `uint64`, `int32`, `int64`, `double-int`, `sf-integer`) and `unixtime`; for `number`, the number formats (`float`, `double`, `decimal`, ...); and a format of `openapi.custom_formats` of the matching type. It reports `Schema with integer type does not define proper format` and `Schema with number type does not define proper format`. ## Examples **Good**. A 64-bit identifier. ```yaml components: schemas: User: type: object properties: id: type: integer format: int64 ``` **Bad**. 32 or 64 bits? Each generator decides. ```yaml components: schemas: User: type: object properties: id: type: integer ``` --- # schema-format-deprecated Source: https://apigenie.pl/docs/linter/openapi/rules/schema-format-deprecated A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.10.0. In the rulesets: Recommended at warning, Strict at warning, All at warning. This rule reports the formats which the [OpenAPI format registry](https://spec.openapis.org/registry/format/) marks as deprecated, and names what replaces them. ## Rule details From OpenAPI 3.1, schemas are JSON Schema 2020-12, which describes encoded content with `contentEncoding` and `contentMediaType`. The registry deprecates the formats that said the same thing in OpenAPI 3.0: | Format | Use instead | | ------ | ----------- | | `byte` | `contentEncoding: base64` | | `base64url` | `contentEncoding: base64url` | | `binary` | `contentMediaType`, or the media type of the body or part without a schema | OpenAPI 3.0 has neither keyword, so in 3.0 documents the rule reports these formats as hints: they show where the document will need a change when it moves to OpenAPI 3.1, without counting as warnings or failing the run. See [Formats](/docs/reference/cli/formats) for every format and what API Genie does with it. Keep the formats, and turn the rule off, when the document must stay readable by tools that only understand the OpenAPI 3.0 formats. ## Examples **Good**. The encoding and the media type as keywords. ```yaml openapi: 3.1.0 components: schemas: Avatar: type: string contentEncoding: base64 contentMediaType: image/png ``` **Bad**. `byte` in a 3.1 document. ```yaml openapi: 3.1.0 components: schemas: Avatar: type: string format: byte ``` --- # schema-format-type-mismatch Source: https://apigenie.pl/docs/linter/openapi/rules/schema-format-type-mismatch A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the `format` of a schema fits its `type`: `date` on a string, `int64` on an integer. ## Rule details A format that does not fit the type is a contradiction that every tool resolves its own way: a validator trusts the type and ignores the format, a generator may do the opposite, and a mock server generates data that the API cannot return. The rule reports a schema whose `format` is in the [OpenAPI format registry](https://spec.openapis.org/registry/format/) when none of the schema's types is a JSON type of that format (see [Formats](/docs/reference/cli/formats) for the list). For example: - `date`, `uuid`, `email`, `http-date`, `language` and the other string formats need `type: string`; - `int8` to `uint64`, `int32`, `int64`, `double-int` and `sf-integer` need `type: integer` or `type: number`; - `float`, `double` and `sf-decimal` need `type: number` (not `integer`); - `int64` and `uint64` also allow `type: string`, and `decimal` and `decimal128` allow `string` and `number`, as the registry does; - `unixtime` allows `integer`, `number` and `string`. The formats of `openapi.custom_formats` in the [configuration file](/docs/reference/cli/configuration) are checked against the type given there, and override the registry's. A schema without a `type` is reported too. Formats neither in the registry nor custom are left to [schema-format-unknown](/docs/linter/openapi/rules/schema-format-unknown). ## Configuration An object with one optional property, `fixTypeFromFormat`: whether `--fix` replaces a mismatched type with the type of the format. `true` by default. ## Examples **Good**. `date` is a string format. ```yaml components: schemas: User: type: object properties: birthDate: type: string format: date ``` **Bad**. An integer with a string format. ```yaml components: schemas: User: type: object properties: birthDate: type: integer format: date ``` ## Automatic fixes `--fix` gives the schema the type of its format: integer formats set `integer`, `decimal` and `decimal128` set `string`, the other number formats set `number` and string formats set `string`. Unknown formats stay for you to resolve. --- # schema-format-unknown Source: https://apigenie.pl/docs/linter/openapi/rules/schema-format-unknown A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.10.0. In the rulesets: Strict at warning, All at warning. This rule reports a `format` which is neither in the [OpenAPI format registry](https://spec.openapis.org/registry/format/) nor declared in `openapi.custom_formats` of the configuration file. ## Rule details Validators, mock servers and code generators ignore formats they do not know, so a misspelled format (`date_time`, `uuid4`) stops being checked without a word. Formats your API defines on purpose are declared in the [configuration file](/docs/reference/cli/configuration#openapicustom_formats): ```yaml openapi: custom_formats: - {name: currency-code, type: string} ``` The rule is off in the `recommended` ruleset, since OpenAPI allows any format, and a warning in `strict` and `all`. See [Formats](/docs/reference/cli/formats) for the registry's formats. Turn the rule off when the document uses many formats of its own and listing them in the configuration file is not worth it. ## Examples **Good**. `uuid` is in the registry. ```yaml components: schemas: Id: type: string format: uuid ``` **Bad**. `uuid4` is not, so nothing checks the value. ```yaml components: schemas: Id: type: string format: uuid4 ``` --- # schema-keyword-support Source: https://apigenie.pl/docs/linter/openapi/rules/schema-keyword-support A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.11.0. In the rulesets: All at warning. This rule reports schema keywords that the tools consuming the document are unlikely to support, and suggests the rewrite where one exists. ## Rule details OpenAPI 3.1 schemas are JSON Schema 2020-12, but much of the tooling around them is not. Validators of older drafts, OpenAPI 3.0 tools and most code generators ignore the keywords they don't know, so `unevaluatedProperties: false` stops rejecting anything, a `prefixItems` tuple turns into an untyped array and an `if`/`then` constraint silently disappears from the generated client. The rule checks each schema against one or more **targets** and reports, once per keyword, the first target that does not support it: | Target | Who it stands for | | ------ | ----------------- | | `draft4` | Validators stuck at draft-04, e.g. NJsonSchema's default dialect, older PHP and Python libraries | | `draft6` | Draft-06 validators | | `draft7` | Validators stopping at draft-07: gojsonschema, everit-org/json-schema, Ajv's default export; also the default schema dialect of AsyncAPI 2.x and 3.0 | | `draft2019-09` | Validators without draft 2020-12 | | `openapi30` | The Schema Object of OpenAPI 3.0 and the tools built for it, e.g. NSwag | | `codegen` | The keywords most code generators ignore or can't express in types (the default) | What each target lacks, and the suggested rewrite: | Keyword or form | Not supported by | Suggested rewrite | | --------------- | ---------------- | ----------------- | | `unevaluatedProperties` | drafts 4 to 7, `openapi30`, `codegen` | merge the `allOf` members into one schema and use `additionalProperties` | | `unevaluatedItems` | drafts 4 to 7 | `additionalItems` next to the array form of `items` | | `unevaluatedItems` | `openapi30`, `codegen` | none | | `prefixItems` | drafts 4 to 2019-09 | the array form of `items`, `additionalItems` for the rest | | `prefixItems` | `openapi30`, `codegen` | an object with named properties | | `$dynamicRef`, `$recursiveRef` | drafts 4 to 7, `openapi30`, `codegen` | `$ref` to the schema it resolves to | | `$dynamicRef` | `draft2019-09` | `$recursiveRef` | | `$dynamicAnchor`, `$recursiveAnchor` | drafts 4 to 7, `openapi30`, `codegen` | drop it once the reference to it is a `$ref` | | `$anchor` | drafts 4 to 7, `openapi30`, `codegen` | reference the schema by a JSON pointer | | `$vocabulary` | drafts 4 to 7, `openapi30`, `codegen` | drop it | | `$defs` | drafts 4 to 7 | `definitions` | | `$defs` | `openapi30` | move the schemas to `components/schemas` | | `dependentRequired` | drafts 4 to 7 | `dependencies` with an array of property names | | `dependentSchemas` | drafts 4 to 7 | `dependencies` with a schema | | `dependentRequired`, `dependentSchemas`, `dependencies` | `openapi30`, `codegen` | none | | `dependencies` | `draft2019-09` | `dependentRequired` or `dependentSchemas` | | `if` (with `then`/`else`) | `draft4`, `draft6`, `openapi30`, `codegen` | `oneOf` with one alternative per case | | `contentSchema`, `minContains`, `maxContains` | drafts 4 to 7, `openapi30`, `codegen` | none | | `contains` | `draft4`, `openapi30`, `codegen` | none | | `propertyNames` | `draft4`, `openapi30` | none | | `const` | `draft4`, `openapi30` | an `enum` with one value | | `patternProperties` | `openapi30` | `properties` for fixed names, `additionalProperties` for the rest | | `patternProperties` | `codegen` | `additionalProperties` | | `not` | `codegen` | none | | `additionalItems` | `openapi30` | none | | `$id`, `$schema`, `$comment`, `examples`, `contentEncoding`, `contentMediaType` | `openapi30` | drop `$id` and `$schema`; `description` for `$comment`; `example`; `format: byte` or `format: binary` | | `$id` | `draft4` | `id` | | a `type` array | `openapi30` | one `type` with `nullable: true`, or `anyOf` | | a `type` array of several non-null types | `codegen` | `oneOf` with one schema per type | | `type: null` | `openapi30` | `nullable: true` | | a numeric `exclusiveMinimum`/`exclusiveMaximum` | `draft4`, `openapi30` | `minimum`/`maximum` with the boolean form | | a boolean `exclusiveMinimum`/`exclusiveMaximum` | drafts 6 to 2019-09 | the bound as the value | | `nullable: true` | drafts 4 to 2019-09 | add `"null"` to `type` | | `$ref` with keywords that constrain the value | drafts 4 to 7, `openapi30`, `codegen` | wrap the reference in `allOf`; the siblings are ignored otherwise | Annotations a validator ignores without harm (`description`, `examples`, `readOnly`, `deprecated`, `$comment`, the content keywords) are reported only for `openapi30`, whose Schema Object allows no keywords besides its own and `x-` extensions. `then` and `else` are covered by the report on `if`. A `$ref` next to annotations only (`description`, `summary`, `example`, ...) is not reported. `apigenie convert --from jsonschema --to draft7|draft4|openapi30` performs most of these rewrites on a standalone JSON Schema document, including the `allOf` flattening that replaces `unevaluatedProperties`. In OpenAPI 3.0 documents the rule finds the keywords the Schema Object does not have (with the `openapi30` target) and the OpenAPI forms that JSON Schema validators do not understand (with the draft targets). Turn the rule off when every consumer of the document supports JSON Schema 2020-12 in full, such as Ajv 2020, networknt, santhosh-tekuri/jsonschema or Python's jsonschema, and no code is generated from it. The rule is in the `all` ruleset only. ## Configuration The options are a target name, an array of target names, or an object with: - `targets`: a target name or an array of target names; `codegen` when omitted. - `allow`: keywords never reported, for the ones your tools are known to support. **Configuration example 1**. Keep a 3.1 document usable by OpenAPI 3.0 tooling. ```yaml commands: lint: rules: schema-keyword-support: - warning - openapi30 ``` **Configuration example 2**. Check against draft-07 validators and the code generators, accepting `not`. ```yaml commands: lint: rules: schema-keyword-support: - warning - targets: [draft7, codegen] allow: [not] ``` ## Examples **Good**. A closed object that every target understands. ```yaml components: schemas: Pet: type: object required: [name] properties: name: type: string additionalProperties: false ``` **Bad**. `unevaluatedProperties` is ignored by OpenAPI 3.0 tools, draft-07 validators and most code generators, so they accept any extra property. ```yaml components: schemas: Pet: allOf: - $ref: '#/components/schemas/Animal' properties: name: type: string unevaluatedProperties: false ``` --- # schema-no-additional-properties Source: https://apigenie.pl/docs/linter/openapi/rules/schema-no-additional-properties A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that every object schema has `additionalProperties: false`. ## Rule details JSON Schema accepts properties a schema does not declare unless the schema says otherwise. An open object hides a misspelled property name in a request (`emial` is accepted and ignored), lets a client send fields the server stores without validating, and leaves generated code to guess whether a map is needed. The rule reports `Object schema does not disable additional properties` on each schema whose type includes `object` and which does not set `additionalProperties: false`. Where a schema is extended with `allOf`, closing the base schema makes every extension invalid; see [schema-no-contradictions](/docs/linter/openapi/rules/schema-no-contradictions) for the `unevaluatedProperties` form that closes the combined schema instead. ## Examples **Good**. The object is closed. ```yaml components: schemas: User: type: object properties: firstName: type: string lastName: type: string additionalProperties: false ``` **Bad**. Any property is accepted. ```yaml components: schemas: User: type: object properties: firstName: type: string lastName: type: string ``` ## Automatic fixes `--fix` adds `additionalProperties: false` to each object schema that lacks it. --- # schema-no-contradictions Source: https://apigenie.pl/docs/linter/openapi/rules/schema-no-contradictions A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule reports schemas with contradicting constraints, which reject every value or some of the properties they describe. ## Rule details The rule merges each schema with its `allOf` members, following references, and reports contradictions it can prove: - `allOf` members requiring types with nothing in common, such as `string` and `integer`; - bounds excluding every value: `minimum` above `maximum` (taking `exclusiveMinimum` and `exclusiveMaximum` into account, and integers when the type is `integer`), `minLength` above `maxLength`, `minItems` above `maxItems`, `minProperties` above `maxProperties`, or more required properties than `maxProperties`; - an `allOf` member rejecting every value, e.g. `false` or `not: {}`, and `anyOf` or `oneOf` whose every branch does; - `enum` or `const` values of an `allOf` member none of which satisfies the whole schema; - a required property whose schema rejects every value, or which an `allOf` member with `additionalProperties: false` does not declare; - a property which can never be present because an `allOf` member with `additionalProperties: false` does not declare it. This is the common mistake of closing a base schema and extending it with `allOf`; use `unevaluatedProperties: false` (OpenAPI 3.1) on the combined schema instead. A contradiction is reported once, at the schema it originates from, and not again at every schema using that one. Formats are not checked, and constraints the rule cannot reason about (such as `pattern`) never lead to a report. In OpenAPI 3.0 documents, `nullable` and the boolean `exclusiveMinimum` and `exclusiveMaximum` are taken into account, and keywords beside `$ref` are ignored as the specification requires. ## Examples **Good**. `Cat` declares every property it allows. ```yaml components: schemas: Pet: type: object required: [petType] properties: petType: type: string Cat: allOf: - $ref: '#/components/schemas/Pet' - properties: meow: type: boolean unevaluatedProperties: false ``` **Bad**. `Pet` forbids `meow`, so a `Cat` can never have it. ```yaml components: schemas: Pet: type: object additionalProperties: false required: [petType] properties: petType: type: string Cat: allOf: - $ref: '#/components/schemas/Pet' - properties: meow: type: boolean ``` **Bad**. No value is both a string and an integer. ```yaml components: schemas: Id: allOf: - type: string - type: integer ``` --- # schema-no-optional-nullable-properties Source: https://apigenie.pl/docs/linter/openapi/rules/schema-no-optional-nullable-properties A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at error, All at error. This rule disallows schema properties that are both optional and nullable. ## Rule details An optional nullable property represents an absent value in two ways: the property may be omitted, or it may be present with the value `null`. Requiring a property to be nullable or allowing it to be omitted makes the API contract unambiguous. A property is nullable when its schema, or the schema it references, allows `null`: - a `null` type, e.g. `type: [string, 'null']`; - `nullable: true` in OpenAPI 3.0 documents; - `null` in `enum` or as `const`; - an `anyOf` or `oneOf` branch allowing `null`, e.g. `anyOf: [{$ref: ...}, {type: 'null'}]`; - an `allOf` whose every member allows `null`. A property counts as required when the schema, one of its `allOf` members, or a schema using it in `allOf` lists it in `required`. In `PATCH` request bodies and `application/merge-patch+json` documents, `null` means "remove this value" (RFC 7396), so optional nullable properties are expected there and the rule skips them and every schema they contain. Turn the rule off when omission and an explicit `null` mean two different things in your API. ## Configuration An object with one optional property: - `ignorePatchBodies`: skip the schemas of `PATCH` request bodies and merge-patch documents. Defaults to `true`. ```yaml commands: lint: rules: schema-no-optional-nullable-properties: - warning - ignorePatchBodies: false ``` ## Examples **Good**. The nullable property is required. ```yaml components: schemas: User: type: object required: [middleName] properties: middleName: type: [string, 'null'] ``` **Good**. The optional property cannot be `null`. ```yaml components: schemas: User: type: object properties: middleName: type: string ``` **Bad**. `middleName` can be omitted or set to `null`. ```yaml components: schemas: User: type: object properties: middleName: type: [string, 'null'] ``` --- # schema-oneof-no-overlap Source: https://apigenie.pl/docs/linter/openapi/rules/schema-oneof-no-overlap A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule reports `oneOf` branches that a single value can match. ## Rule details A value is valid against `oneOf` only if it matches exactly one branch. When branches overlap, the values matching several of them are rejected, which is rarely intended: two object schemas without `additionalProperties: false` both accept `{}`, and `number` overlaps `integer`. The rule reports: - identical branches, such as two references to the same schema or two schemas with the same content; - a value matching two branches. The rule tries the values the branches document (`example`, `examples`, `default`, `const` and `enum`) and small values it builds from their constraints, and reports only a value that it has validated against both branches and against the keywords beside `oneOf`. The message shows that value. `oneOf` with a `discriminator` is skipped, because tools choose the branch named by the discriminator instead of validating every branch. Branches with recursive or external references are skipped too. Turn the rule off when the tools that consume the document do not validate `oneOf` strictly; where overlapping branches are meant, `anyOf` says so. ## Examples **Good**. Each branch forbids the other one's properties. ```yaml components: schemas: Pet: oneOf: - type: object additionalProperties: false required: [meow] properties: meow: type: boolean - type: object additionalProperties: false required: [bark] properties: bark: type: boolean ``` **Good**. A discriminator selects the branch. ```yaml components: schemas: Pet: oneOf: - $ref: '#/components/schemas/Cat' - $ref: '#/components/schemas/Dog' discriminator: propertyName: petType ``` **Bad**. `{"name": ""}` matches both branches, so it is rejected. ```yaml components: schemas: Pet: oneOf: - type: object required: [name] properties: name: type: string meow: type: boolean - type: object required: [name] properties: name: type: string bark: type: boolean ``` --- # schema-property-naming Source: https://apigenie.pl/docs/linter/openapi/rules/schema-property-naming A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Strict at error, All at error. This rule checks that the property names of schemas follow one naming convention, `snake_case` (`first_name`) unless configured otherwise. ## Rule details Property names are typed by every client, and a client author who has seen one should be able to spell the next. The conventions the rule knows: - `CONST_CASE` (also `UPPER_CASE` and `SCREAMING_SNAKE_CASE`): `THIS_IS_CONST_CASE` - `camelCase`: `thisIsCamelCase`, acronyms allowed (`userID`) - `camelCaseStrict`: `thisIsCamelCase`, no two capitals in a row (`userId`) - `kebab-case`: `this-is-kebab-case` - `PascalCase`: `ThisIsPascalCase`, acronyms allowed (`HTTPServer`) - `PascalCaseStrict`: `ThisIsPascalCase`, no two capitals in a row (`HttpServer`) - `Header-Case`: `This-Is-Header-Case` - `snake_case`: `this_is_snake_case` The rule reports `Schema property '...' is not in the '...' convention`. It is in the `strict` and `all` rulesets. ## Configuration A convention name. `snake_case` by default. **Configuration example**. Camel-case properties. ```yaml commands: lint: rules: schema-property-naming: - warning - camelCase ``` ## Examples **Good**. With the default convention. ```yaml components: schemas: User: type: object properties: first_name: type: string last_name: type: string ``` **Bad**. Camel case with the default convention. ```yaml components: schemas: User: type: object properties: firstName: type: string lastName: type: string ``` --- # schema-required-properties-defined Source: https://apigenie.pl/docs/linter/openapi/rules/schema-required-properties-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that every name listed in `required` is defined in `properties`. ## Rule details A required property which is not defined is usually a typo (`required: [nmae]`) or a property removed from `properties` but not from `required`. Its value is not described, and generated code often cannot represent it. The rule looks for the definition wherever the schema's value is also described: - in the schema's `allOf` members, following references; - in the schemas using it in `allOf`, `anyOf`, `oneOf`, `not`, `if`, `then` or `else`, and in their other members. This accepts common patterns such as `anyOf: [{required: [email]}, {required: [phone]}]` below a schema defining both properties, or a mixin requiring a property that the schemas using it define. Schemas which allow undeclared properties on purpose are skipped: those with `patternProperties`, a schema in `additionalProperties`, or `additionalProperties: true`. Schemas whose references cannot be resolved are skipped too. `required` in a schema which does not allow objects, for example beside `items` in an array schema instead of inside it, has no effect and is reported as such. The rule reports `Required property '...' is not defined in 'properties'` and `'required' has no effect because the schema does not allow objects`. ## Examples **Good**. Both required properties are defined. ```yaml components: schemas: User: type: object required: [id, name] properties: id: type: string name: type: string ``` **Bad**. `nmae` is not defined. ```yaml components: schemas: User: type: object required: [id, nmae] properties: id: type: string name: type: string ``` **Bad**. `required` applies to the array, not to its items. ```yaml components: schemas: Packages: type: array items: type: object properties: name: type: string required: [name] ``` --- # server-urls Source: https://apigenie.pl/docs/linter/openapi/rules/server-urls A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that every server URL is valid, has its scheme and host in lower case, and uses `https`, except on `localhost`. ## Rule details A server URL is copied into every client and every tool that calls the API. `http` on a public host sends every request, with its credentials, in clear text. Upper-case letters in a scheme or a host are the same address to DNS and to browsers, but not to a string comparison in a client, a proxy rule or a certificate check. The rule reports `Server URL is not lower case or uses http protocol` on each such server. ## Configuration An object with one optional property, `upgradeHttp`: whether `--fix` changes `http` to `https` on hosts other than `localhost`. `false` by default, since the fix can only be right when the server listens on `https`. **Configuration example**. ```yaml commands: lint: rules: server-urls: - warning - upgradeHttp: true ``` ## Examples **Good**. `https` on the public host, `http` on `localhost`. ```yaml servers: - url: https://api.example.com/v1 description: Production server - url: http://localhost:8080/v1 description: Local development server ``` **Bad**. `http` on a public host, and a host in capitals. ```yaml servers: - url: http://api.example.com/v1 description: Production server - url: https://API.EXAMPLE.COM/v1 description: Production server with upper-case letters ``` ## Automatic fixes `--fix` lowercases the scheme and the host. The user information, port, path, query, fragment and the names of server variables keep their case, since they can be case-sensitive. With `upgradeHttp: true`, it also changes `http` to `https` on hosts other than `localhost`. --- # server-urls-no-trailing-slash Source: https://apigenie.pl/docs/linter/openapi/rules/server-urls-no-trailing-slash A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.12.0. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that no URL in the document's top-level `servers`, other than `/`, ends with a slash. ## Rule details Paths start with a slash, and a client builds a request URL by appending the path to the server URL. A server URL that also ends with a slash gives `https://api.example.com/v1//pets`, which some servers and proxies route differently from `/v1/pets`, or refuse. The rule reports `Server URL ends with a slash` on each such server. A server URL that is only `/` (the host the document is served from) is not reported. The `servers` of path items and operations are not checked. Turn the rule off only for a document you can't change: a path starts with a slash, so a server URL never needs one at its end. ## Examples **Good**. ```yaml servers: - url: https://api.example.com/v1 ``` **Bad**. ```yaml servers: - url: https://api.example.com/v1/ ``` ## Automatic fixes `--fix` removes the trailing slashes. When `server-urls` also fixes the same URL, one `--fix` makes one of the two changes, and the next makes the other. --- # servers-defined Source: https://apigenie.pl/docs/linter/openapi/rules/servers-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that the document has at least one server. ## Rule details The servers are where the API is: without them, documentation cannot offer a "try it" call, a generated client has no default base URL, and `apigenie-server` cannot take the base path from the document. The rule reports `No servers defined` on the document. ## Examples **Good**. ```yaml servers: - url: https://api.dev.example.com/v1 description: Development server ``` **Bad**. A document without `servers`. ```yaml openapi: 3.1.0 info: title: Example API version: 1.0.0 paths: {} ``` --- # spell-check Source: https://apigenie.pl/docs/linter/openapi/rules/spell-check A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Strict at warning, All at warning. This rule checks the spelling of the texts written for humans: titles, summaries and descriptions. ## Rule details The rule reports every misspelled word, with up to three suggested corrections, for example `Misspelled word 'recieve' in description (did you mean 'receive', 'relieve', 'reverie'?)`. The issue points at the object whose text contains the word. The rule checks: - the title, summary and description of the info object, - the summary and description of path items, operations, tags, examples and references, - the description of servers, server variables, parameters, request bodies, responses, headers, links, security schemes and external documentation, - the title and description of schemas. Descriptions are CommonMark: the rule checks their prose, and skips code spans, code blocks, raw HTML and link destinations. Titles and summaries are plain text, in which `backticked` spans are skipped, too. The rule also skips the tokens which are not plain words: - URLs, e-mail addresses, paths, and file and domain names (`openapi.yaml`, `example.com`), - identifiers: `snake_case`, `camelCase` and names with inner capitals (`OpenAPI`, `PetStore`), - acronyms, also in the plural (`JSON`, `APIs`, `ID's`), - tokens with digits (`v2`, `401`) and single letters. The spell checker is a C++ port of [Hunspell](https://hunspell.github.io). By default it uses the built-in English (US) dictionary from [SCOWL](http://wordlist.aspell.net) (as shipped with LibreOffice), extended with words common in API descriptions, such as `webhook`, `endpoint`, `namespace`, `nullable` and `json`. Any Hunspell dictionary can be used instead. The rule is in the `strict` and `all` rulesets. Turn it off when the texts are written in a language you have no dictionary for; to silence it for one object and its children, add `x-apigenie-lint-disable: [spell-check]` to the object. ## Configuration An object with these optional properties: - `words`: extra words to accept, for example product names. A word is accepted as given, capitalized and in capitals: `petstore` accepts `petstore`, `Petstore` and `PETSTORE`. - `dictionary` and `affix`: paths of a Hunspell dictionary (`.dic`) and its affix file (`.aff`) to use instead of the built-in dictionary. They go together. Dictionaries in UTF-8, ISO-8859-1, ISO-8859-2 and ISO-8859-15 are supported. - `suggestions`: how many corrections to suggest for a word, from 0 to 10 (default 3). Suggestions are the costly part of the rule; on a very large document with many unknown words, `0` makes it about ten times faster. ```yaml commands: lint: rules: spell-check: - warning - words: [petstore, Fluffy] ``` ```yaml commands: lint: rules: spell-check: - warning - dictionary: dictionaries/en_GB.dic affix: dictionaries/en_GB.aff ``` ## Examples **Good**. Every word is in the dictionary, and the code span is skipped. ```yaml paths: /users: get: summary: Retrieve a list of users description: This operation retrieves the `users` of the system as JSON. ``` **Bad**. Three misspelled words. ```yaml paths: /users: get: summary: Retrive a list of users description: This operation retrives a list of users from the sytem. ``` --- # standard-media-types Source: https://apigenie.pl/docs/linter/openapi/rules/standard-media-types A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that the media types of request bodies, responses, parameters and headers are ones the rule knows: a top-level type registered with IANA (`application`, `text`, `image`, `multipart`, ...) and one of about sixty common subtypes (`json`, `xml`, `problem+json`, `vnd.api+json`, `form-data`, `x-www-form-urlencoded`, `octet-stream`, `pdf`, `png`, ...), or `*` for either. ## Rule details A media type that no client library knows is parsed by hand on both sides; a misspelled one (`application/jsn`) is a body nobody parses at all. The common types have parsers everywhere. The rule reports `Non-standard media type is used (...)` on the object that declares the media type. Vendor types of your own, `application/vnd.acme.v1+json`, are reported too: turn the rule off when the API uses them on purpose. ## Examples **Good**. ```yaml paths: /users: get: responses: "200": description: OK content: application/json: schema: $ref: "#/components/schemas/User" ``` **Bad**. `application/x-custom` is a type the rule does not know. ```yaml paths: /users: get: responses: "200": description: OK content: application/x-custom: schema: $ref: "#/components/schemas/User" ``` --- # standard-response-codes Source: https://apigenie.pl/docs/linter/openapi/rules/standard-response-codes A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that every response is keyed by a three-digit HTTP status code from `100` to `599`, by a range from `1XX` to `5XX`, or by `default`. ## Rule details HTTP defines the status codes as three digits whose first one is the class of the response, and OpenAPI spells a range of them with two capital `X`. A key outside that form, `2xx`, `0200`, `600`, is not a status code any client will see: validators skip the response, generated clients have no branch for it, and a mock server never answers with it. The rule reports `Operation uses non-standard response code (...)` on each such response. It does not check that a code is registered with IANA: `460` passes. The `default` response, which OpenAPI allows for every code the other entries do not list, passes too. ## Examples **Good**. ```yaml paths: /users: get: responses: "200": description: OK "4XX": description: The request is invalid. default: description: An unexpected error. ``` **Bad**. A range in lower case and a code of four digits. ```yaml paths: /users: get: responses: "2xx": description: OK "0404": description: Not Found ``` --- # standard-response-errors Source: https://apigenie.pl/docs/linter/openapi/rules/standard-response-errors A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Strict at warning, All at warning. This rule checks that every 4xx and 5xx response has the error format of one convention, Problem Details (RFC 9457) unless configured otherwise. ## Rule details A client handles errors in one place when every error has the same shape; with one shape per operation, it handles them in each call, or not at all. The conventions the rule knows: - `problem-json`, [Problem Details for HTTP APIs](https://datatracker.ietf.org/doc/html/rfc9457): the response has the `application/problem+json` media type, and its schema is an object with the properties `type` (a string with `format: uri`), `title` (a string), `status` (an integer), `detail` (a string) and `instance` (a string with `format: uri`). - `json-api`, the [JSON:API error objects](https://jsonapi.org/format/#error-objects): the response has the `application/vnd.api+json` media type, and its schema is an object whose `errors` property is an array of objects. The rule reports `Response must use Problem JSON format` or `Response must use JSON:API error format` when the media type is missing, and `Response must use correct Problem JSON schema` or `Response must use correct JSON:API error schema` when the schema is not the one above. It is in the `strict` and `all` rulesets; turn it off when the API has an error format of its own. ## Configuration A convention name, `problem-json` or `json-api`. `problem-json` by default. **Configuration example**. JSON:API errors. ```yaml commands: lint: rules: standard-response-errors: - error - json-api ``` ## Examples **Good**. A Problem Details response. ```yaml paths: /users: get: responses: "400": description: Bad Request content: application/problem+json: schema: type: object properties: type: type: string format: uri title: type: string status: type: integer detail: type: string instance: type: string format: uri ``` **Bad**. An error shape of its own. ```yaml paths: /users: get: responses: "400": description: Bad Request content: application/json: schema: type: object properties: error: type: string message: type: string ``` **Good**. With the `json-api` convention. ```yaml paths: /users: get: responses: "400": description: Bad Request content: application/vnd.api+json: schema: type: object properties: errors: type: array items: type: object properties: status: type: string title: type: string detail: type: string ``` --- # tag-description-defined Source: https://apigenie.pl/docs/linter/openapi/rules/tag-description-defined A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at warning, Strict at warning, All at warning. This rule checks that every tag has a description of at least 10 characters that is not a placeholder. ## Rule details Tags are the sections of the documentation and the classes of a generated client; the description is the sentence at the top of the section that says what the group is for. A tag named `Users` with no description is a heading over a list. The rule reports `Tag '...' has no meaningful description defined` when the description is missing, shorter than the minimum, white space only, or one of `TBD`, `TODO` and `FIXME`. ## Configuration A positive integer: the minimal length of a description. 10 by default. **Configuration example**. Descriptions of at least 20 characters. ```yaml commands: lint: rules: tag-description-defined: - warning - 20 ``` ## Examples **Good**. ```yaml tags: - name: User description: Operations on user accounts. - name: Product description: Operations on the product catalog. ``` **Bad**. An empty description and a missing one. ```yaml tags: - name: User description: "" - name: Product ``` --- # tags-sorted Source: https://apigenie.pl/docs/linter/openapi/rules/tags-sorted A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Strict at error, All at error. This rule checks that the tags of the document are in alphabetical order of their names. ## Rule details Documentation tools show the tags in the order of the document, so the order of `tags` is the order of the sections the reader sees. Alphabetical order is one a reader can predict, and one that two people editing the list agree on without talking. Turn the rule off when the order of the sections is a choice, such as the most used group first. The rule reports `Tags are not sorted: ...` on each tag that comes before its predecessor. ## Examples **Good**. ```yaml tags: - name: Admin - name: Product - name: User ``` **Bad**. `Admin` after `User`. ```yaml tags: - name: User - name: Admin - name: Product ``` ## Automatic fixes `--fix` reorders the tags. Nothing inside a tag changes. --- # tags-unique Source: https://apigenie.pl/docs/linter/openapi/rules/tags-unique A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that no two tags have the same name, compared without regard to case. ## Rule details Operations refer to tags by name, so two tags named `user` and `User` are one group to the reader and two to the tools, with two descriptions, and the operations tagged `User` land in whichever the tool picks. Two tags with the same name are a typo or a merge that kept both sides. The rule reports `Tag name is not unique (...)` on the later tag. ## Examples **Good**. ```yaml tags: - name: User - name: Product ``` **Bad**. One tag, or a typo? ```yaml tags: - name: user description: First tag - name: User description: Is this another tag, or a typo? ``` ## Automatic fixes `--fix` removes a duplicate whose name, description and external documentation are those of the first tag, and a duplicate that has a name only in favor of the one with a description. Duplicates whose descriptions or external documentation differ stay for you to merge. --- # unambiguous-response-codes Source: https://apigenie.pl/docs/linter/openapi/rules/unambiguous-response-codes A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that no operation declares both a range, such as `2XX`, and a code of that range, such as `204`. ## Rule details OpenAPI gives a code precedence over its range, but a reader does not know that, and a response declared twice, once as `204` and once as part of `2XX`, raises the question which description, body and headers apply. Tools differ too: a mock server picks one, a generated client may deserialize the other. The rule reports `Operation response codes are ambiguous` on the response that overlaps an earlier one. Turn it off when the API treats a range as the default and a code as its override on purpose. ## Examples **Good**. A range and a code of another range. ```yaml paths: /users: get: responses: "103": description: Early hints for the resources the page needs. "2XX": description: A list of users. ``` **Bad**. `204` is in `2XX`. ```yaml paths: /users: get: responses: "2XX": description: A list of users. "204": description: No content. ``` --- # unused-request-body Source: https://apigenie.pl/docs/linter/openapi/rules/unused-request-body A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that `GET`, `HEAD` and `TRACE` operations have no request body. ## Rule details HTTP gives a body on these methods no meaning: proxies and caches may drop it, servers may reject the request, and most client libraries cannot send it. A document that declares one describes a request the API cannot receive, and generated clients either ignore the body or produce a call that fails. The rule reports `Unused request body` on the operation. ## Examples **Good**. ```yaml paths: /users: get: responses: "200": description: A list of users. ``` **Bad**. A `GET` with a body. ```yaml paths: /users: get: requestBody: content: application/json: schema: $ref: "#/components/schemas/User" responses: "200": description: A list of users. ``` ## Automatic fixes `--fix` removes `requestBody` from the `GET`, `HEAD` and `TRACE` operations. --- # unused-shared-component Source: https://apigenie.pl/docs/linter/openapi/rules/unused-shared-component A rule of the OpenAPI linter, which reads OpenAPI 3.0, 3.1 and 3.2 documents. Since 0.0.1. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that every component of the document is reachable from its paths, webhooks, security requirements or tags. ## Rule details A component nothing refers to is dead weight that every reader, generator and reviewer still has to go through: a schema of a resource the API no longer has, a response that an operation stopped using. Generated clients get a type for it, documentation a section. The rule starts from the parts of the document outside `components` (paths, webhooks, security requirements, tags, extensions, ...) and follows references (`$ref`, discriminator mappings and security requirement names) transitively. Every component it cannot reach is reported as `Unused shared component`, including components used only by other unused components. A document without operations (no path items and no webhooks) is taken to be a library of components for other documents and is not checked. Turn the rule off for a document that has operations and also publishes components for other documents to reference. ## Examples **Good**. The `User` schema is referenced by a parameter. ```yaml components: schemas: User: type: object properties: id: type: integer name: type: string paths: /users/{id}: get: parameters: - name: id in: path required: true schema: $ref: "#/components/schemas/User" ``` **Bad**. Nothing refers to the `User` schema. ```yaml components: schemas: User: type: object properties: id: type: integer name: type: string paths: /users/{id}: get: parameters: - name: id in: path required: true schema: type: integer ``` ## Automatic fixes `--fix` removes the components the rule reports. It keeps the components disabled with `x-apigenie-lint-disable` and what they refer to, and the local targets of references and discriminator mappings it could not resolve. --- # audience-defined Source: https://apigenie.pl/docs/linter/asyncapi/rules/audience-defined A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks whether the intended audience of an API is declared in the `#/info/x-audience` extension of an AsyncAPI document. ## Rule details Knowing who an API is built for helps to decide how strict its review should be, how carefully breaking changes must be handled, and where the API can be published. AsyncAPI does not provide a field for this information. The `audience-defined` rule fills this gap. It requires the `x-audience` extension to be present in the info object, and its value to be one of the following strings: - `internal-team` - the API is used only by the team that owns it, - `internal-company` - the API is used by other teams in the same company, - `partner` - the API is shared with selected partners, - `public` - the API is publicly available. The rule reports `API audience (x-audience) is missing` when the extension is absent, and `API audience (x-audience) has invalid value (...)` when its value is not one of the strings listed above (including values that are not strings at all). Turn the rule off if your organization does not classify its APIs by their audience. ## Examples **Good**. The audience of the API is clearly stated. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 x-audience: internal-company ``` **Bad**. The audience is not declared. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 ``` **Bad**. The audience has a value that is not recognized. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 x-audience: everyone ``` --- # channel-address-no-query Source: https://apigenie.pl/docs/linter/asyncapi/rules/channel-address-no-query A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.12.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that no channel address contains a query (`?`) or a fragment (`#`). ## Rule details The specification says that a channel address shall not use query parameters or fragments, and puts them in the channel's bindings instead. The rule reports `Channel address must not contain a query ('?') or a fragment ('#')` on every channel, under `channels` and `components/channels`, whose `address` holds a `?` or a `#`. The rule is the counterpart of the AsyncAPI parser's `asyncapi3-channel-no-query-nor-fragment`, which checks the channel's key rather than its address. Turn the rule off only for a broker whose destination names contain a `?` or a `#`: the specification does not allow them in an address. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets/{kind}/adopted parameters: kind: {} ``` **Bad**. The kind of pet is a query. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets/adopted?kind=cat ``` --- # channel-addresses-unique Source: https://apigenie.pl/docs/linter/asyncapi/rules/channel-addresses-unique A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that no two channels of an AsyncAPI document share the same address, including addresses that differ only by the names of their parameters. ## Rule details In AsyncAPI 3.x the key of a channel in the `channels` map is only an identifier; the actual topic, queue or routing key is given by the channel's `address`. Two channels with the same address describe the same destination, which is usually a copy-and-paste mistake and makes it unclear which of the two definitions (and which set of messages) is authoritative. The `channel-addresses-unique` rule compares the addresses of all channels defined in the root `channels` map. Before comparing, the name of every parameter expression is dropped, so `users.{userId}.events` and `users.{id}.events` are considered duplicates, as they match exactly the same set of concrete addresses. The rule reports `Duplicate channel address found` on every channel whose address duplicates the address of a channel defined earlier in the document. Channels without an `address` (or with `address: null`, meaning the address is dynamic or unknown) are ignored. Channels defined under `components/channels` are not checked. Turn the rule off if you intentionally describe the same destination with several channels, for example when the channels are available on different servers and carry different messages. ## Examples **Good**. Each channel has its own address. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petCreated: address: pets.{petId}.created parameters: petId: description: Identifier of the pet. petDeleted: address: pets.{petId}.deleted parameters: petId: description: Identifier of the pet. ``` **Bad**. Both channels point to the same destination; they differ only by the parameter name. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petEvents: address: pets.{petId}.events parameters: petId: description: Identifier of the pet. animalEvents: address: pets.{animalId}.events parameters: animalId: description: Identifier of the animal. ``` --- # channel-parameters-defined Source: https://apigenie.pl/docs/linter/asyncapi/rules/channel-parameters-defined A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the parameters used in a channel address are declared in the channel's `parameters` map, and that the map declares no parameters the address does not use. ## Rule details A channel address may contain parameter expressions, such as `{userId}` in `users.{userId}.signedUp`. The AsyncAPI specification requires every such expression to have a matching entry in the channel's `parameters` map, whose key is the parameter name. Parameters that are declared but never used in the address are almost always leftovers from an earlier version of the address. The `channel-parameters-defined` rule checks every channel defined in the root `channels` map and in `components/channels` (references to channels are checked where the channel is defined). For each channel it reports: - `Channel parameter '<name>' is not defined` for every parameter used in the address that has no entry in the `parameters` map, - `Channel parameter '<name>' is not used in the channel address` for every entry of the `parameters` map that does not appear in the address. Channels without an `address` (or with `address: null`) are ignored, since their parameters cannot be verified. ## Examples **Good**. The address and the parameters map agree. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 channels: userSignedUp: address: users.{userId}.signedUp parameters: userId: description: Identifier of the user. ``` **Bad**. `userId` is used in the address but not declared, and `region` is declared but not used. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 channels: userSignedUp: address: users.{userId}.signedUp parameters: region: description: Region the user signed up in. ``` ## Automatic fixes `--fix` rewrites the `parameters` map of every reported channel so that it matches the address: declared parameters that the address uses are kept unchanged (including references), missing parameters are added as empty Parameter objects, and unused ones are removed. The parameters are ordered as they first appear in the address. If the address uses no parameters at all, the `parameters` map is removed. --- # channel-servers-in-servers Source: https://apigenie.pl/docs/linter/asyncapi/rules/channel-servers-in-servers A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.12.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the servers of a channel under the root `channels` are references to servers under the root `servers`. ## Rule details A channel's `servers` lists the servers it is available on. The specification requires each entry of a channel under the root `channels` to be a reference to a server under the root `servers`, so that the document says where the channel is. A reference to `components/servers`, or to another file, is reported. A root entry that is a reference to a channel under `components/channels` is checked as that channel, once however many entries name it; a channel under `components/channels` that no root entry names may refer to any server. A root entry that refers to another file is not checked. The rule reports `Channel server '<ref>' must be a reference to a server of the root servers ('#/servers/...')` on each server of the channel that is not under the root `servers`. The rule is the counterpart of the AsyncAPI parser's `asyncapi3-required-channel-servers-unambiguity`, which accepts a reference to another file's `servers` and skips root entries that are references. Turn the rule off for a spec that keeps its servers in another file: the linter does not read other files, and `asyncapi validate` accepts the reference. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 servers: production: host: broker.example.com:9092 protocol: kafka channels: petAdopted: address: pets.adopted servers: - $ref: '#/servers/production' ``` **Bad**. The channel names a server of `components`. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted servers: - $ref: '#/components/servers/production' components: servers: production: host: broker.example.com:9092 protocol: kafka ``` --- # cloudevents/attribute-schemas Source: https://apigenie.pl/docs/linter/asyncapi/rules/cloudevents-attribute-schemas A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.12.0. In the rulesets: CloudEvents at warning. This rule checks that the schemas of CloudEvents attributes say what the specification says of them. ## Rule details The schemas of the attributes are what validators, mocks and generated code know of them. The rule checks the attribute headers of binary-mode messages and the payload properties of structured-mode ones (other than `data` and `data_base64`): - `specversion` is pinned to `'1.0'`, with `const` or an `enum` of that one value; - the context attributes (`id`, `source`, `specversion`, `type`, `datacontenttype`, `dataschema`, `subject`, `time`) are strings when the schema gives a `type`; - `time` has `format: date-time`, `source` has `format: uri-reference` (or `uri`), `dataschema` has `format: uri`; - the names of extension attributes have lower-case letters and digits only, and at most 20 of them. MQTT 5 user properties carry attributes without a prefix, so their other names are not checked. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Shipments version: 1.0.0 servers: kafka: host: kafka.example.com:9092 protocol: kafka channels: shipments: address: shipments messages: created: headers: type: object properties: ce_specversion: const: '1.0' ce_source: type: string format: uri-reference ce_time: type: string format: date-time ce_partitionkey: type: string ``` **Bad**. `specversion` takes any string, `time` has no format, and `partitionKey` has an upper-case letter. ```yaml asyncapi: 3.0.0 info: title: Shipments version: 1.0.0 servers: kafka: host: kafka.example.com:9092 protocol: kafka channels: shipments: address: shipments messages: created: headers: type: object properties: ce_specversion: type: string ce_time: type: string ce_partitionKey: type: string ``` --- # cloudevents/binding-headers Source: https://apigenie.pl/docs/linter/asyncapi/rules/cloudevents-binding-headers A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.12.0. In the rulesets: CloudEvents at error. This rule checks that the attribute headers of binary-mode CloudEvents use the prefix of the protocol their channel is served over. ## Rule details Each protocol binding of CloudEvents names the headers of attributes its own way: `ce-` over HTTP, `ce_` over Kafka, `cloudEvents:` (or `cloudEvents_`) over AMQP, and no prefix for MQTT 5 user properties. SDKs and brokers look only for their binding's prefix, so a header named for another binding, such as `ce-id` on a Kafka topic, is not an attribute to them: the event arrives without it. The rule reports a header whose prefix is another binding's than those of the channel's servers (all servers when the channel lists none), and says what to name it. Headers with a prefix but no valid attribute name after it (`ce-not-an-attribute`) are not reported. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Shipments version: 1.0.0 servers: kafka: host: kafka.example.com:9092 protocol: kafka channels: shipments: address: shipments messages: created: headers: type: object properties: ce_specversion: const: '1.0' ce_id: type: string ``` **Bad**. `ce-id` is the HTTP name of the attribute; over Kafka it is `ce_id`. ```yaml asyncapi: 3.0.0 info: title: Shipments version: 1.0.0 servers: kafka: host: kafka.example.com:9092 protocol: kafka channels: shipments: address: shipments messages: created: headers: type: object properties: ce_specversion: const: '1.0' ce-id: type: string ``` --- # cloudevents/required-attributes Source: https://apigenie.pl/docs/linter/asyncapi/rules/cloudevents-required-attributes A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.12.0. In the rulesets: CloudEvents at error. This rule checks that every CloudEvents message declares and requires the four attributes every event has: `id`, `source`, `specversion` and `type`. ## Rule details A consumer that reads a CloudEvent relies on its required attributes: it routes on `type`, deduplicates on `source` and `id`, and checks `specversion`. A message that leaves one out, or declares it without requiring it, lets producers send events consumers can't process. In binary mode the attributes are headers, named with the prefix of the protocol binding of the channel's servers (all servers when the channel lists none): `ce-id` over HTTP, `ce_id` over Kafka, `cloudEvents:id` (or `cloudEvents_id`) over AMQP and `id` over MQTT 5. When the servers' protocols have no binary mode, the prefixes the headers use are taken. The rule reads the `headers` of the message's traits and of the message as AsyncAPI applies them: the properties of all, and the `required` of the last one that has it. A trait applied later with headers of its own (trace headers, a correlation id) replaces the `required` of an earlier CloudEvents trait, which the rule then reports. In structured mode the attributes are properties of the payload, `allOf` branches included. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Shipments version: 1.0.0 servers: kafka: host: kafka.example.com:9092 protocol: kafka channels: shipments: address: shipments messages: created: headers: type: object required: [ce_specversion, ce_id, ce_source, ce_type] properties: ce_specversion: const: '1.0' ce_id: type: string ce_source: type: string format: uri-reference ce_type: type: string ``` **Bad**. The `traced` trait comes last, so its `required` replaces the CloudEvents one. ```yaml asyncapi: 3.0.0 info: title: Shipments version: 1.0.0 servers: kafka: host: kafka.example.com:9092 protocol: kafka channels: shipments: address: shipments messages: created: traits: - $ref: '#/components/messageTraits/cloudEvent' - $ref: '#/components/messageTraits/traced' components: messageTraits: cloudEvent: headers: type: object required: [ce_specversion, ce_id, ce_source, ce_type] properties: ce_specversion: const: '1.0' ce_id: type: string ce_source: type: string ce_type: type: string traced: headers: type: object required: [traceparent] properties: traceparent: type: string ``` --- # contact-defined Source: https://apigenie.pl/docs/linter/asyncapi/rules/contact-defined A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks whether complete contact information is present in an AsyncAPI document. ## Rule details The `contact-defined` rule ensures that the `info.contact` object is defined and that its `name`, `email` and `url` properties are all present and not empty. Contact information tells consumers of the API whom to ask for help, report problems to, or notify about their use of the API. The rule reports: - `Contact object is missing` when there is no `info.contact` object, - `Contact name is missing or empty` when `name` is missing or empty, - `Contact email is missing` when `email` is missing or empty, - `Contact URL is missing` when `url` is missing or empty. Turn the rule off for APIs used only by the team that owns them. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 contact: name: Pet Platform Team email: pets@your-company.com url: https://your-company.com/teams/pets ``` **Bad**. The contact object is present, but it is not possible to reach the team by email. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 contact: name: Pet Platform Team url: https://your-company.com/teams/pets ``` --- # id-defined Source: https://apigenie.pl/docs/linter/asyncapi/rules/id-defined A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. Fixed by `--fix`. In the rulesets: Strict at error, All at error. This rule checks whether the application identifier (the root `id` field) is present in an AsyncAPI document, and whether its value matches the expected format. ## Rule details Uniquely identifying an application is essential for tracking and managing different versions of its API. Titles and file names change over time, and different applications may share a title. AsyncAPI provides the root `id` field for this purpose; the specification requires its value to be a URI (for example a URN). The `id-defined` rule ensures that the `id` field is defined, and that its value matches the configured pattern. The rule reports `Application identifier (id) is missing` when the field is absent, and `Application identifier (id) has invalid format` when its value does not match the pattern. ## Configuration The rule configuration must be an object with a single optional attribute, `pattern`, which specifies the expected format of the identifier. When given, it must be a non-empty string: - `uri` (the default) - any absolute URI, i.e. a scheme followed by a colon and at least one non-whitespace character (e.g. `urn:example:pets` or `https://your-company.com/apis/pets`), - `uuid` - a UUID URN, i.e. `urn:uuid:` followed by a UUID (e.g. `urn:uuid:9c9c1d3c-3d4c-4a8e-9f54-0b2f7d7e6c11`), - any other string is treated as an ECMAScript regular expression, which must match the whole identifier. **Configuration example**. The following configuration requires the identifier to be a UUID URN. ```yaml version: "1.0" commands: lint: asyncapi: rules: id-defined: - error - pattern: uuid ``` **Configuration example**. The following configuration requires the identifier to be a URN in the `your-company` namespace. ```yaml version: "1.0" commands: lint: asyncapi: rules: id-defined: - error - pattern: "urn:your-company:[a-z-]+" ``` ## Examples **Good**. The application can be tracked independently of its title and version. ```yaml asyncapi: 3.0.0 id: urn:uuid:9c9c1d3c-3d4c-4a8e-9f54-0b2f7d7e6c11 info: title: Pet Events version: 1.2.8 ``` **Bad**. There is no identifier, so it is difficult to track the evolution of the API. Renaming the file, or creating a different API with the same title, leads to ambiguities. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.2.4 ``` **Bad**. The identifier is not a URI. ```yaml asyncapi: 3.0.0 id: pet events info: title: Pet Events version: 1.2.8 ``` ## Automatic fixes If `pattern` is `uri` or `uuid`, this rule is auto-fixing. When the linter is invoked with the `--fix` option, it sets the `id` field to a newly generated UUID URN (`urn:uuid:` followed by a random UUID v4). An existing identifier with an invalid format is replaced. Identifiers checked against a custom regular expression are not fixed. --- # info-defined Source: https://apigenie.pl/docs/linter/asyncapi/rules/info-defined A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether the info object of an AsyncAPI document provides a description and a version. ## Rule details The info object is the first thing readers of an API see. Besides the mandatory title, it should explain what the application does and which version of the API is being described. The `info-defined` rule reports: - `Info description is missing or empty` when `info.description` is missing or empty, - `Info version is empty` when `info.version` is an empty string. The title is required by the AsyncAPI specification itself and is not checked by this rule. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 description: Events published when pets are adopted, returned or updated. ``` **Bad**. The document does not explain what the application does, and its version is empty. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: "" ``` --- # latest-version Source: https://apigenie.pl/docs/linter/asyncapi/rules/latest-version A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.12.0. In the rulesets: Strict at hint, All at hint. This rule suggests the latest version of AsyncAPI, 3.1.0, to a document that declares an older one. ## Rule details AsyncAPI 3.1 is a minor release of 3.0, so a 3.0 document stays valid when its `asyncapi` field says 3.1.0. The rule compares that field with 3.1.0 as versions: `3.1.0` and later pass, `3.0.0` and `3.1.0-rc1` get the suggestion. It reports `AsyncAPI <version> is not the latest version of the specification, 3.1.0 is` on the document. The rule is not in `recommended`. It is the counterpart of the AsyncAPI parser's `asyncapi-latest-version`. Turn it off while a tool that reads your documents supports only AsyncAPI 3.0. ## Examples **Good**. ```yaml asyncapi: 3.1.0 info: title: Pet Events version: 1.0.0 ``` **Bad**. 3.0.0 is an older version. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 ``` --- # license-defined Source: https://apigenie.pl/docs/linter/asyncapi/rules/license-defined A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks whether the licensing information is present in an AsyncAPI document. ## Rule details The license says what a consumer may do with the API and with the code generated from its document; without it, a consumer outside the team has to ask. The rule checks that `info.license` exists with a `name` and a `url`. The rule reports: - `License object is missing` when there is no `info.license` object, - `License name is empty` when `name` is empty, - `License URL is missing or empty` when `url` is missing or empty. Unlike OpenAPI 3.1, AsyncAPI license objects have no SPDX `identifier` field, so the rule always requires a URL. Turn the rule off for APIs used only by the team that owns them. ## Examples **Good**. The document provides a link to its license, thus making it easier to understand how the API can be used. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 license: name: Apache 2.0 url: https://www.apache.org/licenses/LICENSE-2.0 ``` **Bad**. The license has a name, but no link to its terms. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 license: name: Proprietary ``` --- # operation-channel-in-channels Source: https://apigenie.pl/docs/linter/asyncapi/rules/operation-channel-in-channels A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.12.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the channel of an operation under the root `operations` is a reference to a channel under the root `channels`. ## Rule details An operation names the channel it sends to or receives from with a reference. The specification requires the operations under the root `operations` to point at a channel under the root `channels`, and at no other place, so that every channel the application uses is listed there. A reference to `components/channels`, or to another file, is reported. A root entry that is a reference to an operation under `components/operations` is checked as that operation, once however many entries name it; an operation under `components/operations` that no root entry names may refer to any channel. A root entry that refers to another file is not checked. The rule reports `Operation channel '<ref>' must be a reference to a channel of the root channels ('#/channels/...')` on the operation's `channel`. The rule is the counterpart of the AsyncAPI parser's `asyncapi3-required-operation-channel-unambiguity`, which accepts a reference to another file's `channels` and skips root entries that are references. Turn the rule off for a spec that keeps its channels in another file: the linter does not read other files, and `asyncapi validate` accepts the reference. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted operations: onPetAdopted: action: receive channel: $ref: '#/channels/petAdopted' ``` **Bad**. The operation's channel is under `components`. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 operations: onPetAdopted: action: receive channel: $ref: '#/components/channels/petAdopted' components: channels: petAdopted: address: pets.adopted ``` --- # operation-description-defined Source: https://apigenie.pl/docs/linter/asyncapi/rules/operation-description-defined A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether every operation of an AsyncAPI document has a meaningful description. ## Rule details An operation describes what the application does with a channel: whether it sends or receives messages, and why. A good description explains when the messages are produced or consumed, and what the application does with them. The `operation-description-defined` rule reports `Operation has no meaningful description` for every operation (in the root `operations` map and in `components/operations`) whose `description` is missing or shorter than the configured minimal length. Descriptions coming from operation traits are not taken into account. ## Configuration The configuration block is a positive integer: the minimal length of a description, in characters. The default value is `10`. **Configuration example**. The following configuration requires operation descriptions to be at least 30 characters long. ```yaml version: "1.0" commands: lint: asyncapi: rules: operation-description-defined: [error, 30] ``` ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted operations: onPetAdopted: action: receive channel: $ref: "#/channels/petAdopted" description: Updates the shelter inventory when a pet is adopted. ``` **Bad**. The operation has no description. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted operations: onPetAdopted: action: receive channel: $ref: "#/channels/petAdopted" ``` **Bad**. The description is too short to be useful. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted operations: onPetAdopted: action: receive channel: $ref: "#/channels/petAdopted" description: Adopted ``` --- # operation-messages-from-channel Source: https://apigenie.pl/docs/linter/asyncapi/rules/operation-messages-from-channel A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.12.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the messages of an operation, and of its reply, are references to messages of the channel that the operation, or the reply, references. ## Rule details An operation's `messages` lists which of its channel's messages it sends or receives. The specification requires each entry to be a reference to a message of that channel, so with the channel `#/channels/pet`, every entry starts with `#/channels/pet/messages/`. A reference to the same message under `components/messages` is reported too: it says nothing about the channel. The same holds for the `messages` of a reply that has a `channel`. The rule compares references as written: a message in another file is reported, unless the channel is a reference into the same file and the message is under that channel. The rule checks operations under `operations` and `components/operations`, and replies under `components/replies`, where each is defined. A reference to one is not checked again. The rule reports `Operation message '<ref>' must be a reference to a message of its channel ('<channel>/messages/...')`. For a reply, the message starts with `Reply message` instead. The rule is the counterpart of the AsyncAPI parser's `asyncapi3-operation-messages-from-referred-channel`, which does not check replies. Turn the rule off for a spec whose channels are in this file and whose operations name their messages in another file: the linter does not read other files, and `asyncapi validate` accepts the reference. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: pet: address: pets messages: petAdopted: $ref: '#/components/messages/petAdopted' operations: onPetAdopted: action: receive channel: $ref: '#/channels/pet' messages: - $ref: '#/channels/pet/messages/petAdopted' components: messages: petAdopted: payload: type: object ``` **Bad**. The operation names the message under `components`. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: pet: address: pets messages: petAdopted: $ref: '#/components/messages/petAdopted' operations: onPetAdopted: action: receive channel: $ref: '#/channels/pet' messages: - $ref: '#/components/messages/petAdopted' components: messages: petAdopted: payload: type: object ``` --- # operation-security-defined Source: https://apigenie.pl/docs/linter/asyncapi/rules/operation-security-defined A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks whether every operation of an AsyncAPI document is protected by a security requirement. ## Rule details In AsyncAPI 3.x, security requirements can be declared on operations, on operation traits, and on servers. The `operation-security-defined` rule reports `Security requirement is not defined` for every operation that is secured in none of the following ways: - the operation has a non-empty `security` list, - at least one of the operation's traits has a non-empty `security` list, - every server the operation is available on has a non-empty `security` list. The servers of an operation are the servers listed in the `servers` field of its channel or, when the channel does not list any servers, all servers of the document. An operation whose channel lists no servers in a document that has no servers at all, or whose channel reference cannot be resolved, is not considered secured by servers. Turn the rule off for APIs that are intentionally public, or that are available only inside a trusted network. ## Examples **Good**. The operation declares its own security requirement. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted operations: publishPetAdopted: action: send channel: $ref: "#/channels/petAdopted" security: - $ref: "#/components/securitySchemes/apiKey" components: securitySchemes: apiKey: type: httpApiKey name: X-API-Key in: header ``` **Good**. The only server of the channel requires authentication. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 servers: production: host: broker.your-company.com:9093 protocol: kafka-secure security: - $ref: "#/components/securitySchemes/saslScram" channels: petAdopted: address: pets.adopted servers: - $ref: "#/servers/production" operations: onPetAdopted: action: receive channel: $ref: "#/channels/petAdopted" components: securitySchemes: saslScram: type: scramSha512 ``` **Bad**. The channel is available on all servers, and one of them does not require authentication. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 servers: production: host: broker.your-company.com:9093 protocol: kafka-secure security: - $ref: "#/components/securitySchemes/saslScram" legacy: host: legacy.your-company.com:9092 protocol: kafka channels: petAdopted: address: pets.adopted operations: onPetAdopted: action: receive channel: $ref: "#/channels/petAdopted" components: securitySchemes: saslScram: type: scramSha512 ``` --- # operation-tags-defined Source: https://apigenie.pl/docs/linter/asyncapi/rules/operation-tags-defined A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks whether every operation of an AsyncAPI document has at least one tag assigned. ## Rule details Tags group related operations. Documentation generators use them to organize operations into sections, and consumers use them to find the operations they are interested in. The `operation-tags-defined` rule reports `Operation has no tags defined` for every operation (in the root `operations` map and in `components/operations`) whose own `tags` list is missing or empty. Tags coming from operation traits are not taken into account. Turn the rule off for small APIs, whose operations do not need to be grouped. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted operations: onPetAdopted: action: receive channel: $ref: "#/channels/petAdopted" tags: - name: adoption ``` **Bad**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted operations: onPetAdopted: action: receive channel: $ref: "#/channels/petAdopted" ``` --- # parameter-description-defined Source: https://apigenie.pl/docs/linter/asyncapi/rules/parameter-description-defined A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks whether every channel parameter of an AsyncAPI document has a meaningful description. ## Rule details Channel parameters are the variable parts of channel addresses, such as `userId` in `users.{userId}.signedUp`. A description explains what the parameter identifies and which values it may take. The `parameter-description-defined` rule checks the entries of the `parameters` map of every channel (in the root `channels` map and in `components/channels`), as well as the entries of `components/parameters`. References are checked where the referenced parameter is defined. The rule reports `Parameter '<name>' has no meaningful description` for every parameter whose description: - is missing, empty or blank, - is shorter than the configured minimal length, - is a placeholder: `TODO`, `FIXME` or `TBD` (case-insensitive). ## Configuration The configuration block is a positive integer: the minimal length of a description, in characters. The default value is `10`. **Configuration example**. The following configuration requires parameter descriptions to be at least 20 characters long. ```yaml version: "1.0" commands: lint: asyncapi: rules: parameter-description-defined: [warning, 20] ``` ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 channels: userSignedUp: address: users.{userId}.signedUp parameters: userId: description: Identifier of the user who signed up. ``` **Bad**. The first parameter has no description at all, the second one has a placeholder. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 channels: userSignedUp: address: users.{region}.{userId}.signedUp parameters: region: {} userId: description: TODO ``` --- # parameter-naming Source: https://apigenie.pl/docs/linter/asyncapi/rules/parameter-naming A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks all channel parameters in an AsyncAPI document and warns if their names do not adhere to the specified naming convention. ## Rule details A consumer who has seen one parameter should be able to spell the next. In AsyncAPI 3.x, the name of a parameter is its key in the `parameters` map, which is the same name that appears between braces in the channel address. The rule checks the parameters of every channel (in the root `channels` map and in `components/channels`), as well as the entries of `components/parameters`. For every parameter whose name is not in the expected convention, it reports `Parameter should be named <name>`, where `<name>` is the parameter name converted to that convention. The recognised naming conventions are: - `CONST_CASE` (also `UPPER_CASE` and `SCREAMING_SNAKE_CASE`) - THIS_IS_CONST_CASE - `camelCase` - thisIsCamelCase, also with acronyms (userID) - `camelCaseStrict` - thisIsCamelCase, but no two capitals in a row (userId, not userID) - `kebab-case` - this-is-kebab-case - `PascalCase` - ThisIsPascalCase, also with acronyms (HTTPServer) - `PascalCaseStrict` - ThisIsPascalCase, but no two capitals in a row (HttpServer, not HTTPServer) - `Header-Case` - This-Is-Header-Case - `snake_case` - this_is_snake_case The default convention is `snake_case`. Unlike OpenAPI, AsyncAPI parameters have no location (path, query, header or cookie), so a single convention applies to all of them. ## Configuration The configuration block can be a string or an object. If it is a string, its value is the name of the naming convention (see the "Rule details" section for a list of recognized names). If it is an object, it must contain the `default` property, whose value is the name of the naming convention. Other properties are ignored. **Configuration example**. The following two examples are equivalent. They specify that the expected naming convention for all parameters is `camelCase`. ```yaml version: "1.0" commands: lint: asyncapi: rules: parameter-naming: [warning, camelCase] ``` ```yaml version: "1.0" commands: lint: asyncapi: rules: parameter-naming: - warning - default: camelCase ``` ## Examples **Good**. With the default configuration. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 channels: userSignedUp: address: users.{user_id}.signedUp parameters: user_id: description: Identifier of the user. ``` **Bad**. With the default configuration, the linter reports `Parameter should be named user_id`. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 channels: userSignedUp: address: users.{userId}.signedUp parameters: userId: description: Identifier of the user. ``` --- # safe-markdown Source: https://apigenie.pl/docs/linter/asyncapi/rules/safe-markdown A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule ensures that Markdown strings (descriptions) do not contain unsafe constructs like script tags or `eval()` calls. ## Rule details Unsafe constructs embedded in Markdown strings can pose security risks when the documentation is rendered, for example by a documentation portal. The `safe-markdown` rule checks the `description` field of every object that supports CommonMark descriptions: the info object, servers, server variables, channels, parameters, operations, operation traits, operation reply addresses, messages, message traits, correlation IDs, tags, external documentation, schemas and security schemes. It reports: - `Markdown contains <script> tag` when a description contains a `script` element, - `Markdown contains eval() function` when a description contains an `eval()` call. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 description: Events published when pets are adopted or returned. ``` **Bad**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 description: "Events published when pets are adopted. <script>alert('Unsafe')</script>" ``` ## Automatic fixes `--fix` escapes the delimiters of recognized script elements and `eval()` calls. It preserves the surrounding Markdown and does not alter code spans or fenced code blocks. --- # schema-constraints Source: https://apigenie.pl/docs/linter/asyncapi/rules/schema-constraints A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at warning. This rule ensures that schema objects define constraints restricting the size of the underlying data. ## Rule details A schema without bounds accepts a 2 GB string in a name and an array of a million items in a message: the consumer that stores them is the first to find out. Bounds in the document are checked by validators, and generated code picks the right types. The `schema-constraints` rule checks every schema of an AsyncAPI document (component schemas, message payloads and headers, parameter schemas, and all schemas nested in them) and requires, depending on the schema type: - integers - both a lower bound (`minimum` or `exclusiveMinimum`) and an upper bound (`maximum` or `exclusiveMaximum`), - numbers - both a lower bound and an upper bound, as for integers, - strings - `maxLength`, `pattern`, `format` or `enum`, - arrays - `maxItems`, - objects - `maxProperties`, or `additionalProperties: false`. A schema with several types (e.g. `type: [string, integer]`) is checked for each of them. The reported messages are `Integer schema does not define constraints restricting its range`, `Numeric schema does not define constraints restricting its range`, `String schema does not define constraints restricting its length`, `Array schema does not define constraints restricting its size` and `Object schema does not define constraints restricting its size`. Turn the rule off when the API does not bound its values. ## Configuration The configuration should be an object whose keys are supported schema types, and values are boolean values. Only the types set to `true` are checked, and at least one schema type must be set to `true`. Supported schema types are `integer`, `number`, `string`, `array` and `object`. By default, constraints for all supported schema types are verified. The `recommended` ruleset checks only `number` and `string` schemas. **Configuration example**. The rule with the following configuration checks only array and object schemas, and does not check numbers and strings. ```yaml version: "1.0" commands: lint: asyncapi: rules: schema-constraints: - warning - array: true object: true ``` ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 components: schemas: User: type: object properties: username: type: string maxLength: 20 pattern: "^[a-z0-9_-]{3,16}$" roles: type: array items: type: string enum: [admin, member] maxItems: 5 age: type: integer minimum: 18 maximum: 100 maxProperties: 3 ``` **Bad**. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 components: schemas: User: type: object properties: username: type: string roles: type: array items: type: string age: type: integer ``` --- # schema-datetime-suffix Source: https://apigenie.pl/docs/linter/asyncapi/rules/schema-datetime-suffix A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule ensures that the names of date and time properties end with a common suffix. ## Rule details A consistent suffix makes temporal properties easy to recognize, and distinguishes them from other properties describing the same concept (e.g. `created_at` versus `created_by`). The `schema-datetime-suffix` rule checks the properties of every object schema of an AsyncAPI document. For every property whose schema has the `date`, `date-time` or `time` format and whose name does not end with the configured suffix, it reports `Property name <name> should end with <suffix>`. The issue is reported at the property itself, not at a (possibly shared) referenced schema. The default suffix is `_at`. Turn the rule off if your API follows a different convention for naming temporal properties. ## Configuration The configuration block is a non-empty string: the required suffix. **Configuration example**. The following configuration requires temporal properties to end with `At`, which fits camelCase property names. ```yaml version: "1.0" commands: lint: asyncapi: rules: schema-datetime-suffix: [warning, At] ``` ## Examples **Good**. With the default configuration. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 components: schemas: PetAdopted: type: object properties: adopted_at: type: string format: date-time ``` **Bad**. With the default configuration. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 components: schemas: PetAdopted: type: object properties: adoption_date: type: string format: date-time ``` --- # schema-enum-naming Source: https://apigenie.pl/docs/linter/asyncapi/rules/schema-enum-naming A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule ensures that all string values defined in the `enum` properties of schema objects adhere to a predefined naming convention. ## Rule details Enum values are spelled by every consumer, in code and in messages, so a consumer who has seen one should be able to spell the next. The `schema-enum-naming` rule checks the string values of the `enum` list of every schema of an AsyncAPI document. For every value that is not in the expected convention, it reports `Schema enum value '<value>' is not in the '<convention>' convention`. Values of other types (numbers, booleans, `null`, ...) are ignored. The recognised naming conventions are: - `CONST_CASE` (also `UPPER_CASE` and `SCREAMING_SNAKE_CASE`) - THIS_IS_CONST_CASE - `camelCase` - thisIsCamelCase, also with acronyms (userID) - `camelCaseStrict` - thisIsCamelCase, but no two capitals in a row (userId, not userID) - `kebab-case` - this-is-kebab-case - `PascalCase` - ThisIsPascalCase, also with acronyms (HTTPServer) - `PascalCaseStrict` - ThisIsPascalCase, but no two capitals in a row (HttpServer, not HTTPServer) - `Header-Case` - This-Is-Header-Case - `snake_case` - this_is_snake_case The default convention is `CONST_CASE`. Turn the rule off when the API follows no naming convention for `enum` values in its schema objects. ## Configuration The configuration block is a naming convention name (see the "Rule details" section for a list of recognized names). ```yaml version: "1.0" commands: lint: asyncapi: rules: schema-enum-naming: [warning, kebab-case] ``` ## Examples **Good**. With the default configuration. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 components: schemas: UserStatus: type: string enum: - ACTIVE - INACTIVE - BLOCKED ``` **Bad**. To use `UserStatus` properly, a consumer must always consult the documentation. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 components: schemas: UserStatus: type: string enum: - activeStatus - inactive_status - BLOCKED_STATUS ``` --- # schema-enum-no-duplicates Source: https://apigenie.pl/docs/linter/asyncapi/rules/schema-enum-no-duplicates A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule ensures that the `enum` lists of schema objects contain no duplicate values. ## Rule details Duplicate enum values carry no information, and usually indicate a typo or a merge mistake (for example, a value that was meant to be different). The `schema-enum-no-duplicates` rule checks the `enum` list of every schema of an AsyncAPI document, and reports `Duplicate enum value` once for every value that repeats an earlier value of the same list. Values of any type are compared, including numbers, objects and arrays. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 components: schemas: PetStatus: type: string enum: [AVAILABLE, ADOPTED, RETURNED] ``` **Bad**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 components: schemas: PetStatus: type: string enum: [AVAILABLE, ADOPTED, AVAILABLE] ``` ## Automatic fixes `--fix` removes the duplicate values, keeping the first occurrence of each value. --- # schema-enum-types Source: https://apigenie.pl/docs/linter/asyncapi/rules/schema-enum-types A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule ensures that the values listed in the `enum` of a schema are allowed by the schema's `type`. ## Rule details An enum value whose type is not allowed by the schema can never be sent or received: a message containing it would fail validation. Such values usually come from a missing or wrong `type`, or from unquoted YAML values (e.g. `yes`, `1.0`) that are parsed as something other than strings. The `schema-enum-types` rule checks every schema of an AsyncAPI document that has an `enum` list, and reports `Enum value type is not in the schema type` when one of the values is not allowed by the schema's `type`: - strings require `string`, booleans require `boolean`, `null` requires `null`, arrays require `array` and objects require `object`, - integer values require `integer` or `number`, - other numeric values require `number`. A schema that has an `enum` but no `type` is reported as well, since none of its values is allowed by an explicit type. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 components: schemas: PetStatus: type: [string, "null"] enum: [AVAILABLE, ADOPTED, null] Rating: type: number enum: [1, 2.5, 5] ``` **Bad**. The values are integers, but the schema allows only strings. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 components: schemas: Priority: type: string enum: [1, 2, 3] ``` ## Automatic fixes `--fix` sets the `type` of a reported schema to the type of its enum values, provided that all values have the same type and the schema has no `format`. In the "Bad" example above, the type of `Priority` is changed to `integer`. Schemas mixing values of different types are not fixed. --- # schema-example-defined Source: https://apigenie.pl/docs/linter/asyncapi/rules/schema-example-defined A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule ensures that top-level schemas of an AsyncAPI document provide examples. ## Rule details Examples make schemas easier to understand, and are used by documentation generators, mock servers and test tools to produce realistic messages. The `schema-example-defined` rule checks top-level schemas only; nested schemas (such as properties or array items) are not checked. Top-level schemas are: - the entries of `components/schemas` (references are skipped). The rule reports `Schema does not define examples` for these. - inline message payloads, i.e. payloads that are not references. The rule reports `Message payload schema does not define examples` for these. Referenced payloads are checked as component schemas. A schema counts as having examples when it has a non-empty `examples` list, when it has a `const` value, or when it is a boolean schema (`true` or `false`). In addition, a message whose `examples` list contains at least one example with a `payload` counts as providing examples for its inline payload. Turn the rule off if your documentation and tooling do not use examples. ## Examples **Good**. The component schema has its own examples, and the inline payload is illustrated by a message example. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted messages: petAdopted: payload: type: object properties: name: type: string examples: - payload: name: Rex components: schemas: PetStatus: type: string enum: [AVAILABLE, ADOPTED] examples: [AVAILABLE] ``` **Bad**. Neither the component schema nor the inline payload provide examples. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted messages: petAdopted: payload: type: object properties: name: type: string components: schemas: PetStatus: type: string enum: [AVAILABLE, ADOPTED] ``` --- # schema-format-defined Source: https://apigenie.pl/docs/linter/asyncapi/rules/schema-format-defined A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule ensures that numeric schemas specify the precision of their values with a `format`. ## Rule details JSON Schema does not limit the size or the precision of numbers. Without a `format`, code generators and consumers written in strongly typed languages have to guess which native type to use, which often leads to overflows or to lost precision. The `schema-format-defined` rule checks every schema of an AsyncAPI document and reports: - `Schema with integer type does not define proper format` when a schema of type `integer` does not have the `int32` or `int64` format, - `Schema with number type does not define proper format` when a schema of type `number` does not have the `float` or `double` format. Turn the rule off if your messages are consumed only by clients written in dynamically typed languages, where the precision of numbers does not matter. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Order Events version: 1.0.0 components: schemas: OrderPlaced: type: object properties: quantity: type: integer format: int32 total: type: number format: double ``` **Bad**. ```yaml asyncapi: 3.0.0 info: title: Order Events version: 1.0.0 components: schemas: OrderPlaced: type: object properties: quantity: type: integer total: type: number format: decimal ``` --- # schema-format-deprecated Source: https://apigenie.pl/docs/linter/asyncapi/rules/schema-format-deprecated A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.10.0. In the rulesets: Recommended at warning, Strict at warning, All at warning. This rule reports the formats which the [OpenAPI format registry](https://spec.openapis.org/registry/format/) marks as deprecated from OpenAPI 3.1, and names what replaces them. ## Rule details | Format | Use instead | | ------ | ----------- | | `byte` | `contentEncoding: base64` | | `base64url` | `contentEncoding: base64url` | | `binary` | `contentMediaType`, or the media type of the body or part without a schema | AsyncAPI schemas are a superset of JSON Schema draft 7, which has `contentEncoding` and `contentMediaType`, so the issues are warnings in AsyncAPI 2.x and 3.x documents. See [Formats](/docs/reference/cli/formats) for every format. Turn the rule off when the documents must stay readable by tools that only know the older formats. ## Examples **Good**. ```yaml asyncapi: 3.0.0 components: schemas: Avatar: type: string contentEncoding: base64 ``` **Bad**. ```yaml asyncapi: 3.0.0 components: schemas: Avatar: type: string format: byte ``` --- # schema-format-type-mismatch Source: https://apigenie.pl/docs/linter/asyncapi/rules/schema-format-type-mismatch A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule ensures that the `format` of a schema is consistent with its `type`. ## Rule details Formats apply to values of specific types. A schema such as `type: integer, format: email` is contradictory: validators ignore the format, and code generators produce unexpected types. The `schema-format-type-mismatch` rule checks every schema of an AsyncAPI document whose `format` is in the [OpenAPI format registry](https://spec.openapis.org/registry/format/) or in `openapi.custom_formats` of the configuration file, and reports `Schema type and format do not match` when none of the schema's types is a JSON type of the format: - the integer formats (`int8` to `uint64`, `int32`, `int64`, `double-int`, `sf-integer`) need `integer` or `number`, and `int64` and `uint64` also allow `string`; - `float`, `double` and `sf-decimal` need `number`; - `decimal` and `decimal128` allow `string` and `number`, `unixtime` also `integer`; - the others (`date`, `date-time`, `uuid`, `email`, `http-date`, ...) need `string`. A schema with one of these formats but without a `type` is reported as well. Other formats are left to [schema-format-unknown](/docs/linter/asyncapi/rules/schema-format-unknown). The [Formats](/docs/reference/cli/formats) page lists every format. ## Configuration The configuration block is an object with a single optional boolean property, `fixTypeFromFormat`, which controls whether reported issues can be fixed automatically (see "Automatic fixes"). The default value is `true`. **Configuration example**. The following configuration reports mismatches, but does not fix them. ```yaml version: "1.0" commands: lint: asyncapi: rules: schema-format-type-mismatch: - error - fixTypeFromFormat: false ``` ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 components: schemas: UserSignedUp: type: object properties: email: type: string format: email signed_up_at: type: string format: date-time ``` **Bad**. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 components: schemas: UserSignedUp: type: object properties: email: type: integer format: email signed_up_at: format: date-time ``` ## Automatic fixes When `fixTypeFromFormat` is `true` and the linter is invoked with the `--fix` option, this rule sets the `type` of every reported schema to the type the format applies to. In the "Bad" example above, both properties get `type: string`. --- # schema-format-unknown Source: https://apigenie.pl/docs/linter/asyncapi/rules/schema-format-unknown A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.10.0. In the rulesets: Strict at warning, All at warning. This rule reports a `format` of an AsyncAPI document which is neither in the [OpenAPI format registry](https://spec.openapis.org/registry/format/) nor declared in `openapi.custom_formats` of the [configuration file](/docs/reference/cli/configuration#openapicustom_formats). ## Rule details Tools ignore formats they do not know, so a misspelled format (`date_time`, `uuid4`) stops being checked without a word. Formats defined on purpose are declared in the configuration file: ```yaml openapi: custom_formats: - {name: currency-code, type: string} ``` The rule is off in the `recommended` ruleset and a warning in `strict` and `all`. See [Formats](/docs/reference/cli/formats) for the registry's formats. Turn the rule off when the documents use many formats of their own and listing them in the configuration file is not worth it. ## Examples **Good**. `uuid` is in the registry. ```yaml asyncapi: 3.0.0 info: title: Order Events version: 1.0.0 components: schemas: OrderId: type: string format: uuid ``` **Bad**. `uuid4` is not, so nothing checks the value. ```yaml asyncapi: 3.0.0 info: title: Order Events version: 1.0.0 components: schemas: OrderId: type: string format: uuid4 ``` --- # schema-keyword-support Source: https://apigenie.pl/docs/linter/asyncapi/rules/schema-keyword-support A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.11.0. In the rulesets: All at warning. This rule reports schema keywords that the tools consuming the document are unlikely to support, and suggests the rewrite where one exists. ## Rule details The AsyncAPI Schema Object is a superset of JSON Schema draft-07, yet schemas copied from OpenAPI 3.1 or from JSON Schema 2020-12 documents bring keywords of the later drafts along. AsyncAPI tools, draft-07 validators and most code generators ignore the keywords they don't know, so `unevaluatedProperties: false` stops rejecting anything, a `prefixItems` tuple turns into an untyped array and an `if`/`then` constraint silently disappears from the generated client. The rule checks each schema against one or more **targets** and reports, once per keyword, the first target that does not support it: | Target | Who it stands for | | ------ | ----------------- | | `draft4` | Validators stuck at draft-04, e.g. NJsonSchema's default dialect, older PHP and Python libraries | | `draft6` | Draft-06 validators | | `draft7` | Validators stopping at draft-07: gojsonschema, everit-org/json-schema, Ajv's default export; also the default schema dialect of AsyncAPI 2.x and 3.0 | | `draft2019-09` | Validators without draft 2020-12 | | `openapi30` | The Schema Object of OpenAPI 3.0 and the tools built for it, e.g. NSwag | | `codegen` | The keywords most code generators ignore or can't express in types (the default) | What each target lacks, and the suggested rewrite: | Keyword or form | Not supported by | Suggested rewrite | | --------------- | ---------------- | ----------------- | | `unevaluatedProperties` | drafts 4 to 7, `openapi30`, `codegen` | merge the `allOf` members into one schema and use `additionalProperties` | | `unevaluatedItems` | drafts 4 to 7 | `additionalItems` next to the array form of `items` | | `unevaluatedItems` | `openapi30`, `codegen` | none | | `prefixItems` | drafts 4 to 2019-09 | the array form of `items`, `additionalItems` for the rest | | `prefixItems` | `openapi30`, `codegen` | an object with named properties | | `$dynamicRef`, `$recursiveRef` | drafts 4 to 7, `openapi30`, `codegen` | `$ref` to the schema it resolves to | | `$dynamicRef` | `draft2019-09` | `$recursiveRef` | | `$dynamicAnchor`, `$recursiveAnchor` | drafts 4 to 7, `openapi30`, `codegen` | drop it once the reference to it is a `$ref` | | `$anchor` | drafts 4 to 7, `openapi30`, `codegen` | reference the schema by a JSON pointer | | `$vocabulary` | drafts 4 to 7, `openapi30`, `codegen` | drop it | | `$defs` | drafts 4 to 7 | `definitions` | | `$defs` | `openapi30` | move the schemas to `components/schemas` | | `dependentRequired` | drafts 4 to 7 | `dependencies` with an array of property names | | `dependentSchemas` | drafts 4 to 7 | `dependencies` with a schema | | `dependentRequired`, `dependentSchemas`, `dependencies` | `openapi30`, `codegen` | none | | `dependencies` | `draft2019-09` | `dependentRequired` or `dependentSchemas` | | `if` (with `then`/`else`) | `draft4`, `draft6`, `openapi30`, `codegen` | `oneOf` with one alternative per case | | `contentSchema`, `minContains`, `maxContains` | drafts 4 to 7, `openapi30`, `codegen` | none | | `contains` | `draft4`, `openapi30`, `codegen` | none | | `propertyNames` | `draft4`, `openapi30` | none | | `const` | `draft4`, `openapi30` | an `enum` with one value | | `patternProperties` | `openapi30` | `properties` for fixed names, `additionalProperties` for the rest | | `patternProperties` | `codegen` | `additionalProperties` | | `not` | `codegen` | none | | `additionalItems` | `openapi30` | none | | `$id`, `$schema`, `$comment`, `examples`, `contentEncoding`, `contentMediaType` | `openapi30` | drop `$id` and `$schema`; `description` for `$comment`; `example`; `format: byte` or `format: binary` | | `$id` | `draft4` | `id` | | a `type` array | `openapi30` | one `type` with `nullable: true`, or `anyOf` | | a `type` array of several non-null types | `codegen` | `oneOf` with one schema per type | | `type: null` | `openapi30` | `nullable: true` | | a numeric `exclusiveMinimum`/`exclusiveMaximum` | `draft4`, `openapi30` | `minimum`/`maximum` with the boolean form | | a boolean `exclusiveMinimum`/`exclusiveMaximum` | drafts 6 to 2019-09 | the bound as the value | | `nullable: true` | drafts 4 to 2019-09 | add `"null"` to `type` | | `$ref` with keywords that constrain the value | drafts 4 to 7, `openapi30`, `codegen` | wrap the reference in `allOf`; the siblings are ignored otherwise | Annotations a validator ignores without harm (`description`, `examples`, `readOnly`, `deprecated`, `$comment`, the content keywords) are reported only for `openapi30`, whose Schema Object allows no keywords besides its own and `x-` extensions. `then` and `else` are covered by the report on `if`. A `$ref` next to annotations only (`description`, `summary`, `example`, ...) is not reported. `apigenie convert --from jsonschema --to draft7|draft4|openapi30` performs most of these rewrites on a standalone JSON Schema document, including the `allOf` flattening that replaces `unevaluatedProperties`. Turn the rule off when every consumer of the document is known to support JSON Schema 2020-12 in full, for example a validator such as Ajv 2020, networknt, santhosh-tekuri/jsonschema or Python's jsonschema, and no code is generated from it. ## Configuration The options are a target name, an array of target names, or an object with: - `targets`: a target name or an array of target names; `codegen` when omitted. - `allow`: keywords never reported, for the ones your tools are known to support. **Configuration example 1**. Find the keywords AsyncAPI's draft-07 dialect doesn't have. ```yaml commands: lint: asyncapi: rules: schema-keyword-support: - warning - draft7 ``` **Configuration example 2**. Check against draft-07 validators and the code generators, accepting `not`. ```yaml commands: lint: asyncapi: rules: schema-keyword-support: - warning - targets: [draft7, codegen] allow: [not] ``` ## Examples **Good**. A closed object that every target understands. ```yaml components: schemas: Pet: type: object required: [name] properties: name: type: string additionalProperties: false ``` **Bad**. `unevaluatedProperties` is not an AsyncAPI keyword, and draft-07 validators and most code generators ignore it, so they accept any extra property. ```yaml components: schemas: Pet: allOf: - $ref: '#/components/schemas/Animal' properties: name: type: string unevaluatedProperties: false ``` --- # schema-no-additional-properties Source: https://apigenie.pl/docs/linter/asyncapi/rules/schema-no-additional-properties A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule ensures that object schemas explicitly disallow additional properties. ## Rule details By default, JSON Schema allows objects to contain properties that are not listed in `properties`. Messages containing unexpected properties are then considered valid, which hides typos and makes it easy to leak data that was never meant to be published. The `schema-no-additional-properties` rule reports `Object schema does not disable additional properties` for every schema of type `object` that does not have `additionalProperties: false`. Turn the rule off if your messages are designed to be extensible, or if consumers are expected to ignore unknown properties. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 components: schemas: UserSignedUp: type: object properties: user_id: type: string additionalProperties: false ``` **Bad**. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 components: schemas: UserSignedUp: type: object properties: user_id: type: string ``` ## Automatic fixes `--fix` sets `additionalProperties: false` on every reported schema, replacing any other value of `additionalProperties`. --- # schema-property-naming Source: https://apigenie.pl/docs/linter/asyncapi/rules/schema-property-naming A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule ensures that the names of schema properties adhere to a predefined naming convention. ## Rule details Property names are typed by every consumer, and one convention lets a consumer who has seen one name spell the next; it also maps messages to the data structures of one language without renaming. The `schema-property-naming` rule checks the keys of the `properties` map of every schema of an AsyncAPI document. For every property whose name is not in the expected convention, it reports `Schema property '<name>' is not in the '<convention>' convention`. The recognised naming conventions are: - `CONST_CASE` (also `UPPER_CASE` and `SCREAMING_SNAKE_CASE`) - THIS_IS_CONST_CASE - `camelCase` - thisIsCamelCase, also with acronyms (userID) - `camelCaseStrict` - thisIsCamelCase, but no two capitals in a row (userId, not userID) - `kebab-case` - this-is-kebab-case - `PascalCase` - ThisIsPascalCase, also with acronyms (HTTPServer) - `PascalCaseStrict` - ThisIsPascalCase, but no two capitals in a row (HttpServer, not HTTPServer) - `Header-Case` - This-Is-Header-Case - `snake_case` - this_is_snake_case The default convention is `snake_case`. Turn the rule off when the API follows no naming convention for schema properties. ## Configuration The configuration block is a naming convention name (see the "Rule details" section for a list of recognized names). ```yaml version: "1.0" commands: lint: asyncapi: rules: schema-property-naming: [error, camelCase] ``` ## Examples **Good**. With the default configuration. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 components: schemas: UserSignedUp: type: object properties: user_id: type: string display_name: type: string ``` **Bad**. With the default configuration. ```yaml asyncapi: 3.0.0 info: title: User Events version: 1.0.0 components: schemas: UserSignedUp: type: object properties: userId: type: string DisplayName: type: string ``` --- # server-hosts Source: https://apigenie.pl/docs/linter/asyncapi/rules/server-hosts A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that the servers of an AsyncAPI document have well-formed hosts and protocols, and that they use secure protocols. ## Rule details In AsyncAPI 3.x, a server is described by separate `host`, `protocol` and `pathname` fields. A common mistake, especially when migrating from AsyncAPI 2.x (where servers had a single `url`), is to put a complete URL into `host`. The `server-hosts` rule checks every server in the root `servers` map and reports: - `Server host must not contain a scheme or a path` when `host` contains `://` or `/`. The scheme belongs to `protocol`, and the path to `pathname`. - `Server host is not lower case` when `host` contains upper-case letters. Host names are case-insensitive, and lower case is their canonical form. - `Server protocol is not lower case` when `protocol` contains upper-case letters. - `Server uses an insecure protocol (<protocol>)` when the protocol is `http` or `ws`, unless the host is `localhost`, `127.0.0.1` or `[::1]` (with or without a port). Use `https` or `wss` instead. Server variables (e.g. `{environment}` in `{environment}.your-company.com`) are not required to be lower case. ## Configuration The configuration block is an object with a single optional boolean property, `upgradeInsecure`. When it is `true`, the automatic fix also replaces insecure protocols with their secure variants (see "Automatic fixes"). The default value is `false`. **Configuration example**. ```yaml version: "1.0" commands: lint: asyncapi: rules: server-hosts: - warning - upgradeInsecure: true ``` ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 servers: production: host: broker.your-company.com:9092 protocol: kafka staging: host: "{environment}.your-company.com" protocol: wss pathname: /events variables: environment: default: staging local: host: localhost:8080 protocol: ws ``` **Bad**. The first server has an upper-case host and protocol, the second one puts a complete URL into `host`, and the third one uses an insecure protocol. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 servers: production: host: Broker.Your-Company.com:9092 protocol: Kafka staging: host: wss://staging.your-company.com/events protocol: wss public: host: events.your-company.com protocol: ws ``` ## Automatic fixes `--fix` converts hosts and protocols to lower case, leaving server variables untouched. Hosts that contain a scheme or a path are not changed, as the rule cannot tell how to split them. If `upgradeInsecure` is `true`, the fix also replaces `http` with `https`, and `ws` with `wss`, for all servers other than `localhost`, `127.0.0.1` and `[::1]`. Make sure that the servers actually support the secure protocol before enabling this option. --- # servers-defined Source: https://apigenie.pl/docs/linter/asyncapi/rules/servers-defined A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether at least one server is defined in an AsyncAPI document. ## Rule details Servers tell consumers where the application's channels are available: which broker to connect to, and with which protocol. Without them, the document describes messages but not how to reach them. The `servers-defined` rule reports `No servers defined` when the root `servers` map is missing or empty. Servers defined only under `components/servers` do not count. Turn the rule off for documents that describe messages shared by several applications, and whose servers are defined elsewhere. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 servers: production: host: broker.your-company.com:9092 protocol: kafka ``` **Bad**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted ``` --- # spell-check Source: https://apigenie.pl/docs/linter/asyncapi/rules/spell-check A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Strict at warning, All at warning. This rule checks the spelling of the texts written for humans: titles, summaries and descriptions. ## Rule details The rule reports every misspelled word, with up to three suggested corrections, for example `Misspelled word 'Recieve' in summary (did you mean 'Receive', 'Relieve', 'Reverie'?)`. The issue points at the object whose text contains the word. The rule checks: - the title and description of the info object, - the title, summary and description of servers, channels, operations, operation traits, messages and message traits, - the summary and description of message examples, - the title and description of schemas, - the description of server variables, parameters, operation reply addresses, correlation IDs, tags, external documentation and security schemes. Descriptions are CommonMark: the rule checks their prose, and skips code spans, code blocks, raw HTML and link destinations. Titles and summaries are plain text, in which `backticked` spans are skipped, too. The rule also skips the tokens which are not plain words: - URLs, e-mail addresses, paths, and file and domain names (`asyncapi.yaml`, `example.com`), - identifiers: `snake_case`, `camelCase` and names with inner capitals (`AsyncAPI`, `PetStore`), - acronyms, also in the plural (`MQTT`, `APIs`, `ID's`), - tokens with digits (`v2`, `401`) and single letters. The spell checker is a C++ port of [Hunspell](https://hunspell.github.io). By default it uses the built-in English (US) dictionary from [SCOWL](http://wordlist.aspell.net) (as shipped with LibreOffice), extended with words common in API descriptions, such as `webhook`, `endpoint`, `namespace`, `nullable` and `json`. Any Hunspell dictionary can be used instead. The rule is part of the `strict` and `all` rulesets. Turn the rule off if your documentation is written in a language you have no dictionary for. To silence it for a single object and its children, add `x-apigenie-lint-disable: [spell-check]` to the object. ## Configuration This rule accepts an object with the following options: - `words`: extra words to accept, for example product names. A word is accepted as given, capitalized and in capitals: `petstore` accepts `petstore`, `Petstore` and `PETSTORE`. - `dictionary` and `affix`: paths of a Hunspell dictionary (`.dic`) and its affix file (`.aff`) to use instead of the built-in dictionary. They go together. Dictionaries in UTF-8, ISO-8859-1, ISO-8859-2 and ISO-8859-15 are supported. - `suggestions`: how many corrections to suggest for a word, from 0 to 10 (default 3). Suggestions are the costly part of the rule; on a very large document with many unknown words, `0` makes it about ten times faster. **Configuration example** ```yaml version: "1.0" commands: lint: asyncapi: rules: spell-check: - warning - words: [petstore] dictionary: path/to/en_GB.dic affix: path/to/en_GB.aff ``` ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted operations: onPetAdopted: action: receive channel: $ref: "#/channels/petAdopted" summary: Receive adoption events description: Updates the shelter inventory when a pet is adopted. ``` **Bad**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted operations: onPetAdopted: action: receive channel: $ref: "#/channels/petAdopted" summary: Recieve adoption events description: Updates the shelter inventroy when a pet is adopted. ``` --- # standard-media-types Source: https://apigenie.pl/docs/linter/asyncapi/rules/standard-media-types A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether messages use only standard media types. ## Rule details Using non-standard media types can lead to interoperability issues: consumers and tools may not know how to decode the messages. The `standard-media-types` rule checks the following fields of an AsyncAPI document: - the root `defaultContentType`, - the `contentType` of every message, - the `contentType` of every message trait. For every value that is not a recognized media type, the rule reports `Non-standard media type is used (<value>)`. Media type parameters (such as `; charset=utf-8`) are allowed and ignored. A media type is recognized when it has the `type/subtype` form and its subtype is one of the well-known subtypes, such as `json`, `xml`, `plain`, `octet-stream`, `problem+json`, `vnd.api+json` or `x-www-form-urlencoded`. The CloudEvents media types (`application/cloudevents+json`, `application/cloudevents-batch+json` and their other formats) are recognized. Note that some media types commonly used with message brokers, for example `application/vnd.apache.avro+json` or `application/x-protobuf`, are not currently recognized. Turn the rule off if your messages use vendor-specific media types, or binary serialization formats that the rule does not recognize. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 defaultContentType: application/json channels: petAdopted: address: pets.adopted messages: petAdopted: contentType: application/json; charset=utf-8 payload: type: object ``` **Bad**. `json` is not a media type, and `application/pet` uses a subtype that is not registered. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 defaultContentType: json channels: petAdopted: address: pets.adopted messages: petAdopted: contentType: application/pet payload: type: object ``` --- # tag-description-defined Source: https://apigenie.pl/docs/linter/asyncapi/rules/tag-description-defined A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at warning. This rule checks whether every tag of an AsyncAPI document has a meaningful description. ## Rule details Documentation generators usually render tags as section headers, and their descriptions as the introduction of each section. A tag without a description leaves readers guessing what the grouped operations have in common. The `tag-description-defined` rule checks every Tag object of the document, wherever it is defined: in `info.tags`, in the tags of servers, channels, operations, operation traits, messages and message traits, and in `components/tags`. It reports `Tag '<name>' has no meaningful description defined` for every tag whose description: - is missing, empty or blank, - is shorter than the configured minimal length, - is a placeholder: `TODO`, `FIXME` or `TBD` (case-insensitive). Turn the rule off if the tag names are self-explanatory. ## Configuration The configuration block is a positive integer: the minimal length of a description, in characters. The default value is `10`. **Configuration example**. ```yaml version: "1.0" commands: lint: asyncapi: rules: tag-description-defined: [warning, 20] ``` ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 tags: - name: adoption description: Events related to adopting and returning pets. ``` **Bad**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 tags: - name: adoption - name: inventory description: TBD ``` --- # tags-sorted Source: https://apigenie.pl/docs/linter/asyncapi/rules/tags-sorted A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. Fixed by `--fix`. In the rulesets: Strict at error, All at error. This rule checks whether the tags listed in `info.tags` are sorted by their names. ## Rule details A sorted list of tags is easier to scan, and makes it obvious where a new tag should be added. The `tags-sorted` rule checks the `info.tags` list of an AsyncAPI document, and reports `Tags are not sorted: <name>` for every tag whose name sorts before the name of the preceding tag. Tags of operations, messages and other objects are not checked. Names are compared character by character (by their byte values), so the comparison is case-sensitive: all upper-case letters sort before lower-case ones. Turn the rule off if the order of tags is meaningful, for example if documentation generators should render sections in a specific order. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 tags: - name: adoption - name: inventory - name: medical ``` **Bad**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 tags: - name: inventory - name: adoption - name: medical ``` ## Automatic fixes `--fix` sorts the `info.tags` list by tag names, keeping the content of every tag unchanged. --- # tags-unique Source: https://apigenie.pl/docs/linter/asyncapi/rules/tags-unique A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the names of the tags listed in `info.tags` are unique. ## Rule details Duplicate tags are confusing: documentation generators may render the same section twice, or merge the tags in an unpredictable way. The `tags-unique` rule checks the `info.tags` list of an AsyncAPI document, and reports `Tag name is not unique (<name>)` for every tag whose name repeats the name of another tag in the list. Names are compared case-insensitively, so `Pets` and `pets` are duplicates. Tags of operations, messages and other objects are not checked. ## Examples **Good**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 tags: - name: adoption description: Events related to adopting and returning pets. - name: inventory description: Events related to the shelter inventory. ``` **Bad**. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 tags: - name: adoption description: Events related to adopting and returning pets. - name: Adoption ``` ## Automatic fixes `--fix` removes redundant duplicates: - a duplicate that contains only a `name` is removed; if the earlier tag contains only a `name` and the later one has more content, the earlier tag is removed instead, - a duplicate whose content (apart from the `name`) is identical to the earlier tag is removed. Duplicates that differ in their descriptions or other properties are reported but not fixed, as the rule cannot tell which one is correct. In the "Bad" example above, the second tag is removed. --- # unused-shared-component Source: https://apigenie.pl/docs/linter/asyncapi/rules/unused-shared-component A rule of the AsyncAPI linter, which reads AsyncAPI 3 documents; the reader rejects AsyncAPI 2 documents. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether every shared component of an AsyncAPI document is actually used. ## Rule details Components that are never referenced make the document longer and harder to maintain, and suggest that something is missing (for example, a message that was defined but never attached to a channel). The `unused-shared-component` rule checks every entry of every component category: `schemas`, `servers`, `channels`, `operations`, `messages`, `securitySchemes`, `serverVariables`, `parameters`, `correlationIds`, `replies`, `replyAddresses`, `externalDocs`, `tags`, `operationTraits`, `messageTraits`, `serverBindings`, `channelBindings`, `operationBindings` and `messageBindings`. It reports `Unused shared component` for every component that is not reachable from the rest of the document. A component is reachable when a local `$ref` of the form `#/components/<category>/<name>` (possibly pointing deeper into the component, e.g. `#/components/schemas/Pet/properties/name`) appears anywhere outside `components`, or inside another reachable component. References are followed transitively, so a schema used only by an unused message is unused as well. References nested in untyped values, such as bindings or payloads in other schema formats, count too. A component that has this rule disabled (see below) is always considered used, and so is everything it references. Turn the rule off for documents that serve as libraries of shared components, referenced from other documents. ## Examples **Good**. The message is used by the channel, and the schema by the message. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted messages: petAdopted: $ref: "#/components/messages/PetAdopted" components: messages: PetAdopted: payload: $ref: "#/components/schemas/Pet" schemas: Pet: type: object ``` **Bad**. Nothing references the `PetReturned` message, so both the message and the `Shelter` schema it uses are unused. ```yaml asyncapi: 3.0.0 info: title: Pet Events version: 1.0.0 channels: petAdopted: address: pets.adopted messages: petAdopted: $ref: "#/components/messages/PetAdopted" components: messages: PetAdopted: payload: $ref: "#/components/schemas/Pet" PetReturned: payload: $ref: "#/components/schemas/Shelter" schemas: Pet: type: object Shelter: type: object ``` To keep a component that is meant to be referenced from other documents, disable the rule on it: ```yaml components: schemas: Shelter: type: object x-lint-disable: [unused-shared-component] ``` ## Automatic fixes `--fix` removes all unused components. When every entry of a component category is unused, the whole category map is removed, so that no empty map is left behind. --- # audience-defined Source: https://apigenie.pl/docs/linter/swagger/rules/audience-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks whether the intended audience of an API is declared in the `x-audience` extension of the info object of a Swagger 2.0 document. ## Rule details Knowing who an API is built for helps to decide how strict its review should be, how carefully breaking changes must be handled, and where the API can be published. Swagger 2.0 does not provide a field for this information. The `audience-defined` rule fills this gap. It requires the `x-audience` extension to be present in the info object, and its value to be one of the following strings: - `internal-team` - the API is used only by the team that owns it, - `internal-company` - the API is used by other teams in the same company, - `partner` - the API is shared with selected partners, - `public` - the API is publicly available. The rule reports `API audience (x-audience) is missing` when the extension is absent, and `API audience (x-audience) has invalid value (...)` when its value is not one of the strings listed above. For values that are not strings at all the parentheses are empty. The OpenAPI and AsyncAPI linters have rules of the same name, [audience-defined](/docs/linter/openapi/rules/audience-defined) and [audience-defined](/docs/linter/asyncapi/rules/audience-defined). Turn the rule off if your organization does not classify its APIs by their audience. ## Examples **Good**. The audience of the API is clearly stated. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 x-audience: internal-company paths: {} ``` **Bad**. The audience is not declared. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: {} ``` **Bad**. The audience has a value that is not recognized. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 x-audience: everyone paths: {} ``` --- # contact-defined Source: https://apigenie.pl/docs/linter/swagger/rules/contact-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks whether complete contact information is present in a Swagger 2.0 document. ## Rule details The `contact-defined` rule ensures that the `info.contact` object is defined and that its `name`, `email` and `url` properties are all present and not empty. Contact information tells consumers of the API whom to ask for help, report problems to, or notify about their use of the API. The rule reports: - `Contact object is missing` when there is no `info.contact` object, - `Contact name is missing or empty` when `name` is missing or empty, - `Contact email is missing` when `email` is missing or empty, - `Contact URL is missing` when `url` is missing or empty. The OpenAPI and AsyncAPI linters have rules of the same name, [contact-defined](/docs/linter/openapi/rules/contact-defined) and [contact-defined](/docs/linter/asyncapi/rules/contact-defined). Turn the rule off for APIs used only by the team that owns them. ## Examples **Good**. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 contact: name: Pet Platform Team email: pets@your-company.com url: https://your-company.com/teams/pets paths: {} ``` **Bad**. The contact object is present, but it is not possible to reach the team by email. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 contact: name: Pet Platform Team url: https://your-company.com/teams/pets paths: {} ``` --- # host-defined Source: https://apigenie.pl/docs/linter/swagger/rules/host-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether a Swagger 2.0 document declares the host that serves the API. ## Rule details Swagger 2.0 describes where an API is available with three root properties: `host` (the name or IP address, optionally with a port), `basePath` and `schemes`. When `host` is missing, tools fall back to the host that served the document, which is rarely what consumers want: generated clients and API consoles cannot reach the API without extra configuration. The `host-defined` rule reports `No host defined` when the root `host` property is missing or empty. A `basePath` or `schemes` alone do not satisfy the rule. This is the Swagger 2.0 counterpart of the OpenAPI [servers-defined](/docs/linter/openapi/rules/servers-defined) rule. Turn the rule off for documents that are served by the API itself and are meant to be used against the host they are loaded from. ## Examples **Good**. The host of the API is declared. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 host: api.example.com basePath: /v1 schemes: [https] paths: {} ``` **Bad**. Only the base path is declared. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 basePath: /v1 paths: {} ``` --- # id-defined Source: https://apigenie.pl/docs/linter/swagger/rules/id-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Strict at error, All at error. This rule checks whether the info object of a Swagger 2.0 document has an identifier extension (`x-id` by default), and whether its value has the expected format (a UUID by default). ## Rule details A stable identifier makes it possible to track an API across renames, new versions and moved files. Swagger 2.0 does not provide an identifier field for an API, so the rule requires an `info` extension to hold it. The rule reports: - `API identifier (x-id) is missing` when the extension is absent, - `API identifier (x-id) has invalid format` when its value is not a string, or does not fully match the expected pattern. The name in parentheses is the configured attribute. The OpenAPI and AsyncAPI linters have rules of the same name, [id-defined](/docs/linter/openapi/rules/id-defined) and [id-defined](/docs/linter/asyncapi/rules/id-defined). ## Configuration The rule accepts an object with two options. When options are given, both are required: - `attribute`: the name of the extension that holds the identifier. It must not be empty and must start with `x-`. Default: `x-id`. - `pattern`: the expected format of the identifier. `uuid` (the default) accepts UUIDs in the `8-4-4-4-12` hexadecimal form, any other value is an ECMAScript regular expression that must match the whole identifier. **Configuration example**. The rule looks for the `info.x-ident` extension, whose value must be one or more lower case letters. ```yaml version: "1.0" commands: lint: swagger: rules: id-defined: - error - attribute: x-ident pattern: "[a-z]+" ``` ## Examples **Good**. The API can be tracked whatever happens to its title or file name. ```yaml swagger: '2.0' info: title: Payments version: 1.2.8 x-id: 123e4567-e89b-12d3-a456-426614174000 paths: {} ``` **Bad**. The API has no identifier. ```yaml swagger: '2.0' info: title: Payments version: 1.2.4 paths: {} ``` **Bad**. The identifier is not a UUID. ```yaml swagger: '2.0' info: title: Payments version: 1.2.8 x-id: 237849128738 paths: {} ``` ## Automatic fixes The rule is auto-fixable only while `pattern` is `uuid`. Then `--fix` sets the configured attribute of the info object to a newly generated UUID v4, both when the attribute is missing and when its value is invalid. With a custom pattern the issues are reported but not fixed. --- # info-defined Source: https://apigenie.pl/docs/linter/swagger/rules/info-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether the info object of a Swagger 2.0 document provides a description and a version. ## Rule details The info object is the first thing readers of an API see. Besides the mandatory title, it should explain what the application does and which version of the API is being described. The `info-defined` rule reports: - `Info description is missing or empty` when `info.description` is missing or empty, - `Info version is empty` when `info.version` is an empty string. The title is required by the Swagger specification itself and is not checked by this rule. The OpenAPI and AsyncAPI linters have rules of the same name, [info-defined](/docs/linter/openapi/rules/info-defined) and [info-defined](/docs/linter/asyncapi/rules/info-defined). ## Examples **Good**. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 description: Manages the pets of a shelter and their adoptions. paths: {} ``` **Bad**. The document does not explain what the API does, and its version is empty. ```yaml swagger: '2.0' info: title: Pet Store version: '' paths: {} ``` --- # license-defined Source: https://apigenie.pl/docs/linter/swagger/rules/license-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks whether the licensing information is present in a Swagger 2.0 document. ## Rule details The `license-defined` rule ensures that the `info.license` object is defined, and that both its `name` and its `url` are provided. The license specifies the terms under which the API can be used, and helps consumers of the API to understand any restrictions that apply. The rule reports: - `License object is missing` when there is no `info.license` object, - `License name is empty` when `name` is empty, - `License URL is missing or empty` when `url` is missing or empty. Swagger 2.0 license objects have no SPDX `identifier` field (it was added in OpenAPI 3.1), so the rule always requires a URL. The OpenAPI and AsyncAPI linters have rules of the same name, [license-defined](/docs/linter/openapi/rules/license-defined) and [license-defined](/docs/linter/asyncapi/rules/license-defined). Turn the rule off for APIs used only by the team that owns them. ## Examples **Good**. The document links to its license, which makes it easier to understand how the API can be used. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 license: name: Apache 2.0 url: https://www.apache.org/licenses/LICENSE-2.0 paths: {} ``` **Bad**. The license has a name, but no link to its terms. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 license: name: Proprietary paths: {} ``` --- # media-types-defined Source: https://apigenie.pl/docs/linter/swagger/rules/media-types-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the operations of a Swagger 2.0 document that send or receive a body declare its media types. ## Rule details Swagger 2.0 declares the media types of request bodies with `consumes`, and those of response bodies with `produces`. Both can be set on an operation or, as defaults for all operations, on the root object. Without them, clients and code generators have to guess the format of the payloads. The `media-types-defined` rule reports: - `Operation accepts a request body but defines no consumes` when an operation has a `body` or `formData` parameter, either its own or one inherited from its path item (references to `#/parameters` are resolved), and its effective `consumes` list is empty, - `Operation returns a response body but defines no produces` when any response of an operation (references to `#/responses` are resolved) has a `schema`, and its effective `produces` list is empty. An operation's own `consumes` or `produces` replaces the root one, as in the specification, so an operation that sets `produces: []` has no response media types even when the root object declares some. OpenAPI 3.x documents declare media types as the keys of `content` maps, so the OpenAPI linter has no counterpart of this rule. Turn the rule off if all consumers of your API assume a single media type, such as `application/json`, without it being declared. ## Examples **Good**. The root object declares the default media types. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 consumes: [application/json] produces: [application/json] paths: /pets: post: parameters: - name: pet in: body required: true schema: $ref: '#/definitions/Pet' responses: '201': description: The created pet. schema: $ref: '#/definitions/Pet' definitions: Pet: type: object properties: name: type: string ``` **Bad**. The operation sends and receives a body, but no media types are declared. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: post: parameters: - name: pet in: body required: true schema: $ref: '#/definitions/Pet' responses: '201': description: The created pet. schema: $ref: '#/definitions/Pet' definitions: Pet: type: object properties: name: type: string ``` --- # no-content-response-defined Source: https://apigenie.pl/docs/linter/swagger/rules/no-content-response-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether `204 No Content` responses of a Swagger 2.0 document declare a body. ## Rule details By definition a `204` response carries no content. In Swagger 2.0 the body of a response is described by its `schema` property, so a `204` response with a `schema` contradicts its status code and misleads consumers and code generators. The `no-content-response-defined` rule reports `204 response may not have a body defined` for every `204` response of an operation that has a `schema`. Response references (`$ref`) are not followed. Headers are allowed. The OpenAPI linter has a rule of the same name, [no-content-response-defined](/docs/linter/openapi/rules/no-content-response-defined), for OpenAPI 3.x documents. ## Examples **Good**. The `204` response has no schema. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets/{petId}: delete: parameters: - name: petId in: path required: true type: string responses: '204': description: The pet was deleted. ``` **Bad**. The `204` response declares a schema. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets/{petId}: delete: parameters: - name: petId in: path required: true type: string responses: '204': description: The pet was deleted. schema: type: object ``` ## Automatic fixes `--fix` removes the `schema` property from `204` responses. The rest of the response, such as its description and headers, is kept. --- # operation-description-defined Source: https://apigenie.pl/docs/linter/swagger/rules/operation-description-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether every operation of a Swagger 2.0 document has a meaningful description. ## Rule details A description tells consumers what an operation does, when to call it and what side effects it has. Generated documentation and clients show it next to the operation. The `operation-description-defined` rule reports `Operation has no meaningful description` for every operation whose `description` is missing or shorter than the configured minimal length (10 characters by default). The `summary` property does not count as a description. The OpenAPI linter has a rule of the same name, [operation-description-defined](/docs/linter/openapi/rules/operation-description-defined), for OpenAPI 3.x documents. Turn the rule off when operations are documented outside of the Swagger document. ## Configuration A single positive integer: the minimal number of characters of a description. The default is 10. ```yaml commands: lint: swagger: rules: operation-description-defined: [warning, 20] ``` ## Examples **Good**. The operation has a meaningful description. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: description: Lists every pet of the store, ordered by name. responses: '200': description: A list of pets. ``` **Bad**. The first operation has no description, the second one has a description that is too short. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: summary: List pets responses: '200': description: A list of pets. post: description: Adds responses: '201': description: The pet was added. ``` --- # operation-id-defined Source: https://apigenie.pl/docs/linter/swagger/rules/operation-id-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether every operation of a Swagger 2.0 document has an operation ID. ## Rule details The `operationId` property identifies an operation. Code generators use it to name the methods of generated clients and servers, and documentation tools use it to build links to operations. The `operation-id-defined` rule reports `Operation ID is not defined` for every operation without an `operationId`. Since 0.12.0, an `operationId` that is empty or only whitespace is not an issue of this rule but an error of reading the document. `apigenie lint` prints `Operation ID must not be blank` with the line and column of the `operationId` and stops with [exit status 2](/docs/reference/cli/lint#exit-status) before any rule runs. Turning the rule off does not change this, and `--fix` does not fill in the ID. The OpenAPI linter has a rule of the same name, [operation-id-defined](/docs/linter/openapi/rules/operation-id-defined), for OpenAPI 3.x documents. Turn the rule off when no tooling relies on operation IDs. ## Examples **Good**. The operation has an operation ID. ```yaml swagger: '2.0' info: title: Reservations version: 1.0.0 paths: /reservations/{reservationId}: delete: operationId: cancelReservation parameters: - name: reservationId in: path required: true type: string responses: '204': description: The reservation was cancelled. ``` **Bad**. The operation has no operation ID. ```yaml swagger: '2.0' info: title: Reservations version: 1.0.0 paths: /reservations/{reservationId}: delete: parameters: - name: reservationId in: path required: true type: string responses: '204': description: The reservation was cancelled. ``` ## Automatic fixes `--fix` sets `operationId` to an ID generated from the HTTP method and the path. Each literal path segment is appended in PascalCase, and each path parameter is appended as `By` followed by its name in PascalCase: `GET /users/{userId}` becomes `getUsersByUserId`, and `GET /` becomes `getRoot`. IDs already used in the document are reserved, and a generated ID that collides with a reserved one gets a numeric suffix starting at 2 (`getUsers2`). --- # operation-id-unique Source: https://apigenie.pl/docs/linter/swagger/rules/operation-id-unique A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether the operation IDs of a Swagger 2.0 document are unique. ## Rule details The Swagger 2.0 specification requires the `operationId` to be unique among all operations of an API. Duplicate IDs break code generators, which name methods after them, and make links to operations ambiguous. The `operation-id-unique` rule reports `Operation ID is not unique <id>` for every operation that repeats an ID already used by an earlier operation, in document order. The first occurrence is not reported. Operations without an `operationId` are ignored; the `operation-id-defined` rule reports them. Since 0.12.0, an empty or whitespace-only `operationId` is an error of reading the document, reported before any rule runs; see [operation-id-defined](/docs/linter/swagger/rules/operation-id-defined). The OpenAPI linter has a rule of the same name, [operation-id-unique](/docs/linter/openapi/rules/operation-id-unique), for OpenAPI 3.x documents. Turn the rule off only when no tooling relies on operation IDs; duplicate IDs violate the Swagger 2.0 specification. ## Examples **Good**. Each operation has its own ID. ```yaml swagger: '2.0' info: title: Users version: 1.0.0 paths: /users: get: operationId: getUsers responses: '200': description: A list of users. /users/{id}: get: operationId: getUserById parameters: - name: id in: path required: true type: string responses: '200': description: A single user. ``` **Bad**. Two operations share the same ID. ```yaml swagger: '2.0' info: title: Downloads version: 1.0.0 paths: /downloads/{id}: parameters: - name: id in: path required: true type: string patch: operationId: cancelDownload responses: '200': description: The download was updated. delete: operationId: cancelDownload responses: '204': description: The download was cancelled. ``` ## Automatic fixes `--fix` keeps the first occurrence of an ID and replaces every later duplicate with an ID generated the same way as by the `operation-id-defined` rule, from the HTTP method and the path (for example `getPetsById` for `GET /pets/{id}`). IDs already used in the document are reserved, and collisions get a numeric suffix starting at 2. --- # operation-rate-limiting-defined Source: https://apigenie.pl/docs/linter/swagger/rules/operation-rate-limiting-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks whether the responses of Swagger 2.0 operations declare rate limiting headers. ## Rule details When an API limits the rate of requests, declaring the rate limiting headers lets consumers pace their requests and recover from throttling. The `operation-rate-limiting-defined` rule checks the responses of every operation: - a response whose status code starts with `2` or `4` must declare a `RateLimit-Limit`, `X-RateLimit-Limit` or `X-Rate-Limit-Limit` header, otherwise the rule reports `Missing rate limiting header`; - a `429` or `503` response must declare a `Retry-After` header, otherwise the rule reports `Missing Retry-After header`. A `429` response is therefore checked for both headers. Header names are compared case-sensitively. When a response is a `$ref` to a shared response under the root `responses`, the headers of the referenced response are used. The `default` response and other status codes are not checked. The OpenAPI linter has a rule of the same name, [operation-rate-limiting-defined](/docs/linter/openapi/rules/operation-rate-limiting-defined), for OpenAPI 3.x documents. Turn the rule off if your API does not impose any rate limits. ## Examples **Good**. The success response declares a rate limit header, and the shared `429` response declares both `Retry-After` and a rate limit header. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: responses: '200': description: A list of pets. headers: X-RateLimit-Limit: description: The number of requests allowed per hour. type: integer '429': $ref: '#/responses/TooManyRequests' responses: TooManyRequests: description: Too many requests. headers: Retry-After: description: The number of seconds to wait before retrying. type: integer RateLimit-Limit: description: The number of requests allowed per hour. type: integer ``` **Bad**. The `200` response has no rate limit header and the `503` response has no `Retry-After` header. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: responses: '200': description: A list of pets. '503': description: The service is unavailable. ``` --- # operation-security-defined Source: https://apigenie.pl/docs/linter/swagger/rules/operation-security-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks whether every operation of a Swagger 2.0 document is covered by a security requirement. ## Rule details Swagger 2.0 declares security schemes under `securityDefinitions` and applies them with `security` requirements, either at the root of the document (for every operation) or on individual operations. An operation without any requirement is documented as publicly accessible, which is often an oversight. When the root `security` list is not empty, every operation is covered and the rule reports nothing. Otherwise the `operation-security-defined` rule reports `Security requirement is not defined` for every operation whose own `security` list is missing or empty. An explicit `security: []` on an operation is reported as well. The OpenAPI linter has a rule of the same name, [operation-security-defined](/docs/linter/openapi/rules/operation-security-defined), for OpenAPI 3.x documents. Turn the rule off for public APIs, or disable it on the individual operations that are intentionally public. ## Examples **Good**. The root security requirement applies to every operation. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 securityDefinitions: apiKey: type: apiKey name: X-API-Key in: header security: - apiKey: [] paths: /pets: get: responses: '200': description: A list of pets. ``` **Good**. Each operation declares its own security requirement. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 securityDefinitions: basic: type: basic paths: /pets: get: security: - basic: [] responses: '200': description: A list of pets. ``` **Bad**. There is no root security requirement and the `post` operation has none of its own. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 securityDefinitions: basic: type: basic paths: /pets: get: security: - basic: [] responses: '200': description: A list of pets. post: responses: '201': description: The pet was added. ``` --- # operation-success-response Source: https://apigenie.pl/docs/linter/swagger/rules/operation-success-response A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether every operation of a Swagger 2.0 document declares at least one success response. ## Rule details Consumers and code generators rely on the success response of an operation to know what a successful call returns. An operation that only documents errors leaves that unspecified. The `operation-success-response` rule reports `Operation must have at least one success response` for every operation whose responses contain no status code starting with `2` or `3` and no `default` response. The OpenAPI linter has a rule of the same name, [operation-success-response](/docs/linter/openapi/rules/operation-success-response), for OpenAPI 3.x documents. ## Examples **Good**. The operation declares a `200` response. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: responses: '200': description: A list of pets. '500': description: Internal error. ``` **Bad**. The operation only declares error responses. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: responses: '400': description: Invalid request. '500': description: Internal error. ``` --- # operation-tags-defined Source: https://apigenie.pl/docs/linter/swagger/rules/operation-tags-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks whether every operation of a Swagger 2.0 document has at least one tag. ## Rule details Tags group operations. Documentation tools use them to build sections, and code generators use them to split generated clients into classes or modules. Untagged operations usually end up in a catch-all group. The `operation-tags-defined` rule reports `Operation has no tags defined` for every operation whose `tags` list is missing or empty. The OpenAPI linter has a rule of the same name, [operation-tags-defined](/docs/linter/openapi/rules/operation-tags-defined), for OpenAPI 3.x documents. Turn the rule off for small APIs where grouping operations brings no value. ## Examples **Good**. The operation is tagged. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 tags: - name: pets description: Operations on pets. paths: /pets: get: tags: [pets] responses: '200': description: A list of pets. ``` **Bad**. The first operation has no tags, the second has an empty list. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: responses: '200': description: A list of pets. post: tags: [] responses: '201': description: The pet was added. ``` --- # parameter-description-defined Source: https://apigenie.pl/docs/linter/swagger/rules/parameter-description-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks whether every parameter of a Swagger 2.0 document has a meaningful description. ## Rule details A parameter's name rarely tells everything about its meaning, accepted values and effect. A description fills that gap in generated documentation and clients. The `parameter-description-defined` rule checks parameters of operations, of path items and the shared parameters under the root `parameters`, and reports `Parameter '<name>' has no meaningful description` when the `description`: - is missing or empty, - is shorter than the configured minimal length (10 characters by default), - consists of whitespace only, - is `TODO`, `FIXME` or `TBD` (case-insensitive). Parameter references (`$ref`) are skipped; the referenced shared parameter is checked where it is defined. The OpenAPI linter has a rule of the same name, [parameter-description-defined](/docs/linter/openapi/rules/parameter-description-defined), for OpenAPI 3.x documents. Turn the rule off when parameters are self-explanatory or documented outside of the Swagger document. ## Configuration A single positive integer: the minimal number of characters of a description. The default is 10. ```yaml commands: lint: swagger: rules: parameter-description-defined: [warning, 20] ``` ## Examples **Good**. Every parameter has a meaningful description. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: parameters: - $ref: '#/parameters/limit' responses: '200': description: A list of pets. parameters: limit: name: limit in: query type: integer description: The maximum number of pets to return. ``` **Bad**. The path parameter has no description and the query parameter has a description that is too short. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets/{id}: parameters: - name: id in: path required: true type: string get: parameters: - name: fields in: query type: string description: Fields responses: '200': description: A single pet. ``` --- # parameter-naming Source: https://apigenie.pl/docs/linter/swagger/rules/parameter-naming A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks whether parameter names of a Swagger 2.0 document follow a naming convention. ## Rule details Consistent parameter names make an API easier to learn and use. Different parameter locations usually follow different conventions: HTTP headers are traditionally written in `Header-Case`, while query parameters often use `kebab-case` or `snake_case`. The `parameter-naming` rule checks parameters of operations, of path items and the shared parameters under the root `parameters`, converts each name to the convention configured for its location (`path`, `query`, `header` or `formData`) and reports `Parameter should be named <converted name>` when the converted name differs from the actual one. Body parameters are skipped, since their names do not appear in requests. Parameter references (`$ref`) are skipped; the referenced shared parameter is checked where it is defined. Without options, query parameters must use `kebab-case`, header parameters `Header-Case` and path and form data parameters `snake_case`. The OpenAPI linter has a rule of the same name, [parameter-naming](/docs/linter/openapi/rules/parameter-naming), for OpenAPI 3.x documents. Turn the rule off when parameter names are dictated by an existing implementation that cannot be changed. ## Configuration Supported conventions are `camelCase`, `camelCaseStrict`, `CONST_CASE` (also `UPPER_CASE` and `SCREAMING_SNAKE_CASE`), `PascalCase`, `PascalCaseStrict`, `snake_case`, `kebab-case` and `Header-Case` (the strict forms reject two capitals in a row, e.g. `userID`). The options are either a string or an object: - a string sets the convention for parameters in every location, including query and header parameters; - an object must have a `default` property with the convention for every location, and may override it for individual locations with the `path`, `query`, `header` and `formData` properties. Locations that are not listed use the `default` convention. ```yaml commands: lint: swagger: rules: parameter-naming: - warning - default: snake_case query: camelCase header: Header-Case ``` ## Examples **Good**. Parameters follow the default conventions. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets/{pet_id}: get: parameters: - name: pet_id in: path required: true type: string - name: page-size in: query type: integer - name: X-Request-Id in: header type: string responses: '200': description: A single pet. ``` **Bad**. With the default conventions, `pageSize` should be named `page-size`, `x-request-id` should be named `X-Request-Id` and `firstName` should be named `first_name`. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: post: consumes: [application/x-www-form-urlencoded] parameters: - name: pageSize in: query type: integer - name: x-request-id in: header type: string - name: firstName in: formData type: string responses: '201': description: The pet was added. ``` --- # parameters-unique Source: https://apigenie.pl/docs/linter/swagger/rules/parameters-unique A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether the parameter lists of a Swagger 2.0 document contain duplicates. ## Rule details The Swagger 2.0 specification requires a parameter list not to contain duplicate parameters, where a parameter is identified by the combination of its `name` and its location (`in`). With duplicates it is unclear which definition applies. The `parameters-unique` rule checks the `parameters` of every path item and of every operation separately, and reports `Duplicate parameter name '<name>' in location '<location>'` for every parameter that repeats the name and location of an earlier parameter of the same list. Parameter references (`$ref`) are compared by the parameter they point to; unresolved references are ignored. A parameter with the same name in a different location (for example a query parameter and a header both named `id`) is not a duplicate. The OpenAPI linter has a rule of the same name, [parameters-unique](/docs/linter/openapi/rules/parameters-unique), for OpenAPI 3.x documents. duplicate parameters violate the Swagger 2.0 specification. ## Examples **Good**. The parameters differ by name or location. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: parameters: - name: id in: query type: string - name: id in: header type: string responses: '200': description: A list of pets. ``` **Bad**. The inline `limit` parameter duplicates the referenced one. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: parameters: - $ref: '#/parameters/limit' - name: limit in: query type: string responses: '200': description: A list of pets. parameters: limit: name: limit in: query type: integer ``` ## Automatic fixes `--fix` removes a duplicate parameter from its list when it is structurally identical to the first parameter with the same name and location (references are compared by their targets). Duplicates that differ from the first parameter are reported but not fixed, since the rule cannot tell which definition is the right one. --- # path-parameters-defined Source: https://apigenie.pl/docs/linter/swagger/rules/path-parameters-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether every parameter of a path template is declared as a path parameter. ## Rule details The Swagger 2.0 specification requires every template expression of a path (such as `{userId}` in `/users/{userId}`) to correspond to a parameter with `in: path`. Without it, tools do not know the type of the parameter and cannot build request URLs. The `path-parameters-defined` rule checks every operation and reports `One or more path parameters are missing` when a template expression of its path has no matching `in: path` parameter, either among the parameters of the path item or among the parameters of the operation. Parameter references (`$ref`) are resolved; a parameter with the right name in another location (for example `in: query`) does not count. Path parameters that do not appear in the template are not reported. The OpenAPI linter has a rule of the same name, [path-parameters-defined](/docs/linter/openapi/rules/path-parameters-defined), for OpenAPI 3.x documents. undeclared path parameters violate the Swagger 2.0 specification. ## Configuration The options are an object with an optional `defaultType` property, which sets the `type` of the parameters added by the automatic fix: `string` (default), `integer`, `number` or `boolean`. Set it to `null` to disable the automatic fix. ```yaml commands: lint: swagger: rules: path-parameters-defined: - error - defaultType: integer ``` ## Examples **Good**. The path parameter is declared on the path item. ```yaml swagger: '2.0' info: title: Users version: 1.0.0 paths: /users/{userId}: parameters: - name: userId in: path required: true type: string get: responses: '200': description: A single user. delete: responses: '204': description: The user was deleted. ``` **Bad**. The `get` operation declares `userId` as a query parameter and the `delete` operation does not declare it at all. ```yaml swagger: '2.0' info: title: Users version: 1.0.0 paths: /users/{userId}: get: parameters: - name: userId in: query type: string responses: '200': description: A single user. delete: responses: '204': description: The user was deleted. ``` ## Automatic fixes `--fix` appends the missing parameters, in the order they appear in the path template, to the `parameters` of the path item. Each added parameter has the form `{name: <name>, in: path, required: true, type: <defaultType>}`. No fix is offered when `defaultType` is `null`. --- # path-parameters-on-items Source: https://apigenie.pl/docs/linter/swagger/rules/path-parameters-on-items A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks whether path parameters are declared on path items rather than on individual operations. ## Rule details A path parameter belongs to the path, so every operation of a path item shares it. Declaring it once in the `parameters` of the path item avoids repeating the same definition in every operation and keeps the definitions consistent. The `path-parameters-on-items` rule reports `One or more path parameters are missing or not defined in path item` for every path item when a template expression of its path has no matching `in: path` parameter in the path item's own `parameters`. Parameters declared on operations do not count. Parameter references (`$ref`) are resolved. The OpenAPI linter has a rule of the same name, [path-parameters-on-items](/docs/linter/openapi/rules/path-parameters-on-items), for OpenAPI 3.x documents. Turn the rule off if your style guide prefers declaring path parameters on operations. ## Examples **Good**. The path parameter is declared on the path item. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets/{petId}: parameters: - $ref: '#/parameters/petId' get: responses: '200': description: A single pet. parameters: petId: name: petId in: path required: true type: string ``` **Bad**. The path parameter is declared on the operation. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets/{petId}: get: parameters: - name: petId in: path required: true type: string responses: '200': description: A single pet. ``` --- # paths-max-count Source: https://apigenie.pl/docs/linter/swagger/rules/paths-max-count A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks whether a Swagger 2.0 document defines more paths than a configured maximum. ## Rule details A large number of paths may indicate that an API covers too many concerns and could be split into smaller, more focused APIs. The `paths-max-count` rule counts the entries of the root `paths` object and reports `Too many paths found (<count>), maximum number is <maximum>` on the document root when the count exceeds the configured maximum (8 by default). Each path counts once, whatever the number of its operations. The OpenAPI linter has a rule of the same name, [paths-max-count](/docs/linter/openapi/rules/paths-max-count), for OpenAPI 3.x documents. Turn the rule off for APIs that are large by design. ## Configuration A single positive integer: the maximum number of paths. The default is 8. ```yaml commands: lint: swagger: rules: paths-max-count: [warning, 20] ``` ## Examples **Good**. With a maximum of 2, the document defines 2 paths. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: responses: '200': description: A list of pets. /owners: get: responses: '200': description: A list of owners. ``` **Bad**. With a maximum of 2, the document defines 3 paths. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: responses: '200': description: A list of pets. /owners: get: responses: '200': description: A list of owners. /visits: get: responses: '200': description: A list of visits. ``` --- # paths-max-depth Source: https://apigenie.pl/docs/linter/swagger/rules/paths-max-depth A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at error. This rule checks whether the paths of a Swagger 2.0 document are nested deeper than a configured maximum. ## Rule details Deeply nested paths are hard to read and remember, and often expose internal relationships between resources that consumers do not need to know about. The `paths-max-depth` rule counts the non-empty segments of each path, path template expressions included, and reports `Path URL is too much nested (<path>)` on the path item when the count exceeds the configured maximum (4 by default). For example, `/pets/{id}/toys` has 3 segments. The root `basePath` is not counted. The OpenAPI linter has a rule of the same name, [paths-max-depth](/docs/linter/openapi/rules/paths-max-depth), for OpenAPI 3.x documents. Turn the rule off when the resource hierarchy of your API is inherently deep. ## Configuration A single positive integer: the maximum number of path segments. The default is 4. ```yaml commands: lint: swagger: rules: paths-max-depth: [warning, 3] ``` ## Examples **Good**. With the default maximum of 4, the path has 3 segments. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets/{petId}/toys: get: parameters: - name: petId in: path required: true type: string responses: '200': description: The toys of a pet. ``` **Bad**. With the default maximum of 4, the path has 6 segments. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /owners/{ownerId}/pets/{petId}/toys/{toyId}: parameters: - name: ownerId in: path required: true type: string - name: petId in: path required: true type: string - name: toyId in: path required: true type: string get: responses: '200': description: A single toy. ``` --- # paths-sorted Source: https://apigenie.pl/docs/linter/swagger/rules/paths-sorted A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Strict at error, All at error. This rule checks whether the paths of a Swagger 2.0 document are sorted. ## Rule details Sorted paths make a large document easier to navigate and keep diffs small when paths are added. The `paths-sorted` rule walks the entries of the root `paths` object in the order they appear in the document and reports `Paths are not sorted: <path>` for every path that is not greater than the previous one. Paths are compared character by character (byte order), so `/Pets` sorts before `/pets` and `/pets` before `/pets/{id}`. The OpenAPI linter has a rule of the same name, [paths-sorted](/docs/linter/openapi/rules/paths-sorted), for OpenAPI 3.x documents. Turn the rule off when paths are intentionally grouped in another order, for example by resource or by workflow. ## Examples **Good**. The paths are sorted. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /owners: get: responses: '200': description: A list of owners. /pets: get: responses: '200': description: A list of pets. ``` **Bad**. `/owners` is listed after `/pets`. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: responses: '200': description: A list of pets. /owners: get: responses: '200': description: A list of owners. ``` ## Automatic fixes `--fix` reorders the entries of the `paths` object so that the paths are sorted in byte order. --- # paths-unique Source: https://apigenie.pl/docs/linter/swagger/rules/paths-unique A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks whether a Swagger 2.0 document defines paths that are equivalent to each other. ## Rule details Paths such as `/pets/{id}` and `/pets/{petId}` differ only by the names of their template expressions, so they match exactly the same requests. Tools cannot tell which path item a request belongs to. The `paths-unique` rule normalizes every path by replacing each template expression with `{}`, collapsing repeated slashes and removing a trailing slash, and reports `Duplicate path found` on every path item whose normalized path equals the normalized path of an earlier one. Paths are compared case-sensitively. The OpenAPI linter has a rule of the same name, [paths-unique](/docs/linter/openapi/rules/paths-unique), for OpenAPI 3.x documents. ## Examples **Good**. The paths match different requests. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets/{petId}: get: parameters: - name: petId in: path required: true type: string responses: '200': description: A single pet. /pets/{petId}/toys: get: parameters: - name: petId in: path required: true type: string responses: '200': description: The toys of a pet. ``` **Bad**. Both paths match the same requests. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets/{id}: get: parameters: - name: id in: path required: true type: string responses: '200': description: A single pet. /pets/{petId}/: delete: parameters: - name: petId in: path required: true type: string responses: '204': description: The pet was deleted. ``` --- # paths-well-formed Source: https://apigenie.pl/docs/linter/swagger/rules/paths-well-formed A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the paths of a Swagger 2.0 document are well-formed. ## Rule details Consistently formatted paths are easier to read and avoid surprises with servers that treat `/pets`, `/pets/` and `/Pets` as different resources. The `paths-well-formed` rule reports `Path is not well-formed <path>` on every path item whose path: - does not start with a slash, - contains empty segments (`//`), - ends with a slash (except the root path `/`), - contains upper-case ASCII letters outside template expressions. Template expressions such as `{petId}` are left as they are, so parameter names may use any case. The OpenAPI linter has a rule of the same name, [paths-well-formed](/docs/linter/openapi/rules/paths-well-formed), for OpenAPI 3.x documents. Turn the rule off when the paths are dictated by an existing implementation that cannot be changed. ## Examples **Good**. The paths are well-formed. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets/{petId}: get: parameters: - name: petId in: path required: true type: string responses: '200': description: A single pet. ``` **Bad**. The path has an upper-case letter, an empty segment and a trailing slash. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /Pets//{petId}/: get: parameters: - name: petId in: path required: true type: string responses: '200': description: A single pet. ``` ## Automatic fixes `--fix` renames each malformed path to its normalized form: a leading slash is added, empty segments and the trailing slash are removed, and letters outside template expressions are lower-cased. For example, `/Pets//{petId}/` becomes `/pets/{petId}`. --- # safe-markdown Source: https://apigenie.pl/docs/linter/swagger/rules/safe-markdown A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule ensures that the GFM descriptions of a Swagger 2.0 document do not contain unsafe constructs like `script` elements or `eval()` calls. ## Rule details Unsafe constructs embedded in descriptions can pose security risks when the documentation is rendered, for example by a documentation portal or an API console. The `safe-markdown` rule checks the `description` field of the info object, operations, parameters, responses (but not response references), headers, schemas, security definitions, tags and external documentation objects. It reports: - `Markdown contains <script> tag` when a description contains a `script` element (an opening tag followed by a closing tag), - `Markdown contains eval() function` when a description contains `eval` followed by a parenthesized argument list. Both checks are case-insensitive, and skip code spans and code blocks. The OpenAPI and AsyncAPI linters have rules of the same name, [safe-markdown](/docs/linter/openapi/rules/safe-markdown) and [safe-markdown](/docs/linter/asyncapi/rules/safe-markdown). ## Examples **Good**. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 description: Manages the pets of a shelter and their adoptions. paths: {} ``` **Bad**. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 description: "Manages the pets of a shelter. <script>alert('Unsafe')</script>" paths: /pets: get: description: Evaluates eval(filter) on the server. responses: '200': description: The list of pets. ``` ## Automatic fixes When invoked with `--fix`, the rule rewrites the affected descriptions: the `<` of the opening and closing `script` tags is replaced with `<`, and the `(` after `eval` with `(`. The rest of the description, including code spans and code blocks, is preserved. --- # schema-constraints Source: https://apigenie.pl/docs/linter/swagger/rules/schema-constraints A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at warning. This rule ensures that typed objects of a Swagger 2.0 document define constraints restricting the size of the underlying data. ## Rule details A schema without bounds accepts a 2 GB string in a name and an array of a million items in a request: the server that stores them is the first to find out. Bounds in the document are checked by validators and mocks, and generated clients and servers pick the right types. The `schema-constraints` rule checks every object of the document that has a `type`: schemas (definitions, properties, `items`, `allOf` members, `additionalProperties`, body parameter and response schemas), non-body parameters, response headers and `items` objects. Objects with a `$ref` are skipped (their targets are checked where they are defined), and body parameters are checked through their schema. Depending on the type, the rule requires: - `integer` - both `maximum` and `minimum`; it reports `Integer schema does not define constraints restricting its range`, - `number` - both `maximum` and `minimum`; it reports `Numeric schema does not define constraints restricting its range`, - `string` - `maxLength`, `pattern`, `format` or `enum`; it reports `String schema does not define constraints restricting its length`, - `array` - `maxItems`; it reports `Array schema does not define constraints restricting its size`, - `object` - `maxProperties` or `additionalProperties: false`; it reports `Object schema does not define constraints restricting its size`. Only schemas are checked for this type. Objects of type `boolean` or `file`, and schemas without a `type`, are not checked. The OpenAPI linter has a rule of the same name, [schema-constraints](/docs/linter/openapi/rules/schema-constraints), for OpenAPI 3.x documents. Turn the rule off when the API does not bound the size of its values. ## Configuration The configuration is an object whose keys are the types `integer`, `number`, `string`, `array` and `object`, and whose values are booleans. Only the types set to `true` are checked, and at least one type must be set to `true`. By default, all five types are checked. The `recommended` ruleset checks only `number` and `string`. **Configuration example**. The rule with the following configuration checks only arrays and objects. ```yaml version: "1.0" commands: lint: swagger: rules: schema-constraints: - warning - array: true object: true ``` ## Examples **Good**. ```yaml swagger: '2.0' info: title: Users version: 1.0.0 paths: /users: get: parameters: - name: limit in: query type: integer minimum: 1 maximum: 100 responses: '200': description: Users schema: type: array maxItems: 100 items: $ref: '#/definitions/User' definitions: User: type: object additionalProperties: false properties: username: type: string pattern: "^[a-z0-9_-]{3,16}$" roles: type: array maxItems: 5 items: type: string enum: [admin, member] age: type: integer minimum: 18 maximum: 100 ``` **Bad**. None of the typed objects is constrained. ```yaml swagger: '2.0' info: title: Users version: 1.0.0 paths: /users: get: parameters: - name: limit in: query type: integer responses: '200': description: Users schema: type: array items: $ref: '#/definitions/User' definitions: User: type: object properties: username: type: string roles: type: array items: type: string age: type: integer ``` --- # schema-datetime-suffix Source: https://apigenie.pl/docs/linter/swagger/rules/schema-datetime-suffix A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule ensures that the names of date and date-time properties end with a common suffix. ## Rule details A consistent suffix makes temporal properties easy to recognize, and distinguishes them from other properties describing the same concept (e.g. `created_at` versus `created_by`). The `schema-datetime-suffix` rule checks the `properties` of every schema of a Swagger 2.0 document. For every property whose schema has the `date` or `date-time` format and whose name does not end with the configured suffix, it reports `Property name <name> should end with <suffix>`. A property defined with a `$ref` has the format of the referenced schema. The issue is reported at the property itself, not at a (possibly shared) referenced schema. The default suffix is `_at`. The OpenAPI linter has a rule of the same name, [schema-datetime-suffix](/docs/linter/openapi/rules/schema-datetime-suffix), for OpenAPI 3.x documents. Turn the rule off if your API follows a different convention for naming temporal properties. ## Configuration The configuration block is a non-empty string: the required suffix. **Configuration example**. The following configuration requires temporal properties to end with `At`, which fits camelCase property names. ```yaml version: "1.0" commands: lint: swagger: rules: schema-datetime-suffix: [warning, At] ``` ## Examples **Good**. With the default configuration. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: {} definitions: Adoption: type: object properties: adopted_at: type: string format: date-time born_at: $ref: '#/definitions/Day' Day: type: string format: date ``` **Bad**. With the default configuration, both properties are reported. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: {} definitions: Adoption: type: object properties: adoption_date: type: string format: date-time birthday: $ref: '#/definitions/Day' Day: type: string format: date ``` --- # schema-enum-naming Source: https://apigenie.pl/docs/linter/swagger/rules/schema-enum-naming A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule ensures that the string values of `enum` lists adhere to a predefined naming convention. ## Rule details Enum values are spelled by clients, in code and in requests, so a client author who has seen one should be able to spell the next. The `schema-enum-naming` rule checks the `enum` list of every typed object of a Swagger 2.0 document: schemas, non-body parameters, response headers and `items` objects (objects with a `$ref` are checked where they are defined). For every string value that is not in the expected convention, it reports `Schema enum value '<value>' is not in the '<convention>' convention`, where `<convention>` is the display name of the convention (e.g. `CONST_CASE`). Values of other types (numbers, booleans, ...) are ignored. The recognized naming conventions are: - `CONST_CASE` (also `UPPER_CASE` and `SCREAMING_SNAKE_CASE`) - THIS_IS_CONST_CASE - `camelCase` - thisIsCamelCase, also with acronyms (userID) - `camelCaseStrict` - thisIsCamelCase, but no two capitals in a row (userId, not userID) - `kebab-case` - this-is-kebab-case - `PascalCase` - ThisIsPascalCase, also with acronyms (HTTPServer) - `PascalCaseStrict` - ThisIsPascalCase, but no two capitals in a row (HttpServer, not HTTPServer) - `Header-Case` - This-Is-Header-Case - `snake_case` - this_is_snake_case The default convention is `CONST_CASE`. The OpenAPI linter has a rule of the same name, [schema-enum-naming](/docs/linter/openapi/rules/schema-enum-naming), for OpenAPI 3.x documents. Turn the rule off when the API follows no naming convention for `enum` values. ## Configuration The configuration block is a naming convention name (see the "Rule details" section for a list of recognized names). ```yaml version: "1.0" commands: lint: swagger: rules: schema-enum-naming: [warning, kebab-case] ``` ## Examples **Good**. With the default configuration. ```yaml swagger: '2.0' info: title: Users version: 1.0.0 paths: /users: get: parameters: - name: sort in: query type: string enum: [ASCENDING, DESCENDING] responses: '200': description: Users definitions: UserStatus: type: string enum: - ACTIVE - INACTIVE - BLOCKED ``` **Bad**. To use `UserStatus` properly, a consumer must always consult the documentation. ```yaml swagger: '2.0' info: title: Users version: 1.0.0 paths: {} definitions: UserStatus: type: string enum: - activeStatus - inactive_status - BLOCKED_STATUS ``` --- # schema-enum-no-duplicates Source: https://apigenie.pl/docs/linter/swagger/rules/schema-enum-no-duplicates A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule ensures that `enum` lists do not contain duplicate values. ## Rule details A duplicate enum value is redundant and usually a copy-paste mistake. It may also break code generators, which turn enum values into constants that must be unique. The `schema-enum-no-duplicates` rule checks the `enum` list of every typed object of a Swagger 2.0 document: schemas, non-body parameters, response headers and `items` objects (objects with a `$ref` are checked where they are defined). It reports `Duplicate enum value` once for every value that is equal to a value listed before it. Values are compared structurally: arrays are equal when their elements are equal in order, and objects are equal when they have the same keys with equal values, regardless of the order of the keys. The OpenAPI linter has a rule of the same name, [schema-enum-no-duplicates](/docs/linter/openapi/rules/schema-enum-no-duplicates), for OpenAPI 3.x documents. ## Examples **Good**. ```yaml swagger: '2.0' info: title: Users version: 1.0.0 paths: {} definitions: UserStatus: type: string enum: [ACTIVE, INACTIVE] ``` **Bad**. `ACTIVE` is listed twice, and the two points differ only in the order of their keys. ```yaml swagger: '2.0' info: title: Users version: 1.0.0 paths: {} definitions: UserStatus: type: string enum: [ACTIVE, INACTIVE, ACTIVE] Corner: type: object enum: - { x: 1, y: 2 } - { y: 2, x: 1 } ``` ## Automatic fixes `--fix` removes every duplicate value, keeping the first occurrence of each value. --- # schema-enum-types Source: https://apigenie.pl/docs/linter/swagger/rules/schema-enum-types A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule ensures that all values of an `enum` list match the declared `type`. ## Rule details An enum value that does not match the type can never be valid, and usually indicates a mistake in either the type or the values. The `schema-enum-types` rule checks every typed object of a Swagger 2.0 document that has an `enum` list: schemas, non-body parameters, response headers and `items` objects (objects with a `$ref` are checked where they are defined). It reports `Enum value type is not in the schema type` when the object has no `type`, or when at least one value does not match it: - `string` accepts strings, - `integer` accepts integral numbers, - `number` accepts integral and fractional numbers, - `boolean` accepts `true` and `false`, - `array` accepts arrays, - `object` accepts objects. Swagger 2.0 has no `null` type, so `null` never matches, and no value matches the `file` type. The OpenAPI linter has a rule of the same name, [schema-enum-types](/docs/linter/openapi/rules/schema-enum-types), for OpenAPI 3.x documents. ## Examples **Good**. ```yaml swagger: '2.0' info: title: Tasks version: 1.0.0 paths: {} definitions: Status: type: string enum: [OPEN, CLOSED] Ratio: type: number enum: [1, 2.5] ``` **Bad**. The values of `Priority` are integers, and `Status` has no type. ```yaml swagger: '2.0' info: title: Tasks version: 1.0.0 paths: {} definitions: Priority: type: string enum: [1, 2, 3] Status: enum: [OPEN, CLOSED] ``` ## Automatic fixes `--fix` sets the `type` of a reported object to the type of its enum values, provided that all values have the same type (and are not `null`) and the object has no `format`. In the "Bad" example above, `Priority` gets `type: integer` and `Status` gets `type: string`. Objects mixing values of different types are not fixed. --- # schema-example-defined Source: https://apigenie.pl/docs/linter/swagger/rules/schema-example-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule ensures that the schemas of a Swagger 2.0 document provide examples. ## Rule details Examples make an API easier to understand, and are used by documentation tools, mock servers and API consoles. The `schema-example-defined` rule checks: - every entry of `definitions`, reporting `Schema does not define examples` when it has no `example`, - the inline schema of every body parameter, reporting `Body parameter schema does not define examples` when it has no `example`, - the inline schema of every response, reporting `Response schema does not define examples` when it has no `example` and the response has no `examples`. Schemas defined with a `$ref` are not reported: the referenced definition is checked instead. Schemas nested in other schemas (properties, `items`, ...) are not checked. The OpenAPI linter has a rule of the same name, [schema-example-defined](/docs/linter/openapi/rules/schema-example-defined), for OpenAPI 3.x documents. Turn the rule off if examples are provided outside the document. ## Examples **Good**. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: /pets: post: parameters: - name: pet in: body required: true schema: $ref: '#/definitions/Pet' responses: '201': description: Created schema: type: object properties: id: type: integer examples: application/json: id: 42 definitions: Pet: type: object properties: name: type: string example: name: Rex ``` **Bad**. The inline body parameter schema and the `PetId` definition, used by the response, provide no examples. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: /pets: post: parameters: - name: pet in: body required: true schema: type: object properties: name: type: string responses: '201': description: Created schema: $ref: '#/definitions/PetId' definitions: PetId: type: object properties: id: type: integer ``` --- # schema-format-defined Source: https://apigenie.pl/docs/linter/swagger/rules/schema-format-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule ensures that numeric objects declare the size of their values with a `format`. ## Rule details The `integer` and `number` types do not say how large values may be or which precision they have. The formats `int32`, `int64`, `float` and `double` let consumers and code generators choose suitable native types. The `schema-format-defined` rule checks every typed object of a Swagger 2.0 document: schemas, non-body parameters, response headers and `items` objects (objects with a `$ref` are checked where they are defined). It reports: - `Schema with integer type does not define proper format` for an `integer` object whose `format` is not `int32` or `int64`, - `Schema with number type does not define proper format` for a `number` object whose `format` is not `float` or `double`. Objects of other types are not checked. The OpenAPI linter has a rule of the same name, [schema-format-defined](/docs/linter/openapi/rules/schema-format-defined), for OpenAPI 3.x documents. Turn the rule off if the size of numeric values does not matter for your API. ## Examples **Good**. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: /pets: get: parameters: - name: limit in: query type: integer format: int32 responses: '200': description: Pets definitions: Pet: type: object properties: id: type: integer format: int64 weight: type: number format: double ``` **Bad**. The parameter has no format, and the properties have formats of other types. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: /pets: get: parameters: - name: limit in: query type: integer responses: '200': description: Pets definitions: Pet: type: object properties: id: type: integer format: uuid weight: type: number format: int32 ``` --- # schema-format-deprecated Source: https://apigenie.pl/docs/linter/swagger/rules/schema-format-deprecated A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.10.0. In the rulesets: Recommended at warning, Strict at warning, All at warning. This rule reports the formats which the [OpenAPI format registry](https://spec.openapis.org/registry/format/) marks as deprecated from OpenAPI 3.1, and names what replaces them. ## Rule details | Format | Use instead | | ------ | ----------- | | `byte` | `contentEncoding: base64` | | `base64url` | `contentEncoding: base64url` | | `binary` | `contentMediaType`, or the media type of the body or part without a schema | Swagger 2.0 has no replacement for these formats, so the issues are always hints: they mark what needs a change when the document is converted to OpenAPI 3.1, and never count as warnings. See [Formats](/docs/reference/cli/formats) for every format. Turn the rule off when the documents must stay readable by tools that only know the older formats. ## Examples **Good**. ```yaml swagger: '2.0' definitions: Avatar: type: string ``` **Bad**. ```yaml swagger: '2.0' definitions: Avatar: type: string format: byte ``` --- # schema-format-type-mismatch Source: https://apigenie.pl/docs/linter/swagger/rules/schema-format-type-mismatch A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule ensures that the `format` of an object is one that applies to its `type`. ## Rule details Each well-known format applies to a single type. A format paired with another type (e.g. `type: integer` with `format: date-time`) is contradictory, and tools interpret it inconsistently. The `schema-format-type-mismatch` rule checks every object of a Swagger 2.0 document that has a `format`: schemas, non-body parameters, response headers and `items` objects (objects with a `$ref` are checked where they are defined). It checks the formats Swagger 2.0 defines and the JSON Schema ones it allows, with the JSON types the [OpenAPI format registry](https://spec.openapis.org/registry/format/) gives them, and the formats of `openapi.custom_formats` in the configuration file: - `int32`, `int64` - `integer` or `number`, and `string` for `int64`, - `float`, `double` - `number`, - `byte`, `binary`, `date`, `date-time`, `password`, `email`, `hostname`, `ipv4`, `ipv6`, `uri`, `uuid` - `string`. For these formats, it reports `Schema type and format do not match` when the object has another `type` or no `type` at all. Other formats are left to [schema-format-unknown](/docs/linter/swagger/rules/schema-format-unknown). The OpenAPI linter has a rule of the same name, [schema-format-type-mismatch](/docs/linter/openapi/rules/schema-format-type-mismatch), for OpenAPI 3.x documents. Turn the rule off if your API uses well-known format names with a different meaning. ## Configuration The configuration block is an object with a single optional boolean property, `fixTypeFromFormat`, which controls whether reported issues can be fixed automatically (see "Automatic fixes"). The default value is `true`. **Configuration example**. The following configuration reports mismatches, but does not fix them. ```yaml version: "1.0" commands: lint: swagger: rules: schema-format-type-mismatch: - error - fixTypeFromFormat: false ``` ## Examples **Good**. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: {} definitions: Pet: type: object properties: id: type: string format: uuid born_at: type: string format: date-time weight: type: number format: float ``` **Bad**. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: {} definitions: Pet: type: object properties: id: type: integer format: uuid born_at: format: date-time ``` ## Automatic fixes When `fixTypeFromFormat` is `true` and the linter is invoked with the `--fix` option, this rule sets the `type` of every reported object to the type the format applies to. In the "Bad" example above, both properties get `type: string`. --- # schema-format-unknown Source: https://apigenie.pl/docs/linter/swagger/rules/schema-format-unknown A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.10.0. In the rulesets: Strict at warning, All at warning. This rule reports a `format` of a Swagger 2.0 document which is neither in the [OpenAPI format registry](https://spec.openapis.org/registry/format/) nor declared in `openapi.custom_formats` of the [configuration file](/docs/reference/cli/configuration#openapicustom_formats). ## Rule details Tools ignore formats they do not know, so a misspelled format (`date_time`, `uuid4`) stops being checked without a word. Formats defined on purpose are declared in the configuration file: ```yaml openapi: custom_formats: - {name: currency-code, type: string} ``` The rule is off in the `recommended` ruleset and a warning in `strict` and `all`. See [Formats](/docs/reference/cli/formats) for the registry's formats. Turn the rule off when the documents use many formats of their own and listing them in the configuration file is not worth it. ## Examples **Good**. `uuid` is in the registry. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: {} definitions: PetId: type: string format: uuid ``` **Bad**. `uuid4` is not, so nothing checks the value. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: {} definitions: PetId: type: string format: uuid4 ``` --- # schema-no-additional-properties Source: https://apigenie.pl/docs/linter/swagger/rules/schema-no-additional-properties A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at error, Strict at error, All at error. This rule ensures that object schemas do not accept arbitrary additional properties. ## Rule details An object schema accepts properties that are not listed in `properties` unless `additionalProperties` is `false`. Open objects hide typos in property names, and let undocumented data pass through the API. The `schema-no-additional-properties` rule checks every schema of a Swagger 2.0 document with `type: object` (schemas with a `$ref` are checked where they are defined). It reports `Object schema does not disable additional properties` when `additionalProperties` is absent or `true`. A schema value of `additionalProperties` describes a map whose values have that schema. This is a deliberate choice, and such schemas are not reported. The OpenAPI linter has a rule of the same name, [schema-no-additional-properties](/docs/linter/openapi/rules/schema-no-additional-properties), for OpenAPI 3.x documents. Turn the rule off if your API deliberately accepts or returns properties that are not described, for example to stay compatible with future versions. ## Examples **Good**. `Pet` is closed, and `Labels` is a map of strings. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: {} definitions: Pet: type: object additionalProperties: false properties: name: type: string labels: $ref: '#/definitions/Labels' Labels: type: object additionalProperties: type: string ``` **Bad**. Both `Pet` and its `owner` property accept any additional property. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: {} definitions: Pet: type: object properties: name: type: string owner: type: object additionalProperties: true properties: name: type: string ``` ## Automatic fixes `--fix` sets `additionalProperties: false` on every reported schema. --- # schema-property-naming Source: https://apigenie.pl/docs/linter/swagger/rules/schema-property-naming A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule ensures that the names of schema properties adhere to a predefined naming convention. ## Rule details Property names are typed by every client, and one convention lets a client author who has seen one name spell the next; it also maps payloads to the data structures of one language without renaming. The `schema-property-naming` rule checks the keys of the `properties` map of every schema of a Swagger 2.0 document (schemas with a `$ref` are checked where they are defined). For every property whose name is not in the expected convention, it reports `Schema property '<name>' is not in the '<convention>' convention`, where `<convention>` is the display name of the convention (e.g. `snake_case`). The issue is reported at the schema that declares the property. The recognized naming conventions are: - `CONST_CASE` (also `UPPER_CASE` and `SCREAMING_SNAKE_CASE`) - THIS_IS_CONST_CASE - `camelCase` - thisIsCamelCase, also with acronyms (userID) - `camelCaseStrict` - thisIsCamelCase, but no two capitals in a row (userId, not userID) - `kebab-case` - this-is-kebab-case - `PascalCase` - ThisIsPascalCase, also with acronyms (HTTPServer) - `PascalCaseStrict` - ThisIsPascalCase, but no two capitals in a row (HttpServer, not HTTPServer) - `Header-Case` - This-Is-Header-Case - `snake_case` - this_is_snake_case The default convention is `snake_case`. The OpenAPI linter has a rule of the same name, [schema-property-naming](/docs/linter/openapi/rules/schema-property-naming), for OpenAPI 3.x documents. Turn the rule off when the API follows no naming convention for property names. ## Configuration The configuration block is a naming convention name (see the "Rule details" section for a list of recognized names). ```yaml version: "1.0" commands: lint: swagger: rules: schema-property-naming: [error, camelCase] ``` ## Examples **Good**. With the default configuration. ```yaml swagger: '2.0' info: title: Users version: 1.0.0 paths: {} definitions: User: type: object properties: first_name: type: string last_name: type: string ``` **Bad**. With the default configuration. ```yaml swagger: '2.0' info: title: Users version: 1.0.0 paths: {} definitions: User: type: object properties: firstName: type: string LastName: type: string ``` --- # schema-required-properties-defined Source: https://apigenie.pl/docs/linter/swagger/rules/schema-required-properties-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that every name listed in `required` is declared in `properties`. ## Rule details A required property which is not declared is usually a typo (`required: [nmae]`) or a property removed from `properties` but not from `required`. Its value is not described, and generated code often cannot represent it. The `schema-required-properties-defined` rule checks every schema of a Swagger 2.0 document that has a `required` list. It looks for the declaration of each name wherever the value of the schema is also described: - in the `properties` of the schema itself, - in its `allOf` members, following references, - in the schemas it is an `allOf` member of, and in their other members. For every name that is not declared, it reports `Required property '<name>' is not defined in 'properties'`. Schemas which may allow undeclared properties on purpose are skipped: when a schema of the group has a schema in `additionalProperties` (a map) or `additionalProperties: true`. Schemas whose group contains a reference that cannot be resolved are skipped too. `required` in a schema that declares types (itself or through its `allOf` members) none of which is `object`, for example beside `items` in an array schema instead of inside it, has no effect. The rule reports it with `'required' has no effect because the schema does not allow objects`. The OpenAPI linter has a rule of the same name, [schema-required-properties-defined](/docs/linter/openapi/rules/schema-required-properties-defined), for OpenAPI 3.x documents. Turn the rule off when required properties are intentionally left undescribed. ## Examples **Good**. `name` is declared by the `allOf` member `Named`. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: {} definitions: Named: type: object properties: name: type: string Pet: allOf: - $ref: '#/definitions/Named' - type: object required: [name, age] properties: age: type: integer ``` **Bad**. `nmae` is not declared. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: {} definitions: Pet: type: object required: [nmae] properties: name: type: string ``` **Bad**. `required` applies to the array, not to its items. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: {} definitions: Pets: type: array required: [name] items: type: object properties: name: type: string ``` --- # schemes-secure Source: https://apigenie.pl/docs/linter/swagger/rules/schemes-secure A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether a Swagger 2.0 document serves its API over secure transfer protocols only, and whether its host is written in lower case. ## Rule details The root `schemes` list, and the `schemes` lists of operations that override it, name the transfer protocols of the API. `http` and `ws` send requests, credentials and responses unencrypted, so production APIs should use `https` and `wss` instead. The `schemes-secure` rule reports: - `Insecure scheme (http)` or `Insecure scheme (ws)` for every insecure scheme in the root `schemes` list and in the `schemes` list of every operation, - `Host is not lower case` when the root `host` contains upper case letters. Host names are case-insensitive, and lower case is their canonical form. Insecure schemes are allowed when `host` is a loopback address: `localhost` (in any letter case), `127.0.0.1` or `[::1]`, with or without a port. When `host` is missing, insecure schemes are reported. The OpenAPI linter has [server-urls](/docs/linter/openapi/rules/server-urls) for OpenAPI 3.x documents. Turn the rule off for documents that describe APIs that are only reachable in a trusted network, or for an operation with `x-apigenie-lint-disable: [schemes-secure]`. ## Configuration The rule accepts an object with one option: - `upgradeInsecure`: whether `--fix` replaces insecure schemes with their secure variants. Default: `false`. **Configuration example** ```yaml version: "1.0" commands: lint: swagger: rules: schemes-secure: - error - upgradeInsecure: true ``` ## Examples **Good**. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 host: api.example.com schemes: [https, wss] paths: {} ``` **Good**. A local development server may use `http`. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 host: localhost:8080 schemes: [http] paths: {} ``` **Bad**. The root object allows `http`, an operation uses `ws`, and the host is not lower case. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 host: API.Example.com schemes: [http, https] paths: /pets/events: get: schemes: [ws] responses: '101': description: Switching to the event stream. ``` ## Automatic fixes When invoked with `--fix`, the rule always converts the root `host` to lower case. With `upgradeInsecure: true`, it also rewrites every root and operation `schemes` list that contains an insecure scheme, unless the host is a loopback address: `http` becomes `https`, `ws` becomes `wss`, and duplicates are removed while the order is kept. For example, `[http, https, ws]` becomes `[https, wss]`. Without this option the insecure schemes are reported, but not changed, because switching protocols requires the server to support them. --- # spell-check Source: https://apigenie.pl/docs/linter/swagger/rules/spell-check A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Strict at warning, All at warning. This rule checks the spelling of the texts of a Swagger 2.0 document written for humans: titles, summaries and descriptions. ## Rule details The rule reports every misspelled word, with up to three suggested corrections, for example `Misspelled word 'Recieve' in summary (did you mean 'Receive', 'Relieve', 'Reverie'?)`. When there are no suggestions, the part in parentheses is omitted. The issue points at the object whose text contains the word. The rule checks: - the title and description of the info object, - the summary and description of operations, - the title and description of schemas, - the description of parameters, responses (but not response references), headers, security definitions, tags and external documentation objects. Descriptions are Markdown (GFM in Swagger 2.0): the rule checks their prose, and skips code spans, code blocks, raw HTML and link destinations. Titles and summaries are plain text, in which `backticked` spans are skipped, too. The rule also skips the tokens which are not plain words: - URLs, e-mail addresses, paths, and file and domain names (`swagger.yaml`, `example.com`), - identifiers: `snake_case`, `camelCase` and names with inner capitals (`PetStore`), - acronyms, also in the plural (`HTTP`, `APIs`, `ID's`), - tokens with digits (`v2`, `401`) and single letters. The spell checker is a C++ port of [Hunspell](https://hunspell.github.io). By default it uses the built-in English (US) dictionary from [SCOWL](http://wordlist.aspell.net) (as shipped with LibreOffice), extended with words common in API descriptions, such as `webhook`, `endpoint`, `namespace`, `nullable` and `json`. Any Hunspell dictionary can be used instead. The rule is part of the `strict` and `all` rulesets. The OpenAPI and AsyncAPI linters have rules of the same name, [spell-check](/docs/linter/openapi/rules/spell-check) and [spell-check](/docs/linter/asyncapi/rules/spell-check). Turn the rule off if your documentation is written in a language you have no dictionary for. To silence it for a single object and its children, add `x-apigenie-lint-disable: [spell-check]` to the object. ## Configuration This rule accepts an object with the following options: - `words`: extra words to accept, for example product names. A word is accepted as given, capitalized and in capitals: `petstore` accepts `petstore`, `Petstore` and `PETSTORE`. - `dictionary` and `affix`: paths of a Hunspell dictionary (`.dic`) and its affix file (`.aff`) to use instead of the built-in dictionary. They go together. Dictionaries in UTF-8, ISO-8859-1, ISO-8859-2 and ISO-8859-15 are supported. - `suggestions`: how many corrections to suggest for a word, from 0 to 10 (default 3). Suggestions are the costly part of the rule; on a very large document with many unknown words, `0` makes it about ten times faster. **Configuration example** ```yaml version: "1.0" commands: lint: swagger: rules: spell-check: - warning - words: [petstore] dictionary: path/to/en_GB.dic affix: path/to/en_GB.aff ``` ## Examples **Good**. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: summary: Receive the list of pets description: Returns the pets available for adoption. responses: '200': description: The list of pets. ``` **Bad**. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: summary: Recieve the list of pets description: Returns the pets availabel for adoption. responses: '200': description: The list of pets. ``` --- # standard-media-types Source: https://apigenie.pl/docs/linter/swagger/rules/standard-media-types A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether a Swagger 2.0 document uses only well-known media types. ## Rule details Non-standard or misspelled media types lead to interoperability issues: clients and servers may fail to negotiate the format of requests and responses. The `standard-media-types` rule checks: - the root `consumes` and `produces` lists, - the `consumes` and `produces` lists of every operation, - the media type keys of the `examples` of every response (response references are skipped). It reports `Non-standard media type is used (<media type>)` for every value that is not on the built-in list of well-known media types, such as `application/json`, `application/xml`, `application/x-www-form-urlencoded`, `multipart/form-data`, `text/plain` or `application/octet-stream`. Wildcards (`*/*`, `application/*`) are accepted, and parameters after `;` (like `charset=utf-8`) are ignored. Values without a subtype, like `json`, are reported. The OpenAPI and AsyncAPI linters have rules of the same name, [standard-media-types](/docs/linter/openapi/rules/standard-media-types) and [standard-media-types](/docs/linter/asyncapi/rules/standard-media-types). Turn the rule off if your API deliberately uses vendor-specific media types that are not on the built-in list. ## Examples **Good**. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 consumes: [application/json] produces: [application/json, application/xml] paths: /pets: get: produces: [text/plain] responses: '200': description: The list of pets. examples: text/plain: Rex, Fluffy ``` **Bad**. `application/x-custom` and `text/foo` are not well-known media types, and `json` has no subtype. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 consumes: [application/x-custom] paths: /pets: get: produces: [json] responses: '200': description: The list of pets. examples: text/foo: Rex ``` --- # swagger-validation Source: https://apigenie.pl/docs/linter/swagger/rules/swagger-validation A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule reports violations of the Swagger 2.0 specification that span several objects, and therefore cannot be detected while a single object is read. ## Rule details The reader checks the structure of every object of a document, but some requirements of the specification relate several objects to each other: a security requirement must name a declared security definition, a path parameter must appear in its path template, and so on. The `swagger-validation` rule runs these checks: | Check | Requirement | | --- | --- | | `unique-operation-id` | `operationId` values are unique across the document | | `unique-parameter` | (`name`, `in`) pairs are unique within a parameter list | | `single-body-parameter` | an operation has at most one `body` parameter | | `body-form-data-exclusive` | `body` and `formData` parameters are not mixed | | `file-parameter-consumes` | `file` parameters require `multipart/form-data` or `application/x-www-form-urlencoded` in `consumes`; other `formData` parameters are reported when `consumes` lists neither | | `path-parameter-declared` | every path template variable has a `path` parameter | | `path-parameter-in-template` | every `path` parameter appears in the path template | | `security-scheme-defined` | security requirements refer to `securityDefinitions` | | `security-scope-defined` | `oauth2` requirements use declared scopes | | `security-scopes-empty` | requirements of other schemes have empty scope lists | | `unresolved-reference` | local references (`#/definitions`, `#/parameters`, `#/responses`) resolve | | `valid-scheme` | schemes are `http`, `https`, `ws` or `wss` | | `host-format` | `host` contains neither a scheme nor a path | | `unique-tag` | tag names are unique | | `discriminator-required` | a `discriminator` property is listed in `required` | Each message is the message of the check, followed by the check name in parentheses, for example `An operation can have at most one body parameter (single-body-parameter)` or `Unresolved reference '#/definitions/Missing' (unresolved-reference)`. All issues are reported with the severity of this rule. By default all checks run except `unique-operation-id`, `unique-parameter`, `path-parameter-declared` and `unique-tag`. These are covered by the dedicated rules `operation-id-unique`, `parameters-unique`, `path-parameters-defined` and `tags-unique`, which can also fix some of the issues. For OpenAPI 3.x documents, the OpenAPI linter has [openapi-json-schema-validation](/docs/linter/openapi/rules/openapi-json-schema-validation). Documents that violate these requirements are not valid Swagger 2.0 documents, and tools may reject or misread them. ## Configuration The rule accepts an object with one option: - `checks`: the names of the checks to run. The list replaces the default set of checks, so include every check you want. Unknown names are rejected. **Configuration example**. Run all checks, including those of the dedicated rules (which you would then disable). ```yaml version: "1.0" commands: lint: swagger: rules: swagger-validation: - error - checks: - unique-operation-id - unique-parameter - single-body-parameter - body-form-data-exclusive - file-parameter-consumes - path-parameter-declared - path-parameter-in-template - security-scheme-defined - security-scope-defined - security-scopes-empty - unresolved-reference - valid-scheme - host-format - unique-tag - discriminator-required ``` ## Examples **Good**. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 host: api.example.com schemes: [https] paths: /pets/{petId}: get: parameters: - name: petId in: path required: true type: string responses: '200': description: The pet. ``` **Bad**. The host includes a scheme, `ftp` is not a valid scheme, the security requirement names an undeclared security definition, the operation has two body parameters, and one of them refers to a missing definition. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 host: https://api.example.com schemes: [ftp] paths: /pets: post: parameters: - name: a in: body schema: $ref: '#/definitions/Missing' - name: b in: body schema: type: object security: - unknown: [] responses: '200': description: OK ``` --- # tag-description-defined Source: https://apigenie.pl/docs/linter/swagger/rules/tag-description-defined A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. In the rulesets: Recommended at warning, Strict at warning, All at warning. This rule checks whether each tag declared in the root `tags` array of a Swagger 2.0 document has a meaningful description. ## Rule details Tag descriptions explain the purpose of the groups of operations, which makes the structure of the API easier to understand in documentation and API consoles. The `tag-description-defined` rule reports `Tag '<name>' has no meaningful description defined` for every tag whose `description`: - is missing or empty, - is shorter than the configured minimal length (10 characters by default), - consists of whitespace only, - is one of the placeholders `TODO`, `FIXME` or `TBD` (in any letter case). The OpenAPI and AsyncAPI linters have rules of the same name, [tag-description-defined](/docs/linter/openapi/rules/tag-description-defined) and [tag-description-defined](/docs/linter/asyncapi/rules/tag-description-defined). ## Configuration A single positive integer: the minimal length of a meaningful description. The default value is 10. **Configuration example** ```yaml version: "1.0" commands: lint: swagger: rules: tag-description-defined: [warning, 20] ``` ## Examples **Good**. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: {} tags: - name: pets description: Operations on the pets of the shelter. - name: users description: Operations on the accounts of the shelter staff. ``` **Bad**. The first tag has a placeholder description, the second has none. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: {} tags: - name: pets description: TBD - name: users ``` --- # tags-sorted Source: https://apigenie.pl/docs/linter/swagger/rules/tags-sorted A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Strict at error, All at error. This rule checks whether the tags in the root `tags` array of a Swagger 2.0 document are sorted by name. ## Rule details Many tools show tags in the order in which they are declared. Keeping them sorted makes the document and its rendered documentation easier to browse. The `tags-sorted` rule compares the name of each tag with the name of the previous one, and reports `Tags are not sorted: <name>` for every tag that comes after a tag with a greater name. Names are compared byte by byte, so the comparison is case-sensitive and upper case letters sort before lower case ones. The OpenAPI and AsyncAPI linters have rules of the same name, [tags-sorted](/docs/linter/openapi/rules/tags-sorted) and [tags-sorted](/docs/linter/asyncapi/rules/tags-sorted). Turn the rule off if the order of your tags is meaningful, for example when it defines the order of sections in the generated documentation. ## Examples **Good**. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: {} tags: - name: owners - name: pets - name: users ``` **Bad**. `owners` comes after `pets`. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: {} tags: - name: users - name: pets - name: owners ``` ## Automatic fixes When invoked with `--fix`, the rule reorders the elements of the root `tags` array by name, using the same comparison. The tag objects themselves are not changed. --- # tags-unique Source: https://apigenie.pl/docs/linter/swagger/rules/tags-unique A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the tags in the root `tags` array of a Swagger 2.0 document have unique names, comparing names case-insensitively. ## Rule details The Swagger 2.0 specification requires tag names to be unique. Tags whose names differ only in letter case raise the same question: one group of operations, or two? The `tags-unique` rule reports `Tag name is not unique (<name>)` for each duplicate. Names are compared after converting ASCII letters to lower case. The issue normally points at the later duplicate; when the earlier tag has only a `name` and the later one has more properties, it points at the earlier tag instead. The `unique-tag` check of the `swagger-validation` rule reports exact duplicates too, but it is disabled by default in favor of this rule. The OpenAPI and AsyncAPI linters have rules of the same name, [tags-unique](/docs/linter/openapi/rules/tags-unique) and [tags-unique](/docs/linter/asyncapi/rules/tags-unique). ## Examples **Good**. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: {} tags: - name: pets - name: users ``` **Bad**. Two tags differ only in letter case. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: {} tags: - name: pets description: Operations on the pets of the shelter. - name: Pets description: Is this another tag, or a typo? ``` ## Automatic fixes When invoked with `--fix`, the rule removes a duplicate tag from the root `tags` array when it is safe to do so: - a duplicate that has only a `name` is removed, - when the earlier tag has only a `name` and the later duplicate has more properties, the earlier tag is removed, - a duplicate whose properties other than `name` are equal to those of the earlier tag is removed. Duplicates with different descriptions, external documentation or extensions are reported, but left for manual resolution. --- # unused-request-body Source: https://apigenie.pl/docs/linter/swagger/rules/unused-request-body A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether `GET` and `HEAD` operations of a Swagger 2.0 document declare a request body. ## Rule details HTTP gives no meaning to the body of a `GET` or `HEAD` request. Many clients, proxies and servers drop or reject such a body, so a body declared for these operations is unlikely to reach the API. In Swagger 2.0 the request body is described by a parameter with `in: body` or by parameters with `in: formData`. The `unused-request-body` rule reports `Unused request body` for every `get` or `head` operation whose own `parameters` contain a body or form data parameter. Parameter references (`$ref`) are resolved, so a reference to a shared body or form data parameter counts as well. Parameters declared on the path item are not checked. The OpenAPI linter has a rule of the same name, [unused-request-body](/docs/linter/openapi/rules/unused-request-body), for OpenAPI 3.x documents. Turn the rule off when your API and every client and intermediary between them are known to support bodies on `GET` requests. ## Examples **Good**. The `get` operation takes query parameters and the `post` operation takes a body. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: parameters: - name: limit in: query type: integer responses: '200': description: A list of pets. post: parameters: - name: pet in: body schema: $ref: '#/definitions/Pet' responses: '201': description: The pet was added. definitions: Pet: type: object properties: name: type: string ``` **Bad**. The `get` operation declares a body parameter and the `head` operation references a form data parameter. ```yaml swagger: '2.0' info: title: Pet Store version: 1.0.0 paths: /pets: get: parameters: - name: filter in: body schema: type: object - name: limit in: query type: integer responses: '200': description: A list of pets. head: parameters: - $ref: '#/parameters/name' responses: '200': description: The list of pets exists. parameters: name: name: name in: formData type: string ``` ## Automatic fixes `--fix` removes the body and form data parameters (including references to them) from the `parameters` of `get` and `head` operations. Other parameters are kept, and shared parameters under the root `parameters` are not changed. --- # unused-shared-component Source: https://apigenie.pl/docs/linter/swagger/rules/unused-shared-component A rule of the Swagger 2.0 linter, which reads Swagger 2.0 documents; OpenAPI 3 documents go to the OpenAPI linter. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether every shared object of a Swagger 2.0 document is actually used. ## Rule details Shared objects that are never used make the document longer and harder to maintain, and suggest that something is missing (for example, a response that was defined but never attached to an operation). The `unused-shared-component` rule checks every entry of the root `definitions`, `parameters`, `responses` and `securityDefinitions` maps, and reports `Unused shared component` for every entry that is not used: - An entry of `definitions`, `parameters` or `responses` is used when a local `$ref` of the form `#/<section>/<name>` (possibly pointing deeper into the entry, e.g. `#/definitions/Pet/properties/name`) appears anywhere outside these three sections, or inside another used entry. References are followed transitively, so a definition used only by an unused response is unused as well. References nested in untyped values, such as vendor extensions, count too. - An entry of `securityDefinitions` is used when its name appears in the root `security` requirements or in the `security` requirements of an operation. An entry that has this rule disabled (see below) is always considered used, and so is everything it references. The OpenAPI linter has a rule of the same name, [unused-shared-component](/docs/linter/openapi/rules/unused-shared-component), for OpenAPI 3.x documents. Turn the rule off for documents that serve as libraries of shared objects, referenced from other documents. ## Examples **Good**. Every shared object is used, directly or through another one. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 securityDefinitions: apiKey: type: apiKey name: X-API-Key in: header security: - apiKey: [] paths: /pets: get: parameters: - $ref: '#/parameters/limit' responses: '200': $ref: '#/responses/Pets' parameters: limit: name: limit in: query type: integer responses: Pets: description: Pets schema: type: array items: $ref: '#/definitions/Pet' definitions: Pet: type: object properties: owner: $ref: '#/definitions/Owner' Owner: type: object ``` **Bad**. The `basic` security scheme, the `offset` parameter and the `Shelter` definition are not used. ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 securityDefinitions: apiKey: type: apiKey name: X-API-Key in: header basic: type: basic security: - apiKey: [] paths: /pets: get: parameters: - $ref: '#/parameters/limit' responses: '200': description: Pets parameters: limit: name: limit in: query type: integer offset: name: offset in: query type: integer definitions: Shelter: type: object ``` To keep a shared object that is meant to be referenced from other documents, disable the rule on it: ```yaml swagger: '2.0' info: title: Pets version: 1.0.0 paths: {} definitions: Library: x-lint-disable: [unused-shared-component] type: object properties: item: $ref: '#/definitions/Item' Item: type: object ``` ## Automatic fixes `--fix` removes all unused entries. When every entry of a section is unused, the whole section is removed, so that no empty map is left behind. --- # argument-description-defined Source: https://apigenie.pl/docs/linter/graphql/rules/argument-description-defined A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that the arguments of fields and directives have a description. ## Rule details Descriptions are part of the schema: introspection serves them to GraphiQL, IDEs, documentation generators and code generators. A missing or blank description is reported; type extensions have no descriptions and are not checked. The rule applies to definitions. An `# apigenie-lint-disable argument-description-defined` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { user("The identifier of the user." id: ID!): User } ``` **Bad**. The linter reports `Argument 'Query.user(id:)' should have a description`. ```graphql type Query { user(id: ID!): User } ``` --- # argument-naming Source: https://apigenie.pl/docs/linter/graphql/rules/argument-naming A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that the argument names follow a naming convention, camelCase by default. ## Rule details Consistent names make a schema predictable for its clients: generated code, documentation and queries read the same everywhere. The rule reports a name that doesn't follow the convention, with the name converted to it as a suggestion. The rule applies to definitions. An `# apigenie-lint-disable argument-naming` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block can be a string, the convention, or an object with the properties: - `convention`: `camelCase`, `camelCaseStrict`, `PascalCase`, `PascalCaseStrict`, `snake_case`, `CONST_CASE` (or `UPPER_CASE`), `kebab-case` or `Header-Case`; the strict forms reject two capitals in a row (`userID`) - `allowLeadingUnderscore`: whether leading underscores are ignored, e.g. in `_service`; `false` by default ```yaml version: "1.0" commands: lint: graphql: rules: argument-naming: [warning, { convention: snake_case, allowLeadingUnderscore: true }] ``` ## Examples **Good**. ```graphql type Query { users(orderBy: String): [User] } ``` **Bad**. The linter reports `Argument name 'order_by' should be camelCase, e.g. 'orderBy'`. ```graphql type Query { users(order_by: String): [User] } ``` --- # arguments-sorted Source: https://apigenie.pl/docs/linter/graphql/rules/arguments-sorted A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error. This rule checks that the arguments of field and directive definitions are in alphabetical order. ## Rule details Sorted definitions are easier to find and produce smaller diffs. Names are compared ignoring case; the first name out of order of each list is reported. Turn the rule off when the order of definitions is meaningful, for example the most important fields first. The rule applies to definitions. An `# apigenie-lint-disable arguments-sorted` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { users(first: Int, last: Int): [User] } ``` **Bad**. The linter reports `Argument 'first' should come before 'last'`. ```graphql type Query { users(last: Int, first: Int): [User] } ``` --- # custom-scalar-specified-by Source: https://apigenie.pl/docs/linter/graphql/rules/custom-scalar-specified-by A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that custom scalars link their specification with `@specifiedBy`. ## Rule details A custom scalar is a contract between the server and its clients; the URL of its specification tells clients how to parse and serialize it. The rule applies to definitions. An `# apigenie-lint-disable custom-scalar-specified-by` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql scalar DateTime @specifiedBy(url: "https://www.rfc-editor.org/rfc/rfc3339") ``` **Bad**. The linter reports `Scalar type 'DateTime' should link its specification with @specifiedBy(url:)`. ```graphql scalar DateTime ``` --- # deprecation-date-defined Source: https://apigenie.pl/docs/linter/graphql/rules/deprecation-date-defined A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error. This rule checks that `@deprecated` directives have a deletion date that has not passed. ## Rule details A deletion date tells clients how long a deprecated element will stay, and reminds the schema authors to remove it. The date is an argument of `@deprecated`, `deletionDate` by default, in the format `YYYY-MM-DD`. A missing or invalid date, or a date in the past, is reported. The argument has to be added to the definition of `@deprecated` that the server uses. The rule applies to definitions. An `# apigenie-lint-disable deprecation-date-defined` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block is an object with the properties: - `argumentName`: the argument with the date, `deletionDate` by default - `today`: the current date as `YYYY-MM-DD`, for reproducible runs; the date of the run by default ```yaml version: "1.0" commands: lint: graphql: rules: deprecation-date-defined: [warning, { argumentName: removeAfter }] ``` ## Examples **Good**. ```graphql type User { login: String @deprecated(reason: "Use `name`.", deletionDate: "2099-01-01") } ``` **Bad**. The linter reports `The deprecation of field 'User.login' should have a deletion date ('deletionDate' argument)`. ```graphql type User { login: String @deprecated(reason: "Use `name`.") } ``` --- # deprecation-reason-defined Source: https://apigenie.pl/docs/linter/graphql/rules/deprecation-reason-defined A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that `@deprecated` directives have a reason. ## Rule details The reason is the only place where a schema tells its clients what to use instead of a deprecated field, argument or enum value. A missing or blank `reason` is reported. The rule applies to definitions. An `# apigenie-lint-disable deprecation-reason-defined` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type User { login: String @deprecated(reason: "Use `name`.") } ``` **Bad**. The linter reports `The deprecation of field 'User.login' should have a reason`. ```graphql type User { login: String @deprecated } ``` --- # description-capitalized Source: https://apigenie.pl/docs/linter/graphql/rules/description-capitalized A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that descriptions start with a capital letter. ## Rule details Descriptions are sentences shown by documentation tools. Descriptions starting with a character other than a letter, such as a backtick or a digit, are not reported. The rule applies to definitions. An `# apigenie-lint-disable description-capitalized` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql "The users of the shop." type User { id: ID! } ``` **Bad**. The linter reports `The description of object type 'User' should start with a capital letter`. ```graphql "the users of the shop." type User { id: ID! } ``` --- # description-style Source: https://apigenie.pl/docs/linter/graphql/rules/description-style A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that descriptions are written as block strings, or as single-line strings. ## Rule details One style of descriptions makes a schema easier to read and to diff. Block strings (`"""..."""`) are the default, as they allow descriptions to grow over several lines. The rule applies to definitions. An `# apigenie-lint-disable description-style` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block can be a string, `block` or `inline`, or an object with the `style` property. ```yaml version: "1.0" commands: lint: graphql: rules: description-style: [error, inline] ``` ## Examples **Good**. ```graphql """ A user of the shop. """ type User { id: ID! } ``` **Bad**. The linter reports `The description of object type 'User' should be a block string ("""...""")`. ```graphql "A user of the shop." type User { id: ID! } ``` --- # directive-description-defined Source: https://apigenie.pl/docs/linter/graphql/rules/directive-description-defined A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that directive definitions have a description. ## Rule details Descriptions are part of the schema: introspection serves them to GraphiQL, IDEs, documentation generators and code generators. A missing or blank description is reported; type extensions have no descriptions and are not checked. The rule applies to definitions. An `# apigenie-lint-disable directive-description-defined` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql "Requires the role to read the field." directive @auth(role: String) on FIELD_DEFINITION ``` **Bad**. The linter reports `Directive '@auth' should have a description`. ```graphql directive @auth(role: String) on FIELD_DEFINITION ``` --- # directive-naming Source: https://apigenie.pl/docs/linter/graphql/rules/directive-naming A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that directive names follow a naming convention, camelCase by default. ## Rule details Consistent names make a schema predictable for its clients: generated code, documentation and queries read the same everywhere. The rule reports a name that doesn't follow the convention, with the name converted to it as a suggestion. The rule applies to definitions. An `# apigenie-lint-disable directive-naming` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block can be a string, the convention, or an object with the properties: - `convention`: `camelCase`, `camelCaseStrict`, `PascalCase`, `PascalCaseStrict`, `snake_case`, `CONST_CASE` (or `UPPER_CASE`), `kebab-case` or `Header-Case`; the strict forms reject two capitals in a row (`userID`) - `allowLeadingUnderscore`: whether leading underscores are ignored, e.g. in `_service`; `false` by default ```yaml version: "1.0" commands: lint: graphql: rules: directive-naming: [warning, { convention: snake_case, allowLeadingUnderscore: true }] ``` ## Examples **Good**. ```graphql directive @cacheControl on FIELD_DEFINITION ``` **Bad**. The linter reports `Directive name 'CacheControl' should be camelCase, e.g. 'cacheControl'`. ```graphql directive @CacheControl on FIELD_DEFINITION ``` --- # enum-value-description-defined Source: https://apigenie.pl/docs/linter/graphql/rules/enum-value-description-defined A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that enum values have a description. ## Rule details Descriptions are part of the schema: introspection serves them to GraphiQL, IDEs, documentation generators and code generators. A missing or blank description is reported; type extensions have no descriptions and are not checked. The rule applies to definitions. An `# apigenie-lint-disable enum-value-description-defined` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql enum Kind { "A cat." CAT } ``` **Bad**. The linter reports `Enum value 'Kind.CAT' should have a description`. ```graphql enum Kind { CAT } ``` --- # enum-value-naming Source: https://apigenie.pl/docs/linter/graphql/rules/enum-value-naming A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that enum value names follow a naming convention, CONST_CASE by default. ## Rule details Consistent names make a schema predictable for its clients: generated code, documentation and queries read the same everywhere. The rule reports a name that doesn't follow the convention, with the name converted to it as a suggestion. The rule applies to definitions. An `# apigenie-lint-disable enum-value-naming` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block can be a string, the convention, or an object with the properties: - `convention`: `camelCase`, `camelCaseStrict`, `PascalCase`, `PascalCaseStrict`, `snake_case`, `CONST_CASE` (or `UPPER_CASE`), `kebab-case` or `Header-Case`; the strict forms reject two capitals in a row (`userID`) - `allowLeadingUnderscore`: whether leading underscores are ignored, e.g. in `_service`; `false` by default ```yaml version: "1.0" commands: lint: graphql: rules: enum-value-naming: [warning, { convention: snake_case, allowLeadingUnderscore: true }] ``` ## Examples **Good**. ```graphql enum Kind { SMALL_DOG } ``` **Bad**. The linter reports `Enum value name 'smallDog' should be CONST_CASE, e.g. 'SMALL_DOG'`. ```graphql enum Kind { smallDog } ``` --- # enum-values-sorted Source: https://apigenie.pl/docs/linter/graphql/rules/enum-values-sorted A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error. This rule checks that the values of each enum type definition and extension are in alphabetical order. ## Rule details Sorted definitions are easier to find and produce smaller diffs. Names are compared ignoring case; the first name out of order of each list is reported. Turn the rule off when the order of definitions is meaningful, for example the most important fields first. The rule applies to definitions. An `# apigenie-lint-disable enum-values-sorted` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql enum Kind { BIRD, CAT } ``` **Bad**. The linter reports `Enum value 'BIRD' should come before 'CAT'`. ```graphql enum Kind { CAT, BIRD } ``` --- # field-description-defined Source: https://apigenie.pl/docs/linter/graphql/rules/field-description-defined A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that the fields of object and interface types have a description. ## Rule details Descriptions are part of the schema: introspection serves them to GraphiQL, IDEs, documentation generators and code generators. A missing or blank description is reported; type extensions have no descriptions and are not checked. The rule applies to definitions. An `# apigenie-lint-disable field-description-defined` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type User { "The identifier of the user." id: ID! } ``` **Bad**. The linter reports `Field 'User.id' should have a description`. ```graphql type User { id: ID! } ``` --- # field-naming Source: https://apigenie.pl/docs/linter/graphql/rules/field-naming A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that the field names follow a naming convention, camelCase by default. ## Rule details Consistent names make a schema predictable for its clients: generated code, documentation and queries read the same everywhere. The rule reports a name that doesn't follow the convention, with the name converted to it as a suggestion. The rule applies to definitions. An `# apigenie-lint-disable field-naming` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block can be a string, the convention, or an object with the properties: - `convention`: `camelCase`, `camelCaseStrict`, `PascalCase`, `PascalCaseStrict`, `snake_case`, `CONST_CASE` (or `UPPER_CASE`), `kebab-case` or `Header-Case`; the strict forms reject two capitals in a row (`userID`) - `allowLeadingUnderscore`: whether leading underscores are ignored, e.g. in `_service`; `false` by default ```yaml version: "1.0" commands: lint: graphql: rules: field-naming: [warning, { convention: snake_case, allowLeadingUnderscore: true }] ``` ## Examples **Good**. ```graphql type User { firstName: String } ``` **Bad**. The linter reports `Field name 'first_name' should be camelCase, e.g. 'firstName'`. ```graphql type User { first_name: String } ``` --- # fields-on-correct-type Source: https://apigenie.pl/docs/linter/graphql/rules/fields-on-correct-type A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the fields selected by operations are defined by their parent types. ## Rule details A field that its type doesn't define is rejected by the server. `__typename`, and `__schema` and `__type` on the query root type, are allowed. The rule checks operations against the schema files named by the `schema` property of the configuration, or against the type system of their own document. It reports nothing without a schema. The rule applies to operations and fragments. An `# apigenie-lint-disable fields-on-correct-type` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Me { me { id name } } ``` **Bad**. The linter reports `Cannot query field "nmae" on type "User".`. ```graphql query Me { me { id nmae } } ``` --- # fields-sorted Source: https://apigenie.pl/docs/linter/graphql/rules/fields-sorted A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error. This rule checks that the fields of each object and interface type definition and extension are in alphabetical order. ## Rule details Sorted definitions are easier to find and produce smaller diffs. Names are compared ignoring case; the first name out of order of each list is reported. Turn the rule off when the order of definitions is meaningful, for example the most important fields first. The rule applies to definitions. An `# apigenie-lint-disable fields-sorted` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type User { email: String, id: ID!, name: String } ``` **Bad**. The linter reports `Field 'email' should come before 'id'`. ```graphql type User { id: ID!, email: String } ``` --- # fragment-naming Source: https://apigenie.pl/docs/linter/graphql/rules/fragment-naming A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that fragment names follow a naming convention, PascalCase by default. ## Rule details Consistent names make a schema predictable for its clients: generated code, documentation and queries read the same everywhere. The rule reports a name that doesn't follow the convention, with the name converted to it as a suggestion. The rule applies to operations and fragments. An `# apigenie-lint-disable fragment-naming` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block can be a string, the convention, or an object with the properties: - `convention`: `camelCase`, `camelCaseStrict`, `PascalCase`, `PascalCaseStrict`, `snake_case`, `CONST_CASE` (or `UPPER_CASE`), `kebab-case` or `Header-Case`; the strict forms reject two capitals in a row (`userID`) - `allowLeadingUnderscore`: whether leading underscores are ignored, e.g. in `_service`; `false` by default ```yaml version: "1.0" commands: lint: graphql: rules: fragment-naming: [warning, { convention: snake_case, allowLeadingUnderscore: true }] ``` ## Examples **Good**. ```graphql fragment UserFields on User { id } ``` **Bad**. The linter reports `Fragment name 'userFields' should be PascalCase, e.g. 'UserFields'`. ```graphql fragment userFields on User { id } ``` --- # input-field-description-defined Source: https://apigenie.pl/docs/linter/graphql/rules/input-field-description-defined A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that the fields of input object types have a description. ## Rule details Descriptions are part of the schema: introspection serves them to GraphiQL, IDEs, documentation generators and code generators. A missing or blank description is reported; type extensions have no descriptions and are not checked. The rule applies to definitions. An `# apigenie-lint-disable input-field-description-defined` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql input UserFilter { "Part of the name." name: String } ``` **Bad**. The linter reports `Input field 'UserFilter.name' should have a description`. ```graphql input UserFilter { name: String } ``` --- # input-field-naming Source: https://apigenie.pl/docs/linter/graphql/rules/input-field-naming A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that the input field names follow a naming convention, camelCase by default. ## Rule details Consistent names make a schema predictable for its clients: generated code, documentation and queries read the same everywhere. The rule reports a name that doesn't follow the convention, with the name converted to it as a suggestion. The rule applies to definitions. An `# apigenie-lint-disable input-field-naming` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block can be a string, the convention, or an object with the properties: - `convention`: `camelCase`, `camelCaseStrict`, `PascalCase`, `PascalCaseStrict`, `snake_case`, `CONST_CASE` (or `UPPER_CASE`), `kebab-case` or `Header-Case`; the strict forms reject two capitals in a row (`userID`) - `allowLeadingUnderscore`: whether leading underscores are ignored, e.g. in `_service`; `false` by default ```yaml version: "1.0" commands: lint: graphql: rules: input-field-naming: [warning, { convention: snake_case, allowLeadingUnderscore: true }] ``` ## Examples **Good**. ```graphql input UserFilter { firstName: String } ``` **Bad**. The linter reports `Input field name 'FirstName' should be camelCase, e.g. 'firstName'`. ```graphql input UserFilter { FirstName: String } ``` --- # input-fields-sorted Source: https://apigenie.pl/docs/linter/graphql/rules/input-fields-sorted A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error. This rule checks that the fields of each input object type definition and extension are in alphabetical order. ## Rule details Sorted definitions are easier to find and produce smaller diffs. Names are compared ignoring case; the first name out of order of each list is reported. Turn the rule off when the order of definitions is meaningful, for example the most important fields first. The rule applies to definitions. An `# apigenie-lint-disable input-fields-sorted` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql input UserFilter { kind: Kind, name: String } ``` **Bad**. The linter reports `Input field 'kind' should come before 'name'`. ```graphql input UserFilter { name: String, kind: Kind } ``` --- # input-no-circular-non-null Source: https://apigenie.pl/docs/linter/graphql/rules/input-no-circular-non-null A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that input object types don't reference themselves through non-null fields. ## Rule details No value can satisfy an input object type that requires itself, directly or through other input types, through non-null fields; the specification forbids it. Nullable and list fields break the cycle. The rule applies to definitions. An `# apigenie-lint-disable input-no-circular-non-null` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql input Filter { and: [Filter!], not: Filter } ``` **Bad**. The linter reports `Cannot reference Input Object "Filter" within itself through a series of non-null fields: "not".`. ```graphql input Filter { not: Filter! } ``` --- # input-output-types Source: https://apigenie.pl/docs/linter/graphql/rules/input-output-types A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that arguments and input fields have input types, and fields have output types, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to definitions. An `# apigenie-lint-disable input-output-types` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { users(filter: UserFilter): [User] } input UserFilter { name: String } type User { id: ID! } ``` **Bad**. The linter reports `The type of Query.users(filter:) must be Input Type but got: User.`. ```graphql type Query { users(filter: User): [User] } type User { id: ID! } ``` --- # input-type-suffix Source: https://apigenie.pl/docs/linter/graphql/rules/input-type-suffix A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that input object type names end with a suffix, `Input` by default. ## Rule details The suffix tells input types from the output types they often mirror, e.g. `User` and `UserInput`. Type extensions are not checked. The rule applies to definitions. An `# apigenie-lint-disable input-type-suffix` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block can be a string, the suffix, or an object with the `suffix` property. The suffix cannot be empty. ```yaml version: "1.0" commands: lint: graphql: rules: input-type-suffix: [warning, Params] ``` ## Examples **Good**. ```graphql input CreateUserInput { name: String } ``` **Bad**. The linter reports `Input object type 'CreateUser' should end with 'Input'`. ```graphql input CreateUser { name: String } ``` --- # interface-implementation Source: https://apigenie.pl/docs/linter/graphql/rules/interface-implementation A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that object and interface types implement their interfaces with all their fields, compatible field types and matching arguments, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to definitions. An `# apigenie-lint-disable interface-implementation` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql interface Node { id: ID! } type User implements Node { id: ID! } ``` **Bad**. The linter reports `Interface field Node.id expected but User does not provide it.`. ```graphql interface Node { id: ID! } type User implements Node { name: String } ``` --- # known-argument-names Source: https://apigenie.pl/docs/linter/graphql/rules/known-argument-names A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the arguments given to fields and directives are defined by them. ## Rule details Unknown arguments are rejected by the server. The arguments of `@skip`, `@include` and of the directives of the schema are checked. The rule checks operations against the schema files named by the `schema` property of the configuration, or against the type system of their own document. It reports nothing without a schema. The rule applies to operations and fragments. An `# apigenie-lint-disable known-argument-names` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query User { user(id: 1) { id } } ``` **Bad**. The linter reports `Unknown argument "userId" on field "Query.user".`. ```graphql query User { user(userId: 1) { id } } ``` --- # known-directive-locations Source: https://apigenie.pl/docs/linter/graphql/rules/known-directive-locations A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that directives are used at one of the locations of their definition, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to schemas and to operations. The built-in directives and those defined in the document are known; other directives are not checked. The rule applies to definitions. An `# apigenie-lint-disable known-directive-locations` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql directive @auth on FIELD_DEFINITION type Query { a: Int @auth } ``` **Bad**. The linter reports `Directive "@auth" may not be used on OBJECT.`. ```graphql directive @auth on FIELD_DEFINITION type Query @auth { a: Int } ``` --- # known-fragment-names Source: https://apigenie.pl/docs/linter/graphql/rules/known-fragment-names A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that fragment spreads name fragments of the document, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule reports references to types and fragments that are not in the document only when the configuration sets `self_contained: true`, since schemas and operations are often split across files. The rule applies to operations and fragments. An `# apigenie-lint-disable known-fragment-names` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Q { user { ...A } } fragment A on User { id } ``` **Bad**. The linter reports `Unknown fragment "A".`. ```graphql query Q { user { ...A } } ``` --- # known-types Source: https://apigenie.pl/docs/linter/graphql/rules/known-types A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the types referenced by type system definitions are built-in scalars or defined in the document, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule reports references to types and fragments that are not in the document only when the configuration sets `self_contained: true`, since schemas and operations are often split across files. The rule applies to definitions. An `# apigenie-lint-disable known-types` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { user: User } type User { id: ID! } ``` **Bad**. The linter reports `Unknown type "User".`. ```graphql type Query { user: User } ``` --- # lone-anonymous-operation Source: https://apigenie.pl/docs/linter/graphql/rules/lone-anonymous-operation A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that an anonymous operation is the only operation of the document, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to operations and fragments. An `# apigenie-lint-disable lone-anonymous-operation` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql { a } ``` **Bad**. The linter reports `This anonymous operation must be the only defined operation.`. ```graphql { a } query B { b } ``` --- # lone-executable-definition Source: https://apigenie.pl/docs/linter/graphql/rules/lone-executable-definition A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error. This rule checks that a document holds a single operation or fragment. ## Rule details One definition per file keeps files small, and lets tools map files to operations. The rule applies to operations and fragments. An `# apigenie-lint-disable lone-executable-definition` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block is an object with the `ignore` property: the kinds of definitions (`query`, `mutation`, `subscription`, `fragment`) that may be added to a document. ```yaml version: "1.0" commands: lint: graphql: rules: lone-executable-definition: [error, { ignore: [fragment] }] ``` ## Examples **Good**. ```graphql query Me { me { id } } ``` **Bad**. The linter reports `Operation 'Users' should be in a document of its own; a document should hold one operation or fragment`. ```graphql query Me { me { id } } query Users { users { id } } ``` --- # lone-schema-definition Source: https://apigenie.pl/docs/linter/graphql/rules/lone-schema-definition A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that a document has at most one schema definition, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to definitions. An `# apigenie-lint-disable lone-schema-definition` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql schema { query: Query } type Query { a: Int } ``` **Bad**. The linter reports `Must provide only one schema definition.`. ```graphql schema { query: Query } schema { query: Query } type Query { a: Int } ``` --- # match-document-filename Source: https://apigenie.pl/docs/linter/graphql/rules/match-document-filename A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error. This rule checks that the file name of a document with one operation or fragment is the name of the definition. ## Rule details Files named after their operation are easy to find. Documents with several definitions are not checked (see `lone-executable-definition`). The rule applies to operations and fragments. An `# apigenie-lint-disable match-document-filename` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block is an object with the properties: - `style`: the case of the file name, `camelCase`, `camelCaseStrict`, `PascalCase`, `PascalCaseStrict`, `snake_case`, `CONST_CASE` (or `UPPER_CASE`), `kebab-case` or `Header-Case`; the strict forms reject two capitals in a row (`userID`); the name as written by default - `fileExtension`: the extension the file must have, e.g. `.gql`; any by default ```yaml version: "1.0" commands: lint: graphql: rules: match-document-filename: [error, { style: kebab-case, fileExtension: .graphql }] ``` ## Examples **Good**. ```graphql # GetUser.graphql query GetUser { me { id } } ``` **Bad**. The linter reports `The file name 'user.graphql' should match the query 'GetUser', e.g. 'GetUser.graphql'`. ```graphql # user.graphql query GetUser { me { id } } ``` --- # mutation-input-argument Source: https://apigenie.pl/docs/linter/graphql/rules/mutation-input-argument A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that mutation fields take a single argument, `input`, of a non-null input object type. ## Rule details A single input object can evolve without breaking clients: fields are added to the input type rather than as new arguments of the mutation. Mutations without arguments are not reported. The rule applies to definitions. An `# apigenie-lint-disable mutation-input-argument` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block is an object with the properties: - `argumentName`: the name of the argument, `input` by default - `requireNonNull`: whether the argument must be non-null, `true` by default ```yaml version: "1.0" commands: lint: graphql: rules: mutation-input-argument: [error, { argumentName: data, requireNonNull: false }] ``` ## Examples **Good**. ```graphql type Mutation { createUser(input: CreateUserInput!): CreateUserPayload } input CreateUserInput { name: String } ``` **Bad**. The linter reports `Field 'Mutation.createUser' should take a single argument named 'input'`. ```graphql type Mutation { createUser(name: String, email: String): CreateUserPayload } ``` --- # mutation-payload-suffix Source: https://apigenie.pl/docs/linter/graphql/rules/mutation-payload-suffix A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that the result types of mutation fields end with a suffix, `Payload` by default. ## Rule details Payload types are specific to their mutation; the suffix tells them from the domain types they contain. Scalar and enum results are not reported (see `no-scalar-result-on-mutation`). The rule applies to definitions. An `# apigenie-lint-disable mutation-payload-suffix` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block can be a string, the suffix, or an object with the `suffix` property. ```yaml version: "1.0" commands: lint: graphql: rules: mutation-payload-suffix: [error, Result] ``` ## Examples **Good**. ```graphql type Mutation { createUser(input: CreateUserInput!): CreateUserPayload } ``` **Bad**. The linter reports `The result type 'User' of field 'Mutation.createUser' should end with 'Payload'`. ```graphql type Mutation { createUser(input: CreateUserInput!): User } ``` --- # no-deprecated Source: https://apigenie.pl/docs/linter/graphql/rules/no-deprecated A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that operations don't use deprecated fields, arguments and enum values. ## Rule details Deprecated elements will be removed from the schema; operations using them will break. The message includes the reason of the deprecation. The rule checks operations against the schema files named by the `schema` property of the configuration, or against the type system of their own document. It reports nothing without a schema. The rule applies to operations and fragments. An `# apigenie-lint-disable no-deprecated` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Me { me { name } } ``` **Bad**. The linter reports `The field 'User.login' is deprecated: Use name.`. ```graphql query Me { me { login } } ``` --- # no-deprecated-required-argument Source: https://apigenie.pl/docs/linter/graphql/rules/no-deprecated-required-argument A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that required arguments and input fields are not deprecated. ## Rule details Clients cannot stop sending a required argument (non-null and without a default value), so deprecating it has no effect; the specification forbids it. Make the argument optional, or give it a default value, before deprecating it. The rule applies to definitions. An `# apigenie-lint-disable no-deprecated-required-argument` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { users(limit: Int = 10 @deprecated(reason: "Use `first`.")): [User] } ``` **Bad**. The linter reports `Required argument 'Query.users(limit:)' cannot be deprecated; make it optional or give it a default value first`. ```graphql type Query { users(limit: Int! @deprecated(reason: "Use `first`.")): [User] } ``` --- # no-fragment-cycles Source: https://apigenie.pl/docs/linter/graphql/rules/no-fragment-cycles A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that fragments don't spread themselves, directly or indirectly, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to operations and fragments. An `# apigenie-lint-disable no-fragment-cycles` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql fragment A on User { id } ``` **Bad**. The linter reports `Cannot spread fragment "A" within itself via "B".`. ```graphql fragment A on User { ...B } fragment B on User { ...A } ``` --- # no-get-prefix-on-query-fields Source: https://apigenie.pl/docs/linter/graphql/rules/no-get-prefix-on-query-fields A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that the fields of the query root type are not named `getSomething`. ## Rule details Query fields are nouns: the operation type already says that they read data. `user(id:)` is the convention, `getUser(id:)` comes from RPC APIs. The rule applies to definitions. An `# apigenie-lint-disable no-get-prefix-on-query-fields` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { user(id: ID!): User } ``` **Bad**. The linter reports `Query field 'getUser' should not start with 'get', e.g. 'user'`. ```graphql type Query { getUser(id: ID!): User } ``` --- # no-hashtag-description Source: https://apigenie.pl/docs/linter/graphql/rules/no-hashtag-description A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that definitions are documented with descriptions rather than with `#` comments. ## Rule details Comments are dropped by GraphQL servers: introspection, GraphiQL and generated code never show them. The rule reports a `#` comment directly above a definition that can have a description and has none. Comments separated from the definition by a blank line, and `apigenie-lint-disable` comments, are not reported. The rule applies to definitions. An `# apigenie-lint-disable no-hashtag-description` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql "The users of the shop." type User { id: ID! } ``` **Bad**. The linter reports `Use a description instead of a comment to document object type 'User'`. ```graphql # The users of the shop. type User { id: ID! } ``` --- # no-mixed-definitions Source: https://apigenie.pl/docs/linter/graphql/rules/no-mixed-definitions A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that a document holds either a schema or operations, not both. ## Rule details Schemas and operations have different owners and lifecycles: schema files are served, operation files are compiled into clients. Each operation and fragment of a document with type system definitions is reported. The rule applies to definitions. An `# apigenie-lint-disable no-mixed-definitions` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { me: User } ``` **Bad**. The linter reports `Operation 'Me' should not be in a document with type system definitions`. ```graphql type Query { me: User } query Me { me { id } } ``` --- # no-one-place-fragments Source: https://apigenie.pl/docs/linter/graphql/rules/no-one-place-fragments A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error. This rule checks that fragments are spread more than once in the document. ## Rule details A fragment spread once adds indirection without reuse; its selections are better inlined. The rule applies to operations and fragments. An `# apigenie-lint-disable no-one-place-fragments` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Q { a: user(id: 1) { ...UserFields } b: user(id: 2) { ...UserFields } } fragment UserFields on User { id } ``` **Bad**. The linter reports `Fragment 'UserFields' is spread only once; inline its selections`. ```graphql query Q { me { ...UserFields } } fragment UserFields on User { id } ``` --- # no-root-type Source: https://apigenie.pl/docs/linter/graphql/rules/no-root-type A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error. This rule checks that the schema doesn't have the root operation types the configuration disallows. ## Rule details Some APIs are read-only, or don't support subscriptions. The rule reports the disallowed root operation types; with the default configuration it reports nothing. The rule applies to definitions. An `# apigenie-lint-disable no-root-type` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block is an object with the `disallow` property: a list of `mutation` and `subscription`. ```yaml version: "1.0" commands: lint: graphql: rules: no-root-type: [error, { disallow: [mutation, subscription] }] ``` ## Examples **Good**. ```graphql type Query { me: User } ``` **Bad**. With the options `{ disallow: [mutation] }`, the linter reports `The schema should not have a mutation root operation type ('Mutation')`. ```graphql type Query { me: User } type Mutation { logout: Boolean } ``` --- # no-scalar-result-on-mutation Source: https://apigenie.pl/docs/linter/graphql/rules/no-scalar-result-on-mutation A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that mutation fields return object types rather than scalars. ## Rule details A payload object can grow, e.g. with the changed objects or with errors, while a scalar result can only be replaced by a breaking change. The rule applies to definitions. An `# apigenie-lint-disable no-scalar-result-on-mutation` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Mutation { logout: LogoutPayload } type LogoutPayload { success: Boolean } ``` **Bad**. The linter reports `Field 'Mutation.logout' should return an object type rather than the scalar 'Boolean'`. ```graphql type Mutation { logout: Boolean } ``` --- # no-type-suffix Source: https://apigenie.pl/docs/linter/graphql/rules/no-type-suffix A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that type names don't end with a redundant suffix such as `Type` or `Enum`. ## Rule details The kind of a type is already part of its definition and of introspection; `UserType` or `KindEnum` only make names longer. By default the suffixes are `Type`, `Object`, `Interface`, `Union`, `Enum`, `Scalar` and `Input`; `Input` is allowed on input object types (see `input-type-suffix`). The rule applies to definitions. An `# apigenie-lint-disable no-type-suffix` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block is an object with the `suffixes` property, the list of suffixes that are reported. ```yaml version: "1.0" commands: lint: graphql: rules: no-type-suffix: [error, { suffixes: [Type, Model] }] ``` ## Examples **Good**. ```graphql type User { id: ID! } enum Kind { CAT } ``` **Bad**. The linter reports `Object type 'UserType' should not end with 'Type'`. ```graphql type UserType { id: ID! } ``` --- # no-typename-prefix Source: https://apigenie.pl/docs/linter/graphql/rules/no-typename-prefix A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that field names don't start with the name of their type, as in `User.userId`. ## Rule details The type already gives the context of a field: `user.id` reads better than `user.userId`. A field is reported when its name starts with the type name in camelCase followed by an upper-case letter, a digit or an underscore, so `User.users` is not reported. The rule applies to definitions. An `# apigenie-lint-disable no-typename-prefix` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type User { id: ID!, name: String } ``` **Bad**. The linter reports `Field 'userId' should not start with the name of its type 'User'`. ```graphql type User { userId: ID! } ``` --- # no-undefined-variables Source: https://apigenie.pl/docs/linter/graphql/rules/no-undefined-variables A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the variables used by an operation, including in the fragments it spreads, are defined by the operation, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to operations and fragments. An `# apigenie-lint-disable no-undefined-variables` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Q($id: ID!) { user(id: $id) { id } } ``` **Bad**. The linter reports `Variable "$id" is not defined by operation "Q".`. ```graphql query Q { user(id: $id) { id } } ``` --- # no-unused-fragments Source: https://apigenie.pl/docs/linter/graphql/rules/no-unused-fragments A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that every fragment is spread by an operation, directly or through other fragments, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule reports references to types and fragments that are not in the document only when the configuration sets `self_contained: true`, since schemas and operations are often split across files. The rule applies to operations and fragments. An `# apigenie-lint-disable no-unused-fragments` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Q { user { ...A } } fragment A on User { id } ``` **Bad**. The linter reports `Fragment "A" is never used.`. ```graphql query Q { user { id } } fragment A on User { id } ``` --- # no-unused-variables Source: https://apigenie.pl/docs/linter/graphql/rules/no-unused-variables A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the variables defined by an operation are used, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to operations and fragments. An `# apigenie-lint-disable no-unused-variables` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Q($id: ID!) { user(id: $id) { id } } ``` **Bad**. The linter reports `Variable "$id" is never used in operation "Q".`. ```graphql query Q($id: ID!) { me { id } } ``` --- # one-field-subscriptions Source: https://apigenie.pl/docs/linter/graphql/rules/one-field-subscriptions A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that subscriptions select a single root field, as the specification requires. ## Rule details A subscription maps one event stream to responses; selecting several root fields, or an introspection field, is invalid. Inline fragments and the fragments of the document are followed. The rule applies to operations and fragments. An `# apigenie-lint-disable one-field-subscriptions` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql subscription OnMessage { messageAdded { id } } ``` **Bad**. The linter reports `Subscription "OnEvents" must select only one top level field.`. ```graphql subscription OnEvents { messageAdded { id } userJoined { id } } ``` --- # oneof-fields-nullable Source: https://apigenie.pl/docs/linter/graphql/rules/oneof-fields-nullable A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the fields of `@oneOf` input object types are nullable and have no default value. ## Rule details Exactly one field of a `@oneOf` input object is given; a non-null field or a default value would make every value invalid, as the specification of `@oneOf` requires. The rule applies to definitions. An `# apigenie-lint-disable oneof-fields-nullable` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql input UserBy @oneOf { id: ID, email: String } ``` **Bad**. The linter reports `Input field 'UserBy.id' of the @oneOf input object type should be nullable`. ```graphql input UserBy @oneOf { id: ID!, email: String } ``` --- # operation-known-types Source: https://apigenie.pl/docs/linter/graphql/rules/operation-known-types A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the types of variables and the type conditions of fragments are types of the schema. ## Rule details Unknown types are rejected by the server. The rule checks operations against the schema files named by the `schema` property of the configuration, or against the type system of their own document. It reports nothing without a schema. The rule applies to operations and fragments. An `# apigenie-lint-disable operation-known-types` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Users($kind: Kind) { users(kind: $kind) { id } } ``` **Bad**. The linter reports `Unknown type "UserKind".`. ```graphql query Users($kind: UserKind) { users(kind: $kind) { id } } ``` --- # operation-name-defined Source: https://apigenie.pl/docs/linter/graphql/rules/operation-name-defined A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that operations have names. ## Rule details Names identify operations in server logs, metrics, persisted queries and developer tools. The rule applies to operations and fragments. An `# apigenie-lint-disable operation-name-defined` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Me { me { id } } ``` **Bad**. The linter reports `The query should have a name`. ```graphql { me { id } } ``` --- # operation-name-suffix Source: https://apigenie.pl/docs/linter/graphql/rules/operation-name-suffix A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that operation and fragment names don't end with a redundant suffix. ## Rule details The keyword already gives the kind of a definition: `query GetUserQuery` repeats it. The default suffixes are `Query`, `Mutation`, `Subscription` and `Fragment`. The rule applies to operations and fragments. An `# apigenie-lint-disable operation-name-suffix` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block is an object with the `suffixes` property, the list of suffixes that are reported. ```yaml version: "1.0" commands: lint: graphql: rules: operation-name-suffix: [error, { suffixes: [Query, Mutation] }] ``` ## Examples **Good**. ```graphql query GetUser { me { id } } ``` **Bad**. The linter reports `Operation 'GetUserQuery' should not end with 'Query'`. ```graphql query GetUserQuery { me { id } } ``` --- # operation-naming Source: https://apigenie.pl/docs/linter/graphql/rules/operation-naming A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that operation names follow a naming convention, PascalCase by default. ## Rule details Consistent names make a schema predictable for its clients: generated code, documentation and queries read the same everywhere. The rule reports a name that doesn't follow the convention, with the name converted to it as a suggestion. The rule applies to operations and fragments. An `# apigenie-lint-disable operation-naming` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block can be a string, the convention, or an object with the properties: - `convention`: `camelCase`, `camelCaseStrict`, `PascalCase`, `PascalCaseStrict`, `snake_case`, `CONST_CASE` (or `UPPER_CASE`), `kebab-case` or `Header-Case`; the strict forms reject two capitals in a row (`userID`) - `allowLeadingUnderscore`: whether leading underscores are ignored, e.g. in `_service`; `false` by default ```yaml version: "1.0" commands: lint: graphql: rules: operation-naming: [warning, { convention: snake_case, allowLeadingUnderscore: true }] ``` ## Examples **Good**. ```graphql query GetUser { me { id } } ``` **Bad**. The linter reports `Operation name 'get_user' should be PascalCase, e.g. 'GetUser'`. ```graphql query get_user { me { id } } ``` --- # possible-type-extensions Source: https://apigenie.pl/docs/linter/graphql/rules/possible-type-extensions A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that extended types have the same kind as their definition, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to definitions. An `# apigenie-lint-disable possible-type-extensions` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type User { id: ID! } extend type User { name: String } ``` **Bad**. The linter reports `Cannot extend non-object type "User".`. ```graphql scalar User extend type User { name: String } ``` --- # query-root-defined Source: https://apigenie.pl/docs/linter/graphql/rules/query-root-defined A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that the schema has a query root operation type. ## Rule details A schema must have a query root type. Without a schema definition, the type named `Query` is the query root type. Documents that hold only a part of a schema should not use this rule. Turn the rule off when the schema is split across files, and the query root type is in another file. The rule applies to definitions. An `# apigenie-lint-disable query-root-defined` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { me: User } type User { id: ID! } ``` **Bad**. The linter reports `The schema should have a query root operation type (type Query)`. ```graphql type User { id: ID! } ``` --- # relay-arguments Source: https://apigenie.pl/docs/linter/graphql/rules/relay-arguments A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error, Relay at error. This rule checks that fields returning connections take the pagination arguments of the Relay Cursor Connections specification. ## Rule details Forward pagination takes `first: Int` and `after` (String or a scalar), backward pagination `last: Int` and `before`. By default both pairs are required. The rule applies to definitions. An `# apigenie-lint-disable relay-arguments` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block is an object with the `includeBoth` property: whether both pairs of arguments are required (`true` by default) or one is enough. ```yaml version: "1.0" commands: lint: graphql: rules: relay-arguments: [error, { includeBoth: false }] ``` ## Examples **Good**. ```graphql type Query { users(first: Int, after: String, last: Int, before: String): UserConnection } interface Node { id: ID! } type User implements Node { id: ID! } type UserConnection { edges: [UserEdge], pageInfo: PageInfo! } type UserEdge { node: User, cursor: String! } type PageInfo { hasNextPage: Boolean! hasPreviousPage: Boolean! startCursor: String endCursor: String } ``` **Bad**. The linter reports `Field 'Query.users' returns a connection and should take the arguments first: Int, after: String, last: Int and before: String`. ```graphql type Query { users: UserConnection } ``` --- # relay-connection-types Source: https://apigenie.pl/docs/linter/graphql/rules/relay-connection-types A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error, Relay at error. This rule checks that connection types follow the Relay Cursor Connections specification. ## Rule details Types named `*Connection` are object types with an `edges` field returning a list of edge types and a `pageInfo: PageInfo!` field. Object types that have both fields are named `*Connection`. The rule applies to definitions. An `# apigenie-lint-disable relay-connection-types` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { users(first: Int, after: String, last: Int, before: String): UserConnection } interface Node { id: ID! } type User implements Node { id: ID! } type UserConnection { edges: [UserEdge], pageInfo: PageInfo! } type UserEdge { node: User, cursor: String! } type PageInfo { hasNextPage: Boolean! hasPreviousPage: Boolean! startCursor: String endCursor: String } ``` **Bad**. The linter reports `Connection type 'UserConnection' should have an 'edges' field returning a list of edges`. ```graphql type UserConnection { users: [User] } ``` --- # relay-edge-types Source: https://apigenie.pl/docs/linter/graphql/rules/relay-edge-types A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error, Relay at error. This rule checks that the edge types of connections follow the Relay Cursor Connections specification. ## Rule details The edge types returned by the `edges` field of connection types are object types with a `node` field that is not a list and a `cursor` field of type String or a scalar. The rule applies to definitions. An `# apigenie-lint-disable relay-edge-types` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block is an object with the boolean properties: - `withEdgeSuffix`: edge type names end with `Edge`; `true` by default - `shouldImplementNode`: the object types of nodes implement the `Node` interface; `true` by default - `listTypeCanWrapOnlyEdgeType`: the list fields of connection types return edge types; `false` by default ```yaml version: "1.0" commands: lint: graphql: rules: relay-edge-types: [error, { shouldImplementNode: false }] ``` ## Examples **Good**. ```graphql type Query { users(first: Int, after: String, last: Int, before: String): UserConnection } interface Node { id: ID! } type User implements Node { id: ID! } type UserConnection { edges: [UserEdge], pageInfo: PageInfo! } type UserEdge { node: User, cursor: String! } type PageInfo { hasNextPage: Boolean! hasPreviousPage: Boolean! startCursor: String endCursor: String } ``` **Bad**. The linter reports `Edge type 'UserEdge' should have a 'node' field that is not a list`. ```graphql type UserConnection { edges: [UserEdge], pageInfo: PageInfo! } type UserEdge { node: [User] } ``` --- # relay-page-info Source: https://apigenie.pl/docs/linter/graphql/rules/relay-page-info A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error, Relay at error. This rule checks that a schema with connections has a `PageInfo` type as the Relay Cursor Connections specification defines it. ## Rule details `PageInfo` is an object type with the fields `hasNextPage: Boolean!`, `hasPreviousPage: Boolean!`, and the nullable `startCursor` and `endCursor` of type String or a scalar. The rule applies to definitions. An `# apigenie-lint-disable relay-page-info` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { users(first: Int, after: String, last: Int, before: String): UserConnection } interface Node { id: ID! } type User implements Node { id: ID! } type UserConnection { edges: [UserEdge], pageInfo: PageInfo! } type UserEdge { node: User, cursor: String! } type PageInfo { hasNextPage: Boolean! hasPreviousPage: Boolean! startCursor: String endCursor: String } ``` **Bad**. The linter reports `PageInfo should have a field 'hasNextPage: Boolean!'`. ```graphql type UserConnection { edges: [UserEdge], pageInfo: PageInfo! } type PageInfo { hasNextPage: Boolean } ``` --- # require-selections Source: https://apigenie.pl/docs/linter/graphql/rules/require-selections A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that selections of objects with an identifier select it. ## Rule details Clients such as Apollo Client and Relay cache and update objects by their identifier; an object fetched without it cannot be normalized. The identifier may be selected directly, in inline fragments or in the fragments of the document. The rule checks operations against the schema files named by the `schema` property of the configuration, or against the type system of their own document. It reports nothing without a schema. The rule applies to operations and fragments. An `# apigenie-lint-disable require-selections` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block can be a string, the name of the identifier field, or an object with the `fieldName` property. The name is `id` by default. ```yaml version: "1.0" commands: lint: graphql: rules: require-selections: [error, uuid] ``` ## Examples **Good**. ```graphql query Me { me { id name } } ``` **Bad**. The linter reports `Field 'me' should select 'id', which identifies its type 'User'`. ```graphql query Me { me { name } } ``` --- # required-arguments-provided Source: https://apigenie.pl/docs/linter/graphql/rules/required-arguments-provided A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the required arguments of fields and directives are given. ## Rule details Arguments that are non-null and without default value are required; the server rejects operations that omit them. The rule checks operations against the schema files named by the `schema` property of the configuration, or against the type system of their own document. It reports nothing without a schema. The rule applies to operations and fragments. An `# apigenie-lint-disable required-arguments-provided` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query User { user(id: 1) { id } } ``` **Bad**. The linter reports `Field "user" argument "id" of type "ID!" is required, but it was not provided.`. ```graphql query User { user { id } } ``` --- # reserved-names Source: https://apigenie.pl/docs/linter/graphql/rules/reserved-names A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the names of types, fields, arguments, enum values and directives don't start with "__", as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to definitions. An `# apigenie-lint-disable reserved-names` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type User { id: ID! } ``` **Bad**. The linter reports `Name "__id" must not begin with "__", which is reserved by GraphQL introspection.`. ```graphql type User { __id: ID! } ``` --- # root-fields-nullable Source: https://apigenie.pl/docs/linter/graphql/rules/root-fields-nullable A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that the fields of the query and mutation root types are nullable. ## Rule details An error in a non-null field nulls its parent; for a root field, the parent is the whole `data` of the response. Nullable root fields keep the other fields of a response when one of them fails. The rule applies to definitions. An `# apigenie-lint-disable root-fields-nullable` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { user(id: ID!): User } ``` **Bad**. The linter reports `Field 'Query.user' of the query root type should be nullable, not 'User!'`. ```graphql type Query { user(id: ID!): User! } ``` --- # selection-set-depth Source: https://apigenie.pl/docs/linter/graphql/rules/selection-set-depth A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that selection sets are nested at most 7 levels deep. ## Rule details Deep queries are expensive to execute and often a sign of over-fetching. The fields of the fragments of the document are counted where they are spread; the root fields have the depth 1. The rule applies to operations and fragments. An `# apigenie-lint-disable selection-set-depth` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block is an object with the properties: - `maxDepth`: the maximum depth, from 1 to 1000, 7 by default - `ignore`: the names of fields whose selections are not counted, e.g. `edges` ```yaml version: "1.0" commands: lint: graphql: rules: selection-set-depth: [warning, { maxDepth: 10, ignore: [edges, node] }] ``` ## Examples **Good**. ```graphql query Me { me { friends { name } } } ``` **Bad**. The linter reports `Field 'name' of operation 'Me' is nested deeper than the maximum depth of 7`. ```graphql query Me { me { friends { friends { friends { friends { friends { friends { name } } } } } } } } ``` --- # selections-sorted Source: https://apigenie.pl/docs/linter/graphql/rules/selections-sorted A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error. This rule checks that the fields of each selection set of operations and fragments are in alphabetical order. ## Rule details Sorted definitions are easier to find and produce smaller diffs. Names are compared ignoring case; the first name out of order of each list is reported. Turn the rule off when the order of definitions is meaningful, for example the most important fields first. The rule applies to operations and fragments. An `# apigenie-lint-disable selections-sorted` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Me { me { id name } } ``` **Bad**. The linter reports `Field 'id' should come before 'name'`. ```graphql query Me { me { name id } } ``` --- # spell-check Source: https://apigenie.pl/docs/linter/graphql/rules/spell-check A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at warning, All at warning. This rule checks the spelling of descriptions and comments. ## Rule details Descriptions are the documentation of a schema. The rule checks them, as Markdown, and the comments of the definitions that can have descriptions, with a built-in English dictionary. Code in backticks, identifiers and URLs are skipped. The rule applies to definitions. An `# apigenie-lint-disable spell-check` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block is an object with the properties: - `dictionary` and `affix`: the paths of Hunspell dictionary and affix files that replace the built-in dictionary; they must be given together - `words`: extra words, e.g. product names - `suggestions`: the maximum number of suggestions, from 0 to 10, 3 by default ```yaml version: "1.0" commands: lint: graphql: rules: spell-check: [warning, { words: [Acme], suggestions: 1 }] ``` ## Examples **Good**. ```graphql "The users of the service." type User { id: ID! } ``` **Bad**. The linter reports `Misspelled word 'sevrice' in description (did you mean 'service'?)`. ```graphql "The users of the sevrice." type User { id: ID! } ``` --- # strict-id-in-types Source: https://apigenie.pl/docs/linter/graphql/rules/strict-id-in-types A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that object types have exactly one non-null identifier field, `id: ID!` by default. ## Rule details Clients such as Apollo Client and Relay cache objects by their identifier. Root operation types are not checked; payload and connection types usually need exceptions. The rule applies to definitions. An `# apigenie-lint-disable strict-id-in-types` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block is an object with the properties: - `acceptedIdNames`: the names of identifier fields, `[id]` by default - `acceptedIdTypes`: the types of identifier fields, `[ID]` by default - `exceptions`: an object with `types`, the names of types that are not checked, and `suffixes`, the suffixes of the names of types that are not checked ```yaml version: "1.0" commands: lint: graphql: rules: strict-id-in-types: [error, { exceptions: { suffixes: [Payload, Connection, Edge] } }] ``` ## Examples **Good**. ```graphql type User { id: ID!, name: String } ``` **Bad**. The linter reports `Object type 'User' should have exactly one non-null field named 'id' of type 'ID'`. ```graphql type User { name: String } ``` --- # type-description-defined Source: https://apigenie.pl/docs/linter/graphql/rules/type-description-defined A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that type definitions have a description. ## Rule details Descriptions are part of the schema: introspection serves them to GraphiQL, IDEs, documentation generators and code generators. A missing or blank description is reported; type extensions have no descriptions and are not checked. The rule applies to definitions. An `# apigenie-lint-disable type-description-defined` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql "A user of the shop." type User { id: ID! } ``` **Bad**. The linter reports `Object type 'User' should have a description`. ```graphql type User { id: ID! } ``` --- # type-naming Source: https://apigenie.pl/docs/linter/graphql/rules/type-naming A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks that type names follow a naming convention, PascalCase by default. ## Rule details Consistent names make a schema predictable for its clients: generated code, documentation and queries read the same everywhere. The rule reports a name that doesn't follow the convention, with the name converted to it as a suggestion. The rule applies to definitions. An `# apigenie-lint-disable type-naming` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Configuration The configuration block can be a string, the convention, or an object with the properties: - `convention`: `camelCase`, `camelCaseStrict`, `PascalCase`, `PascalCaseStrict`, `snake_case`, `CONST_CASE` (or `UPPER_CASE`), `kebab-case` or `Header-Case`; the strict forms reject two capitals in a row (`userID`) - `allowLeadingUnderscore`: whether leading underscores are ignored, e.g. in `_service`; `false` by default ```yaml version: "1.0" commands: lint: graphql: rules: type-naming: [warning, { convention: snake_case, allowLeadingUnderscore: true }] ``` ## Examples **Good**. ```graphql type UserProfile { id: ID! } ``` **Bad**. The linter reports `Type name 'user_profile' should be PascalCase, e.g. 'UserProfile'`. ```graphql type user_profile { id: ID! } ``` --- # types-sorted Source: https://apigenie.pl/docs/linter/graphql/rules/types-sorted A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error. This rule checks that the type definitions of a document, and its directive definitions are in alphabetical order. ## Rule details Sorted definitions are easier to find and produce smaller diffs. Names are compared ignoring case; the first name out of order of each list is reported. Turn the rule off when the order of definitions is meaningful, for example the most important fields first. The rule applies to definitions. An `# apigenie-lint-disable types-sorted` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { me: User } type User { id: ID! } ``` **Bad**. The linter reports `Type 'Query' should come before 'User'`. ```graphql type User { id: ID! } type Query { me: User } ``` --- # unique-argument-definition-names Source: https://apigenie.pl/docs/linter/graphql/rules/unique-argument-definition-names A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the argument names of a field or directive definition are unique, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to definitions. An `# apigenie-lint-disable unique-argument-definition-names` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { users(first: Int, after: String): [User] } ``` **Bad**. The linter reports `Argument "Query.users(first:)" can only be defined once.`. ```graphql type Query { users(first: Int, first: String): [User] } ``` --- # unique-argument-names Source: https://apigenie.pl/docs/linter/graphql/rules/unique-argument-names A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the argument names of a field or directive are unique, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to operations and fragments. An `# apigenie-lint-disable unique-argument-names` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Q { users(first: 1, after: "a") { id } } ``` **Bad**. The linter reports `There can be only one argument named "first".`. ```graphql query Q { users(first: 1, first: 2) { id } } ``` --- # unique-directive-names Source: https://apigenie.pl/docs/linter/graphql/rules/unique-directive-names A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that directive names are unique, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to definitions. An `# apigenie-lint-disable unique-directive-names` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql directive @auth on FIELD_DEFINITION ``` **Bad**. The linter reports `There can be only one directive named "@auth".`. ```graphql directive @auth on FIELD_DEFINITION directive @auth on OBJECT ``` --- # unique-directives-per-location Source: https://apigenie.pl/docs/linter/graphql/rules/unique-directives-per-location A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that non-repeatable directives are used once per location, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to schemas and to operations. The built-in directives and those defined in the document are known; other directives are not checked. The rule applies to definitions. An `# apigenie-lint-disable unique-directives-per-location` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { a: Int @deprecated } ``` **Bad**. The linter reports `The directive "@deprecated" can only be used once at this location.`. ```graphql type Query { a: Int @deprecated @deprecated } ``` --- # unique-enum-value-names Source: https://apigenie.pl/docs/linter/graphql/rules/unique-enum-value-names A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the values of an enum are unique across the enum and its extensions, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to definitions. An `# apigenie-lint-disable unique-enum-value-names` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql enum Kind { CAT } extend enum Kind { DOG } ``` **Bad**. The linter reports `Enum value "Kind.CAT" can only be defined once.`. ```graphql enum Kind { CAT } extend enum Kind { CAT } ``` --- # unique-field-definition-names Source: https://apigenie.pl/docs/linter/graphql/rules/unique-field-definition-names A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the field names of a type are unique across the type and its extensions, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to definitions. An `# apigenie-lint-disable unique-field-definition-names` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type User { id: ID! } extend type User { name: String } ``` **Bad**. The linter reports `Field "User.id" can only be defined once.`. ```graphql type User { id: ID! } extend type User { id: ID } ``` --- # unique-fragment-names Source: https://apigenie.pl/docs/linter/graphql/rules/unique-fragment-names A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that fragment names are unique, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to operations and fragments. An `# apigenie-lint-disable unique-fragment-names` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Q { user { ...A ...B } } fragment A on User { id } fragment B on User { name } ``` **Bad**. The linter reports `There can be only one fragment named "A".`. ```graphql query Q { user { ...A } } fragment A on User { id } fragment A on User { name } ``` --- # unique-input-field-names Source: https://apigenie.pl/docs/linter/graphql/rules/unique-input-field-names A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the field names of an object value are unique, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to operations and fragments. An `# apigenie-lint-disable unique-input-field-names` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Q { users(filter: { name: "a", kind: ADMIN }) { id } } ``` **Bad**. The linter reports `There can be only one input field named "name".`. ```graphql query Q { users(filter: { name: "a", name: "b" }) { id } } ``` --- # unique-operation-names Source: https://apigenie.pl/docs/linter/graphql/rules/unique-operation-names A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that operation names are unique, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to operations and fragments. An `# apigenie-lint-disable unique-operation-names` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query A { a } query B { b } ``` **Bad**. The linter reports `There can be only one operation named "A".`. ```graphql query A { a } query A { b } ``` --- # unique-operation-types Source: https://apigenie.pl/docs/linter/graphql/rules/unique-operation-types A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that each root operation type is defined once across the schema definition and its extensions, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to definitions. An `# apigenie-lint-disable unique-operation-types` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql schema { query: Query } extend schema { mutation: Mutation } ``` **Bad**. The linter reports `There can be only one query type in schema.`. ```graphql schema { query: Query } extend schema { query: Other } ``` --- # unique-type-names Source: https://apigenie.pl/docs/linter/graphql/rules/unique-type-names A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that type names are unique, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to definitions. An `# apigenie-lint-disable unique-type-names` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type User { id: ID! } extend type User { name: String } ``` **Bad**. The linter reports `There can be only one type named "User".`. ```graphql type User { id: ID! } type User { name: String } ``` --- # unique-variable-names Source: https://apigenie.pl/docs/linter/graphql/rules/unique-variable-names A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks that the variable names of an operation are unique, as the GraphQL specification requires. ## Rule details The rule reports the issues of the validation rule of the same name, with the messages of graphql-js. A document that breaks it is rejected by GraphQL servers and tools, so the rule should stay enabled with the `error` severity. The rule applies to operations and fragments. An `# apigenie-lint-disable unique-variable-names` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Q($a: Int, $b: Int) { f(a: $a, b: $b) } ``` **Bad**. The linter reports `There can be only one variable named "$a".`. ```graphql query Q($a: Int, $a: Int) { f(a: $a) } ``` --- # unreachable-types Source: https://apigenie.pl/docs/linter/graphql/rules/unreachable-types A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that every type is reachable from the root operation types. ## Rule details A type that no field, argument or union reaches is dead code: clients cannot use it. Types are reached through the fields, arguments, input fields, union members and interfaces of reached types, the implementations of reached interfaces, and the arguments of directive definitions. Documents without root operation types are not checked. Turn the rule off when the schema is split across files. The rule applies to definitions. An `# apigenie-lint-disable unreachable-types` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql type Query { user: User } type User { id: ID! } ``` **Bad**. The linter reports `Object type 'Orphan' is not reachable from the root operation types`. ```graphql type Query { user: User } type User { id: ID! } type Orphan { id: ID! } ``` --- # unused-directive-definition Source: https://apigenie.pl/docs/linter/graphql/rules/unused-directive-definition A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks that the directives defined for schemas are applied in the document. ## Rule details An unused directive definition is dead code. Directives with executable locations (e.g. `FIELD`) are meant for operations and are not reported. Turn the rule off when the directives are defined in a file and applied in others. The rule applies to definitions. An `# apigenie-lint-disable unused-directive-definition` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql directive @auth on FIELD_DEFINITION type Query { me: User @auth } ``` **Bad**. The linter reports `Directive '@auth' is defined but never applied`. ```graphql directive @auth on FIELD_DEFINITION type Query { me: User } ``` --- # variables-sorted Source: https://apigenie.pl/docs/linter/graphql/rules/variables-sorted A rule of the GraphQL linter, which reads GraphQL schemas and operations. Since 0.9.0. In the rulesets: All at error. This rule checks that the variable definitions of each operation are in alphabetical order. ## Rule details Sorted definitions are easier to find and produce smaller diffs. Names are compared ignoring case; the first name out of order of each list is reported. Turn the rule off when the order of definitions is meaningful, for example the most important fields first. The rule applies to operations and fragments. An `# apigenie-lint-disable variables-sorted` comment on a node turns it off for the node and everything nested in it; at the top of the file, separated from the first definition by a blank line, the comment turns it off for the whole file. ## Examples **Good**. ```graphql query Users($first: Int, $kind: Kind) { users(first: $first, kind: $kind) { id } } ``` **Bad**. The linter reports `Variable 'first' should come before 'kind'`. ```graphql query Users($kind: Kind, $first: Int) { users(first: $first, kind: $kind) { id } } ``` --- # directory-same-package Source: https://apigenie.pl/docs/linter/protobuf/rules/directory-same-package A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether all the `.proto` files of a directory declare the same package. ## Rule details Many code generators, for example the Go one, turn a directory into a single package of the generated code. Files of different Protobuf packages in one directory then produce code that does not compile, and they make the layout of the API harder to follow. The `directory-same-package` rule compares the package of the linted file with the packages of the other `.proto` files in the same directory (subdirectories are not included). If any of them declares another package, or no package while the linted file has one (or the other way round), the rule reports: `Other files of the directory declare other packages: <files>` where `<files>` lists each such file as `'<package>' (<file name>)`, or as `no package (<file name>)` when the file has no package. The issue is reported at the package declaration, or at the syntax statement of a file without a package. Files of the directory that cannot be read, for example because of syntax errors, or because they are proto2 or editions files, are ignored. The rule reads the other `.proto` files in the directory of the linted file. Turn the rule off if your build tools and code generators do not map directories to packages, and you deliberately keep several packages in one directory. ## Examples **Good**. The directory `acme/pets/v1` contains `pet.proto`: ```proto syntax = "proto3"; package acme.pets.v1; message Pet { string name = 1; } ``` and `owner.proto`: ```proto syntax = "proto3"; package acme.pets.v1; message Owner { string name = 1; } ``` **Bad**. The directory `acme/pets/v1` contains the same `pet.proto` as above, and this `owner.proto`: ```proto syntax = "proto3"; package acme.owners.v1; message Owner { string name = 1; } ``` The linter reports `Other files of the directory declare other packages: 'acme.owners.v1' (owner.proto)` in `pet.proto`, and `Other files of the directory declare other packages: 'acme.pets.v1' (pet.proto)` in `owner.proto`. --- # enum-comment-defined Source: https://apigenie.pl/docs/linter/protobuf/rules/enum-comment-defined A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks whether every enum of a Protobuf file has a leading comment. ## Rule details Comments are the documentation of a Protobuf API: `protoc` passes them to the code generators, which copy them to the generated code, and documentation generators render them. The `enum-comment-defined` rule checks every enum, including enums nested in messages, and reports `Enum '<name>' has no leading comment` when there is no leading comment, or when it contains only whitespace. A leading comment is the comment right before the declaration, as `protoc` attaches it: a comment separated from the declaration by a blank line is a detached comment, and a comment after the declaration on the same line is a trailing comment; neither counts. Both `//` and `/* */` comments count. The rule is part of the `strict` and `all` rulesets. Turn the rule off if the enums of your files are documented elsewhere, or if their names are descriptive enough. Lines with an `apigenie-lint-disable` directive do not count as documentation: a leading comment made only of directives does not satisfy the rule. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; // The species of a pet. enum PetKind { PET_KIND_UNSPECIFIED = 0; PET_KIND_DOG = 1; } ``` **Bad**. The linter reports `Enum 'PetKind' has no leading comment`. ```proto syntax = "proto3"; package acme.pets.v1; enum PetKind { PET_KIND_UNSPECIFIED = 0; PET_KIND_DOG = 1; } ``` --- # enum-naming Source: https://apigenie.pl/docs/linter/protobuf/rules/enum-naming A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the name of every enum of a Protobuf file is in `PascalCase`. ## Rule details PascalCase enum names match the type naming conventions of most target languages, and are what the Protobuf style guide recommends. The `enum-value-prefix` rule derives the expected prefix of the values from the enum name. The `enum-naming` rule checks every enum, including enums nested in messages, and reports `Enum name '<name>' should be PascalCase` for every name that is not in `PascalCase`. A name is in `PascalCase` when it starts with an upper-case letter and contains only letters and digits, such as `PetOwner` (acronyms such as `HTTPServer` are accepted). When the name converted to `PascalCase` differs from the original and is itself valid, the message ends with a suggestion, for example `, e.g. '<converted>'`. To convert a name, it is split into words at underscores and other separators, at lower-to-upper case changes and before the last capital of an acronym, and the words are capitalized and joined, so `pet_owner` becomes `PetOwner`. Turn the rule off if the names are part of an existing API that you cannot rename. To allow a single enum, add an `// apigenie-lint-disable enum-naming` comment to it. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; enum PetKind { PET_KIND_UNSPECIFIED = 0; PET_KIND_DOG = 1; } ``` **Bad**. The linter reports `Enum name 'pet_kind' should be PascalCase, e.g. 'PetKind'`. ```proto syntax = "proto3"; package acme.pets.v1; enum pet_kind { PET_KIND_UNSPECIFIED = 0; PET_KIND_DOG = 1; } ``` --- # enum-no-allow-alias Source: https://apigenie.pl/docs/linter/protobuf/rules/enum-no-allow-alias A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether any enum sets the `allow_alias` option. ## Rule details With `option allow_alias = true;`, several values of an enum can share a number. Only one of the names survives serialization, though: the JSON and text formats always write the first name of the number, so a client that sends one name may read back another. Aliases also make renaming values harder than it looks, since both names have to be kept in sync with every consumer. The `enum-no-allow-alias` rule reports `Enum '<enum>' should not allow aliases` at the `allow_alias` option of every enum that sets it to `true`. Turn the rule off while renaming enum values: an alias lets the old and the new name coexist until all clients have moved to the new one. To allow a single enum, add an `// apigenie-lint-disable enum-no-allow-alias` comment to the enum. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; enum PetKind { PET_KIND_UNSPECIFIED = 0; PET_KIND_DOG = 1; PET_KIND_CAT = 2; } ``` **Bad**. The linter reports `Enum 'PetKind' should not allow aliases`. ```proto syntax = "proto3"; package acme.pets.v1; enum PetKind { option allow_alias = true; PET_KIND_UNSPECIFIED = 0; PET_KIND_DOG = 1; PET_KIND_HOUND = 1; PET_KIND_CAT = 2; } ``` --- # enum-value-comment-defined Source: https://apigenie.pl/docs/linter/protobuf/rules/enum-value-comment-defined A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: All at error. This rule checks whether every enum value of a Protobuf file has a leading comment. ## Rule details Comments are the documentation of a Protobuf API: `protoc` passes them to the code generators, which copy them to the generated code, and documentation generators render them. The `enum-value-comment-defined` rule checks every enum value, and reports `Enum value '<name>' has no leading comment` when there is no leading comment, or when it contains only whitespace. A leading comment is the comment right before the declaration, as `protoc` attaches it: a comment separated from the declaration by a blank line is a detached comment, and a comment after the declaration on the same line is a trailing comment; neither counts. Both `//` and `/* */` comments count. The rule is only part of the `all` ruleset. Turn the rule off if the values of your files are documented elsewhere, or if their names are descriptive enough. To exempt the values of a single enum, add an `// apigenie-lint-disable enum-value-comment-defined` comment to the enum. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; // The species of a pet. enum PetKind { // The species is not known. PET_KIND_UNSPECIFIED = 0; // A dog. PET_KIND_DOG = 1; } ``` **Bad**. The linter reports `Enum value 'PET_KIND_DOG' has no leading comment`. ```proto syntax = "proto3"; package acme.pets.v1; // The species of a pet. enum PetKind { // The species is not known. PET_KIND_UNSPECIFIED = 0; PET_KIND_DOG = 1; } ``` --- # enum-value-naming Source: https://apigenie.pl/docs/linter/protobuf/rules/enum-value-naming A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the name of every enum value of a Protobuf file is in `UPPER_SNAKE_CASE`. ## Rule details Enum values are constants, and `UPPER_SNAKE_CASE` is how most target languages write constants. It is also what the Protobuf style guide recommends. The `enum-value-naming` rule checks every enum value, and reports `Enum value name '<name>' should be UPPER_SNAKE_CASE` for every name that is not in `UPPER_SNAKE_CASE`. A name is in `UPPER_SNAKE_CASE` when it starts with an upper-case letter and contains only upper-case letters, digits and single underscores, with no underscore at the end, such as `PET_KIND_DOG`. When the name converted to `UPPER_SNAKE_CASE` differs from the original and is itself valid, the message ends with a suggestion, for example `, e.g. '<converted>'`. To convert a name, it is split into words at underscores and other separators, at lower-to-upper case changes and before the last capital of an acronym, and the words are joined in upper case with underscores, so `petKindDog` becomes `PET_KIND_DOG`. Turn the rule off if the names are part of an existing API that you cannot rename. To allow a single enum value, add an `// apigenie-lint-disable enum-value-naming` comment to it. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; enum PetKind { PET_KIND_UNSPECIFIED = 0; PET_KIND_DOG = 1; } ``` **Bad**. The linter reports `Enum value name 'petKindDog' should be UPPER_SNAKE_CASE, e.g. 'PET_KIND_DOG'`. ```proto syntax = "proto3"; package acme.pets.v1; enum PetKind { PET_KIND_UNSPECIFIED = 0; petKindDog = 1; } ``` --- # enum-value-prefix Source: https://apigenie.pl/docs/linter/protobuf/rules/enum-value-prefix A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the names of the values of every enum start with the name of the enum in `UPPER_SNAKE_CASE`, for example `PET_KIND_DOG` in the enum `PetKind`. ## Rule details Protobuf enum values follow C++ scoping rules: they are siblings of their enum, not children of it. Two enums of the same package or message therefore cannot both have a value named `UNKNOWN` or `OTHER`. Prefixing every value with the name of its enum avoids such clashes, and keeps the values unambiguous in the generated code of languages without scoped enums. The `enum-value-prefix` rule converts the name of each enum to `UPPER_SNAKE_CASE` and appends an underscore, and reports `Enum value '<value>' should start with '<prefix>'` for every value whose name does not start with this prefix. The name is split into words at underscores, at lower-to-upper case changes and before the last capital of an acronym, so the prefix of `HTTPMethod` is `HTTP_METHOD_`. The prefix is made of the name of the enum only, also for enums nested in messages. Turn the rule off if the enum values are part of an existing API that you cannot rename. To allow the values of a single enum, add an `// apigenie-lint-disable enum-value-prefix` comment to the enum. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; enum PetKind { PET_KIND_UNSPECIFIED = 0; PET_KIND_DOG = 1; PET_KIND_CAT = 2; } ``` **Bad**. The linter reports `Enum value 'UNSPECIFIED' should start with 'PET_KIND_'`, `Enum value 'DOG' should start with 'PET_KIND_'` and `Enum value 'CAT' should start with 'PET_KIND_'`. ```proto syntax = "proto3"; package acme.pets.v1; enum PetKind { UNSPECIFIED = 0; DOG = 1; CAT = 2; } ``` --- # enum-zero-value-suffix Source: https://apigenie.pl/docs/linter/protobuf/rules/enum-zero-value-suffix A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the zero value of every enum ends with a suffix, `_UNSPECIFIED` by default. ## Rule details In proto3, the zero value is the default of every enum field: a field that was never set reads as zero. A name like `PET_KIND_UNSPECIFIED` makes it clear that the zero value means "not set", rather than a real value such as `PET_KIND_DOG` that clients would then receive by accident. The `enum-zero-value-suffix` rule checks every enum value whose number is `0`, and reports `Enum zero value '<value>' should end with '<suffix>'` when its name does not end with the suffix. When an enum allows aliases, every value numbered `0` is checked. Turn the rule off if the zero value of some enums is a meaningful value, for example in enums mirroring an external standard. To allow a single enum, add an `// apigenie-lint-disable enum-zero-value-suffix` comment to the enum. ## Configuration The configuration block can be a string or an object. If it is a string, its value is the suffix. If it is an object, it must contain only the `suffix` property, whose value is the suffix. The suffix cannot be empty. **Configuration example**. The following two examples are equivalent. They specify that the zero values must end with `_UNKNOWN`. ```yaml version: "1.0" commands: lint: protobuf: rules: enum-zero-value-suffix: [warning, _UNKNOWN] ``` ```yaml version: "1.0" commands: lint: protobuf: rules: enum-zero-value-suffix: - warning - suffix: _UNKNOWN ``` ## Examples **Good**. With the default configuration. ```proto syntax = "proto3"; package acme.pets.v1; enum PetKind { PET_KIND_UNSPECIFIED = 0; PET_KIND_DOG = 1; } ``` **Bad**. With the default configuration, the linter reports `Enum zero value 'PET_KIND_UNKNOWN' should end with '_UNSPECIFIED'`. ```proto syntax = "proto3"; package acme.pets.v1; enum PetKind { PET_KIND_UNKNOWN = 0; PET_KIND_DOG = 1; } ``` --- # field-comment-defined Source: https://apigenie.pl/docs/linter/protobuf/rules/field-comment-defined A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: All at error. This rule checks whether every field of a Protobuf file has a leading comment. ## Rule details Comments are the documentation of a Protobuf API: `protoc` passes them to the code generators, which copy them to the generated code, and documentation generators render them. The `field-comment-defined` rule checks every field, including the fields of oneofs, map fields and extension fields, and reports `Field '<name>' has no leading comment` when there is no leading comment, or when it contains only whitespace. A leading comment is the comment right before the declaration, as `protoc` attaches it: a comment separated from the declaration by a blank line is a detached comment, and a comment after the declaration on the same line is a trailing comment; neither counts. Both `//` and `/* */` comments count. The rule is only part of the `all` ruleset. Turn the rule off if the fields of your files are documented elsewhere, or if their names are descriptive enough. To exempt the fields of a single message, add an `// apigenie-lint-disable field-comment-defined` comment to the message. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; // A pet that lives in the shelter. message Pet { // The name the shelter gave to the pet. string name = 1; // Free-form labels, such as the color of the pet. map<string, string> labels = 2; } ``` **Bad**. The linter reports `Field 'labels' has no leading comment`. ```proto syntax = "proto3"; package acme.pets.v1; // A pet that lives in the shelter. message Pet { // The name the shelter gave to the pet. string name = 1; map<string, string> labels = 2; // Free-form labels. } ``` --- # field-naming Source: https://apigenie.pl/docs/linter/protobuf/rules/field-naming A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the name of every field of a Protobuf file is in `lower_snake_case`. ## Rule details Code generators derive the accessor names and the JSON names of fields from their Protobuf names, assuming `lower_snake_case`: `owner_name` becomes `ownerName` in JSON and `getOwnerName()` in Java. Other conventions produce surprising names, and can make the JSON names of two fields collide. The `field-naming` rule checks every field, including the fields of oneofs, map fields and extension fields, and reports `Field name '<name>' should be lower_snake_case` for every name that is not in `lower_snake_case`. A name is in `lower_snake_case` when it starts with a lower-case letter and contains only lower-case letters, digits and single underscores, with no underscore at the end, such as `owner_name` or `address_2`. When the name converted to `lower_snake_case` differs from the original and is itself valid, the message ends with a suggestion, for example `, e.g. '<converted>'`. To convert a name, it is split into words at underscores and other separators, at lower-to-upper case changes and before the last capital of an acronym, and the words are joined in lower case with underscores, so `ownerName` becomes `owner_name` and `HTTPServer` becomes `http_server`. Turn the rule off if the names are part of an existing API that you cannot rename. To allow a single field, add an `// apigenie-lint-disable field-naming` comment to it. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; message Pet { string owner_name = 1; map<string, string> labels = 2; } ``` **Bad**. The linter reports `Field name 'ownerName' should be lower_snake_case, e.g. 'owner_name'`. ```proto syntax = "proto3"; package acme.pets.v1; message Pet { string ownerName = 1; map<string, string> labels = 2; } ``` --- # file-naming Source: https://apigenie.pl/docs/linter/protobuf/rules/file-naming A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the name of every Protobuf file is in `lower_snake_case`, with the `.proto` extension. ## Rule details Code generators derive the names of the generated files, and sometimes of classes, from the names of the `.proto` files. `lower_snake_case` names such as `pet_owner.proto` are safe on every file system and in every target language, and are what the Protobuf style guide recommends. The `file-naming` rule checks the name of the linted file, without its directory. The name must end with `.proto`, and the part before the extension must start with a lower-case letter or a digit (as in `2fa.proto`), and contain only lower-case letters, digits and single underscores, with no underscore at the end. Otherwise the rule reports: `File name '<name>' should be lower_snake_case.proto` followed by a suggestion such as `, e.g. 'pet_store.proto'`. To build the suggestion, the part before the extension is split into words at underscores and other separators such as `-` and `.`, at lower-to-upper case changes and before the last capital of an acronym, and the words are joined in lower case with underscores. Files linted without a path are not checked. The rule uses the path of the linted file, but not its content. Turn the rule off if the file names are dictated by an existing project layout that you cannot change. ## Examples **Good**. The file `pet_store.proto`: ```proto syntax = "proto3"; package acme.pets.v1; message Pet { string name = 1; } ``` **Bad**. The same content in the file `PetStore.proto` makes the linter report `File name 'PetStore.proto' should be lower_snake_case.proto, e.g. 'pet_store.proto'`, and in the file `pet-store.proto`, `File name 'pet-store.proto' should be lower_snake_case.proto, e.g. 'pet_store.proto'`. ```proto syntax = "proto3"; package acme.pets.v1; message Pet { string name = 1; } ``` --- # import-no-cycle Source: https://apigenie.pl/docs/linter/protobuf/rules/import-no-cycle A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether Protobuf files import each other in a cycle. ## Rule details `protoc` rejects files that import themselves through a chain of imports, so such files cannot be compiled at all. For every import of the linted file, the `import-no-cycle` rule follows the imports of the imported file, and of the files it imports, looking for a path back to the linted file. If there is one, it reports: `Import '<import>' creates an import cycle: <file name> -> <import> -> ... -> <import>` A file that imports itself is reported with `Import '<import>' creates an import cycle: the file imports itself`. The cycle starts with the name of the linted file, followed by the imports that lead back to it, as they are written in the import statements. Every file of the cycle that is linted reports its own import. Imports that cannot be found are ignored (see `import-resolved`). Files linted without a path are not checked. The rule reads the imported files, found in the import paths and in the directories above the importing file. ## Examples **Good**. `acme/pets/v1/pet.proto` imports `acme/pets/v1/owner.proto`, which imports nothing from the package. ```proto syntax = "proto3"; package acme.pets.v1; import "acme/pets/v1/owner.proto"; message Pet { string name = 1; Owner owner = 2; } ``` **Bad**. The same `acme/pets/v1/pet.proto`, while `acme/pets/v1/owner.proto` imports it back: ```proto syntax = "proto3"; package acme.pets.v1; import "acme/pets/v1/pet.proto"; message Owner { string name = 1; repeated Pet pets = 2; } ``` The linter reports, in `pet.proto`: `Import 'acme/pets/v1/owner.proto' creates an import cycle: pet.proto -> acme/pets/v1/owner.proto -> acme/pets/v1/pet.proto` and in `owner.proto`: `Import 'acme/pets/v1/pet.proto' creates an import cycle: owner.proto -> acme/pets/v1/pet.proto -> acme/pets/v1/owner.proto` --- # import-no-public Source: https://apigenie.pl/docs/linter/protobuf/rules/import-no-public A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether a Protobuf file uses `import public`. ## Rule details A public import makes the declarations of the imported file visible to every file that imports the importing one. It is meant as a temporary measure when moving declarations between files, but it hides the real dependencies of the importers, and several code generators support it poorly or not at all. The `import-no-public` rule reports `Import '<import>' should not be public` for every `import public` statement. Turn the rule off while moving declarations from one file to another, when a public import keeps the existing importers working. To allow a single import, add an `// apigenie-lint-disable import-no-public` comment to it. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; import "google/protobuf/timestamp.proto"; message Pet { string name = 1; google.protobuf.Timestamp born_at = 2; } ``` **Bad**. The linter reports `Import 'google/protobuf/timestamp.proto' should not be public`. ```proto syntax = "proto3"; package acme.pets.v1; import public "google/protobuf/timestamp.proto"; message Pet { string name = 1; google.protobuf.Timestamp born_at = 2; } ``` --- # import-no-weak Source: https://apigenie.pl/docs/linter/protobuf/rules/import-no-weak A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether a Protobuf file uses `import weak`. ## Rule details A weak import lets a file compile when the imported file is not linked into the program. It is an undocumented feature, supported by few code generators, and its semantics differ between them. The `import-no-weak` rule reports `Import '<import>' should not be weak` for every `import weak` statement. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; import "google/protobuf/timestamp.proto"; message Pet { string name = 1; google.protobuf.Timestamp born_at = 2; } ``` **Bad**. The linter reports `Import 'google/protobuf/timestamp.proto' should not be weak`. ```proto syntax = "proto3"; package acme.pets.v1; import weak "google/protobuf/timestamp.proto"; message Pet { string name = 1; google.protobuf.Timestamp born_at = 2; } ``` --- # import-resolved Source: https://apigenie.pl/docs/linter/protobuf/rules/import-resolved A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether every file imported by a Protobuf file can be found. ## Rule details An import that cannot be found breaks the compilation of the file. It also keeps the linter from checking the rules that need the imported declarations: `import-used`, for example, stays silent for a file whose names it cannot resolve. The `import-resolved` rule looks up every import the way the linter does for all rules: 1. in the import paths, in order: first those given with `--proto-path`, then those of the `import_paths` key of the configuration (relative to the directory of the configuration file); 2. then in the directory of the importing file and in each directory above it, nearest first. The well-known files of the Protobuf distribution (`google/protobuf/timestamp.proto`, `google/protobuf/empty.proto` and the other files of `google/protobuf`) are known built in, so they are always found, even when they are not on the import paths. For every import that is not found, the rule reports: `Import '<import>' is not found in the import paths or the directories above the file` A file that is found but cannot be read, for example because of syntax errors, or because it is a proto2 or editions file, counts as found. To add an import path in the configuration: ```yaml version: "1.0" commands: lint: protobuf: import_paths: [proto, third_party/googleapis] ``` The rule looks for the imported files in the import paths and in the directories above the importing file. Turn the rule off when the imported files are generated or fetched during the build, and are not available where the linter runs. Consider adding their location to `import_paths` instead. ## Examples **Good**. The file `acme/pets/v1/pet.proto`, next to `acme/pets/v1/owner.proto`: ```proto syntax = "proto3"; package acme.pets.v1; import "acme/pets/v1/owner.proto"; import "google/protobuf/timestamp.proto"; message Pet { string name = 1; Owner owner = 2; google.protobuf.Timestamp born_at = 3; } ``` **Bad**. No `acme/pets/v1/kind.proto` exists in the import paths or in the directories above the file. The linter reports: `Import 'acme/pets/v1/kind.proto' is not found in the import paths or the directories above the file` ```proto syntax = "proto3"; package acme.pets.v1; import "acme/pets/v1/kind.proto"; message Pet { string name = 1; Kind kind = 2; } ``` --- # import-used Source: https://apigenie.pl/docs/linter/protobuf/rules/import-used A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. Fixed by `--fix`. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether every file imported by a Protobuf file is actually used. ## Rule details Unused imports add dependencies that are not needed: the generated code imports packages it does not use, which some languages reject, and the build has to fetch and compile more files. The `import-used` rule collects the names a file refers to: the types of fields and map values, the request and response types of RPCs, the extended types, the custom options used in option names (`(acme.options.v1.sensitive)`), and the extensions and `Any` types in option values. It resolves these names like `protoc` does, among the declarations of the file, of the files it imports and of the files those import publicly. An import is used when it declares one of these names, or when one of the files it imports publicly, directly or indirectly, does. For every import that is not used, the rule reports `Import '<import>' is unused`. The rule does not report: - public imports, which are there for the importers of the file rather than for the file itself; - imports that are not found (see `import-resolved`), and imports whose file, or one of the files it imports publicly, cannot be read, for example because of syntax errors, or because it is a proto2 or editions file (`google/protobuf/descriptor.proto` is known built in, though); - any import of a file in which some name cannot be resolved: the name may come from a file the linter cannot read, so it cannot tell which imports are unused. The rule reads the imported files, and the files they import publicly, found in the import paths and in the directories above the importing file. Turn the rule off if some imports are needed only for their side effects in the generated code, for example to register extensions. To keep a single import, add an `// apigenie-lint-disable import-used` comment to it. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; import "google/protobuf/timestamp.proto"; message Pet { string name = 1; google.protobuf.Timestamp born_at = 2; } ``` **Bad**. The linter reports `Import 'google/protobuf/duration.proto' is unused`. ```proto syntax = "proto3"; package acme.pets.v1; import "google/protobuf/duration.proto"; import "google/protobuf/timestamp.proto"; message Pet { string name = 1; google.protobuf.Timestamp born_at = 2; } ``` ## Automatic fixes `--fix` removes the unused import statements. --- # imports-sorted Source: https://apigenie.pl/docs/linter/protobuf/rules/imports-sorted A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. Fixed by `--fix`. In the rulesets: Strict at error, All at error. This rule checks whether the import statements of a Protobuf file are sorted by path. ## Rule details Sorted imports are easier to scan, make duplicates obvious, and keep merge conflicts small when several people add imports to the same file. The `imports-sorted` rule compares the paths of the import statements in the order they appear in the file, whatever their kind (plain, `public` or `weak`). At the first import whose path sorts before the path of the preceding one, it reports: `Imports are not sorted: '<import>' should come before '<previous import>'` Only the first import out of order is reported. Paths are compared character by character (by their byte values), so the comparison is case-sensitive: all upper-case letters sort before lower-case ones. The rule is part of the `strict` and `all` rulesets. Turn the rule off if you group the imports in another way, for example the imports of the file's own package first. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; import "acme/pets/v1/owner.proto"; import "google/protobuf/timestamp.proto"; message Pet { string name = 1; Owner owner = 2; google.protobuf.Timestamp born_at = 3; } ``` **Bad**. The linter reports `Imports are not sorted: 'acme/pets/v1/owner.proto' should come before 'google/protobuf/timestamp.proto'`. ```proto syntax = "proto3"; package acme.pets.v1; import "google/protobuf/timestamp.proto"; import "acme/pets/v1/owner.proto"; message Pet { string name = 1; Owner owner = 2; google.protobuf.Timestamp born_at = 3; } ``` ## Automatic fixes `--fix` sorts the import statements by path, keeping the kind (`public` or `weak`) of each import. Every import statement is replaced by the one that belongs at its place, so imports separated by other statements stay at the same places in the file. The fix is only offered when none of the import statements has a comment, neither before, after nor inside the statement, since moving the statements would separate the comments from them. Otherwise the issue is reported without a fix, and the imports must be sorted by hand. --- # message-comment-defined Source: https://apigenie.pl/docs/linter/protobuf/rules/message-comment-defined A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks whether every message of a Protobuf file has a leading comment. ## Rule details Comments are the documentation of a Protobuf API: `protoc` passes them to the code generators, which copy them to the generated code, and documentation generators render them. The `message-comment-defined` rule checks every message, including nested messages, and reports `Message '<name>' has no leading comment` when there is no leading comment, or when it contains only whitespace. A leading comment is the comment right before the declaration, as `protoc` attaches it: a comment separated from the declaration by a blank line is a detached comment, and a comment after the declaration on the same line is a trailing comment; neither counts. Both `//` and `/* */` comments count. The rule is part of the `strict` and `all` rulesets. Turn the rule off if the messages of your files are documented elsewhere, or if their names are descriptive enough. Lines with an `apigenie-lint-disable` directive do not count as documentation: a leading comment made only of directives does not satisfy the rule. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; // A pet that lives in the shelter. message Pet { string name = 1; } ``` **Bad**. The linter reports `Message 'Pet' has no leading comment`. ```proto syntax = "proto3"; package acme.pets.v1; message Pet { string name = 1; } ``` --- # message-naming Source: https://apigenie.pl/docs/linter/protobuf/rules/message-naming A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the name of every message of a Protobuf file is in `PascalCase`. ## Rule details PascalCase message names match the type naming conventions of most target languages, and are what the Protobuf style guide recommends. The `message-naming` rule checks every message, including nested messages, and reports `Message name '<name>' should be PascalCase` for every name that is not in `PascalCase`. A name is in `PascalCase` when it starts with an upper-case letter and contains only letters and digits, such as `PetOwner` (acronyms such as `HTTPServer` are accepted). When the name converted to `PascalCase` differs from the original and is itself valid, the message ends with a suggestion, for example `, e.g. '<converted>'`. To convert a name, it is split into words at underscores and other separators, at lower-to-upper case changes and before the last capital of an acronym, and the words are capitalized and joined, so `pet_owner` becomes `PetOwner`. Turn the rule off if the names are part of an existing API that you cannot rename. To allow a single message, add an `// apigenie-lint-disable message-naming` comment to it. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; message PetOwner { string name = 1; } ``` **Bad**. The linter reports `Message name 'pet_owner' should be PascalCase, e.g. 'PetOwner'`. ```proto syntax = "proto3"; package acme.pets.v1; message pet_owner { string name = 1; } ``` --- # oneof-comment-defined Source: https://apigenie.pl/docs/linter/protobuf/rules/oneof-comment-defined A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: All at error. This rule checks whether every oneof of a Protobuf file has a leading comment. ## Rule details Comments are the documentation of a Protobuf API: `protoc` passes them to the code generators, which copy them to the generated code, and documentation generators render them. The `oneof-comment-defined` rule checks every oneof, and reports `Oneof '<name>' has no leading comment` when there is no leading comment, or when it contains only whitespace. A leading comment is the comment right before the declaration, as `protoc` attaches it: a comment separated from the declaration by a blank line is a detached comment, and a comment after the declaration on the same line is a trailing comment; neither counts. Both `//` and `/* */` comments count. The rule is only part of the `all` ruleset. Turn the rule off if the oneofs of your files are documented elsewhere, or if their names are descriptive enough. To exempt the oneofs of a single message, add an `// apigenie-lint-disable oneof-comment-defined` comment to the message. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; // A pet that lives in the shelter. message Pet { string name = 1; // How the shelter can reach the owner. oneof contact { string email = 2; string phone = 3; } } ``` **Bad**. The linter reports `Oneof 'contact' has no leading comment`. ```proto syntax = "proto3"; package acme.pets.v1; // A pet that lives in the shelter. message Pet { string name = 1; oneof contact { string email = 2; string phone = 3; } } ``` --- # oneof-naming Source: https://apigenie.pl/docs/linter/protobuf/rules/oneof-naming A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the name of every oneof of a Protobuf file is in `lower_snake_case`. ## Rule details Code generators derive the names of the accessors and case enums of oneofs from their Protobuf names, assuming `lower_snake_case`, like for fields. The `oneof-naming` rule checks every oneof, and reports `Oneof name '<name>' should be lower_snake_case` for every name that is not in `lower_snake_case`. A name is in `lower_snake_case` when it starts with a lower-case letter and contains only lower-case letters, digits and single underscores, with no underscore at the end, such as `owner_name` or `address_2`. When the name converted to `lower_snake_case` differs from the original and is itself valid, the message ends with a suggestion, for example `, e.g. '<converted>'`. To convert a name, it is split into words at underscores and other separators, at lower-to-upper case changes and before the last capital of an acronym, and the words are joined in lower case with underscores, so `ownerName` becomes `owner_name` and `HTTPServer` becomes `http_server`. Turn the rule off if the names are part of an existing API that you cannot rename. To allow a single oneof, add an `// apigenie-lint-disable oneof-naming` comment to it. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; message Pet { string name = 1; oneof owner_contact { string email = 2; string phone = 3; } } ``` **Bad**. The linter reports `Oneof name 'ownerContact' should be lower_snake_case, e.g. 'owner_contact'`. ```proto syntax = "proto3"; package acme.pets.v1; message Pet { string name = 1; oneof ownerContact { string email = 2; string phone = 3; } } ``` --- # package-defined Source: https://apigenie.pl/docs/linter/protobuf/rules/package-defined A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether every Protobuf file declares a package. ## Rule details Without a `package` declaration, the messages, enums and services of a file live in the global namespace, where they can clash with the declarations of any other file. Most code generators also derive the names of the generated packages or namespaces from the Protobuf package. The `package-defined` rule reports `File has no package declaration` for every file without a `package` statement. The issue is reported at the syntax statement. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; message Pet { string name = 1; } ``` **Bad**. The linter reports `File has no package declaration`. ```proto syntax = "proto3"; message Pet { string name = 1; } ``` --- # package-directory-match Source: https://apigenie.pl/docs/linter/protobuf/rules/package-directory-match A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether every Protobuf file is in the directory that corresponds to its package, for example `acme/pets/v1` for the package `acme.pets.v1`. ## Rule details When the directories mirror the packages, the import path of a file tells where its declarations live, and the files of a package are easy to find. Many code generators and build tools expect this layout. The expected directory of a package is its name with the dots replaced by slashes. The `package-directory-match` rule compares it with the directory of the file in one of two ways: - If the file is inside one of the import paths (given with `--proto-path` or with the `import_paths` key of the configuration), the directory of the file relative to the first import path that contains it must be the expected directory. Otherwise the rule reports `Package '<package>' should be in directory '<expected>' of import path '<import path>', not in '<directory>'`, where `<directory>` is `.` for a file directly in the import path. The import path is shown as an absolute path. - Otherwise, the directory of the file must end with the expected directory. If it does not, the rule reports `Package '<package>' should be in a directory ending with '<expected>'`. Import paths in the configuration are relative to the directory of the configuration file: ```yaml version: "1.0" commands: lint: protobuf: import_paths: [proto] ``` Files without a package, and files linted without a path, are not checked. The rule uses the path of the linted file and the import paths, but does not read other files. Turn the rule off if your build places the files in directories that are unrelated to their packages, for example a flat directory of `.proto` files. ## Examples **Good**. The file `proto/acme/pets/v1/pet.proto`: ```proto syntax = "proto3"; package acme.pets.v1; message Pet { string name = 1; } ``` **Bad**. Without import paths, the file `proto/pets/v1/pet.proto` makes the linter report `Package 'acme.pets.v1' should be in a directory ending with 'acme/pets/v1'`. With the import path `proto`, and the project in `/work`, it reports `Package 'acme.pets.v1' should be in directory 'acme/pets/v1' of import path '/work/proto', not in 'pets/v1'`. ```proto syntax = "proto3"; package acme.pets.v1; message Pet { string name = 1; } ``` --- # package-naming Source: https://apigenie.pl/docs/linter/protobuf/rules/package-naming A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the package name of a Protobuf file consists of `lower_snake_case` components separated by dots. ## Rule details Package names such as `acme.pet_store.v1` map cleanly to directories and to the package and namespace names of the generated code in every language. The `package-naming` rule splits the package name at dots and checks that every component is `lower_snake_case`: it starts with a lower-case letter, and contains only lower-case letters, digits and single underscores, with no underscore at the end. If a component is not, the rule reports `Package name '<name>' should be lower_snake_case components separated by dots`, followed by a suggestion such as `, e.g. 'acme.pet_store.v1'` when converting the components gives a different name. To build the suggestion, each component is split into words at underscores and other separators, at lower-to-upper case changes and before the last capital of an acronym (so that `HTTPServer` becomes `http_server`), and the words are joined in lower case with underscores. Files without a package are not checked; see the `package-defined` rule. Turn the rule off if the package names are dictated by an existing API that you cannot rename. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pet_store.v1; message Pet { string name = 1; } ``` **Bad**. The linter reports `Package name 'Acme.PetStore.v1' should be lower_snake_case components separated by dots, e.g. 'acme.pet_store.v1'`. ```proto syntax = "proto3"; package Acme.PetStore.v1; message Pet { string name = 1; } ``` --- # package-no-import-cycle Source: https://apigenie.pl/docs/linter/protobuf/rules/package-no-import-cycle A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether packages import each other in a cycle. ## Rule details Even when no file imports itself through a chain of imports, two packages can depend on each other: a file of package A imports a file of package B, and another file of package B imports a file of package A. Code generators that turn Protobuf packages into packages of the target language, like the Go one, produce code with an import cycle that does not compile. The `package-no-import-cycle` rule builds the graph of the packages: package A imports package B when any file of A imports a file of B. For every import of the linted file that refers to a file of another package, it looks for a path in this graph from that package back to the package of the linted file. If there is one, it reports: `Import '<import>' creates a package import cycle: <package> -> ... -> <package>` The cycle starts and ends with the package of the linted file. Each imported package is reported once per file, at the first import that leads to it. The graph contains the files the linter knows about: the files being linted, the other `.proto` files in their directories, and the files these import, directly or indirectly. Imports that cannot be found are ignored. Files without a package are not checked, and are not part of the graph. The rule reads the imported files, found in the import paths and in the directories above the importing file, and the other files in the directories of the linted files. To accept an import that is part of a known cycle, add an `// apigenie-lint-disable package-no-import-cycle` comment to the import statement. ## Examples **Good**. `acme/pets/v1/pet.proto` imports a file of `acme.owners.v1`, which does not import anything from `acme.pets.v1`. ```proto syntax = "proto3"; package acme.pets.v1; import "acme/owners/v1/owner.proto"; message Pet { string name = 1; acme.owners.v1.Owner owner = 2; } ``` **Bad**. The same `acme/pets/v1/pet.proto`, while `acme/owners/v1/owner.proto` imports another file of `acme.pets.v1`: ```proto syntax = "proto3"; package acme.owners.v1; import "acme/pets/v1/kind.proto"; message Owner { string name = 1; repeated acme.pets.v1.Kind preferred_kinds = 2; } ``` No file imports itself, but when `pet.proto` is linted, the linter reports: `Import 'acme/owners/v1/owner.proto' creates a package import cycle: acme.pets.v1 -> acme.owners.v1 -> acme.pets.v1` --- # package-options-consistent Source: https://apigenie.pl/docs/linter/protobuf/rules/package-options-consistent A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at error, Strict at error, All at error. This rule checks whether the files of a package set the same language-specific file options, such as `go_package` and `java_package`. ## Rule details Options like `go_package`, `java_package` and `csharp_namespace` tell the code generators where to put the generated code. When the files of one Protobuf package disagree on them, the code of the package is scattered over several packages or namespaces of the target language, or does not compile at all. The `package-options-consistent` rule compares the options of the linted file with those of the other files of the same package. For every checked option whose value differs from that of another file, including when the option is set in one file only, it reports: `Option '<option>' differs between the files of package '<package>': <value> here, <value> in <file name>` where each value is the value in quotes, or `unset`. At most one issue is reported per option, for the first other file that differs. The issue is reported at the option statement, or at the package declaration when the linted file does not set the option. String values are compared after decoding their escapes; other values, such as `true`, as they are written. By default the rule checks these options: `csharp_namespace`, `go_package`, `java_multiple_files`, `java_package`, `objc_class_prefix`, `php_namespace`, `ruby_package` and `swift_prefix`. The other files of the package are those the linter knows about: the files being linted, the other `.proto` files in their directories, and the files these import, directly or indirectly. Files that cannot be read, for example because of syntax errors, or because they are proto2 or editions files, are ignored. Files without a package are not checked. The rule reads the other files of the package: the other files in the directories of the linted files, and the imported files, found in the import paths and in the directories above the importing file. If you do not generate code for some languages, restrict the list of options to those you use. ## Configuration The configuration block can be an array of option names, or an object with the `options` property, whose value is such an array. The list replaces the default list of options. **Configuration example**. The following two examples are equivalent. They specify that only `go_package` and `java_package` must be consistent. ```yaml version: "1.0" commands: lint: protobuf: rules: package-options-consistent: [error, [go_package, java_package]] ``` ```yaml version: "1.0" commands: lint: protobuf: rules: package-options-consistent: - error - options: [go_package, java_package] ``` ## Examples **Good**. The directory `acme/pets/v1` contains `pet.proto`: ```proto syntax = "proto3"; package acme.pets.v1; option go_package = "example.com/acme/pets/v1;petsv1"; message Pet { string name = 1; } ``` and `owner.proto`: ```proto syntax = "proto3"; package acme.pets.v1; option go_package = "example.com/acme/pets/v1;petsv1"; message Owner { string name = 1; } ``` **Bad**. The directory contains the same `pet.proto` as above, and this `owner.proto`: ```proto syntax = "proto3"; package acme.pets.v1; message Owner { string name = 1; } ``` The linter reports, in `pet.proto`: `Option 'go_package' differs between the files of package 'acme.pets.v1': 'example.com/acme/pets/v1;petsv1' here, unset in owner.proto` and in `owner.proto`: `Option 'go_package' differs between the files of package 'acme.pets.v1': unset here, 'example.com/acme/pets/v1;petsv1' in pet.proto` --- # package-same-directory Source: https://apigenie.pl/docs/linter/protobuf/rules/package-same-directory A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether all the files of a package are in the same directory. ## Rule details A package spread over several directories is hard to find, and code generators that map directories to packages of the generated code, like the Go one, split it into several packages that cannot see each other. The `package-same-directory` rule looks for other files that declare the same package as the linted file but are in another directory. If there are some, it reports: `Package '<package>' is also declared in other directories: <directories>` where `<directories>` lists each other directory once, as `'<directory>' (<file name>)` with the absolute path of the directory and the name of one of its files. The issue is reported at the package declaration. The rule can only compare the files the linter knows about: the files being linted, the other `.proto` files in their directories, and the files these import, directly or indirectly. A file of the package that none of them reaches is not seen. Files that cannot be read, for example because of syntax errors, or because they are proto2 or editions files, are ignored. Files without a package are not checked. The rule reads the other files of the package: the other files in the directories of the linted files, and the imported files, found in the import paths and in the directories above the importing file. Turn the rule off if your build tools and code generators do not map directories to packages, and you deliberately split large packages into several directories. ## Examples **Good**. The files of `acme.pets.v1` are all in `acme/pets/v1`. `acme/pets/v1/pet.proto`: ```proto syntax = "proto3"; package acme.pets.v1; import "acme/pets/v1/owner.proto"; message Pet { string name = 1; Owner owner = 2; } ``` and `acme/pets/v1/owner.proto`: ```proto syntax = "proto3"; package acme.pets.v1; message Owner { string name = 1; } ``` **Bad**. The same `pet.proto` imports `acme/pets/v1/owners/owner.proto`, which declares the same package in a subdirectory: ```proto syntax = "proto3"; package acme.pets.v1; import "acme/pets/v1/owners/owner.proto"; message Pet { string name = 1; Owner owner = 2; } ``` With the project in `/work`, the linter reports, in `pet.proto`: `Package 'acme.pets.v1' is also declared in other directories: '/work/acme/pets/v1/owners' (owner.proto)` --- # package-version-suffix Source: https://apigenie.pl/docs/linter/protobuf/rules/package-version-suffix A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Strict at error, All at error. This rule checks whether the last component of the package name of a Protobuf file is a version, such as `v1` or `v1beta2`. ## Rule details Versioned packages let a new, incompatible version of an API live next to the old one: the messages and services of `acme.pets.v2` do not clash with those of `acme.pets.v1`, neither in the Protobuf namespace nor in the generated code. The `package-version-suffix` rule reports `Package '<name>' should end with a version component, e.g. v1 or v1beta1` when the last component of the package name is not a version. A version component is: - `v` followed by a major version that does not start with `0`: `v1`, `v2`, `v10`, - optionally followed by a stability, `alpha` or `beta`, itself optionally followed by a number: `v1alpha`, `v1beta2`, - optionally with a point release between the major version and the stability: `v1p1alpha`, `v1p2beta3`. A point release requires a stability, so `v1p1` is not a version, - or followed by `test` and any lowercase letters and digits: `v2test`, `v1testfoo`. These are the versions buf accepts. Components such as `v0`, `V1`, `version1`, `v1final` and `v1p1test` are not versions. Files without a package are not checked; see the `package-defined` rule. The rule is part of the `strict` and `all` rulesets. Turn the rule off if your APIs are versioned in another way, for example by the repository or the service name, or if the files are internal and never published. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1beta1; message Pet { string name = 1; } ``` **Bad**. The linter reports `Package 'acme.pets' should end with a version component, e.g. v1 or v1beta1`. ```proto syntax = "proto3"; package acme.pets; message Pet { string name = 1; } ``` --- # rpc-comment-defined Source: https://apigenie.pl/docs/linter/protobuf/rules/rpc-comment-defined A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether every RPC of a Protobuf file has a leading comment. ## Rule details Comments are the documentation of a Protobuf API: `protoc` passes them to the code generators, which copy them to the generated code, and documentation generators render them. The `rpc-comment-defined` rule checks every RPC of every service, and reports `RPC '<name>' has no leading comment` when there is no leading comment, or when it contains only whitespace. A leading comment is the comment right before the declaration, as `protoc` attaches it: a comment separated from the declaration by a blank line is a detached comment, and a comment after the declaration on the same line is a trailing comment; neither counts. Both `//` and `/* */` comments count. Turn the rule off if the RPCs of your files are documented elsewhere, or if their names are descriptive enough. To exempt the RPCs of a single service, add an `// apigenie-lint-disable rpc-comment-defined` comment to the service. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { // Returns the pet with the given name. rpc GetPet(GetPetRequest) returns (GetPetResponse); } message GetPetRequest { string name = 1; } message GetPetResponse { string name = 1; } ``` **Bad**. The linter reports `RPC 'GetPet' has no leading comment`. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc GetPet(GetPetRequest) returns (GetPetResponse); } message GetPetRequest { string name = 1; } message GetPetResponse { string name = 1; } ``` --- # rpc-naming Source: https://apigenie.pl/docs/linter/protobuf/rules/rpc-naming A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the name of every RPC of a Protobuf file is in `PascalCase`. ## Rule details RPC names become method names in the generated code and appear in the paths of gRPC requests (`/acme.pets.v1.PetService/GetPet`). PascalCase is what the Protobuf style guide recommends, and the `rpc-request-standard-name` and `rpc-response-standard-name` rules derive the names of the request and response types from them. The `rpc-naming` rule checks every RPC of every service, and reports `RPC name '<name>' should be PascalCase` for every name that is not in `PascalCase`. A name is in `PascalCase` when it starts with an upper-case letter and contains only letters and digits, such as `PetOwner` (acronyms such as `HTTPServer` are accepted). When the name converted to `PascalCase` differs from the original and is itself valid, the message ends with a suggestion, for example `, e.g. '<converted>'`. To convert a name, it is split into words at underscores and other separators, at lower-to-upper case changes and before the last capital of an acronym, and the words are capitalized and joined, so `pet_owner` becomes `PetOwner`. Turn the rule off if the names are part of an existing API that you cannot rename. To allow a single RPC, add an `// apigenie-lint-disable rpc-naming` comment to it. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc GetPet(GetPetRequest) returns (GetPetResponse); } message GetPetRequest { string name = 1; } message GetPetResponse { string name = 1; } ``` **Bad**. The linter reports `RPC name 'get_pet' should be PascalCase, e.g. 'GetPet'`. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc get_pet(GetPetRequest) returns (GetPetResponse); } message GetPetRequest { string name = 1; } message GetPetResponse { string name = 1; } ``` --- # rpc-no-client-streaming Source: https://apigenie.pl/docs/linter/protobuf/rules/rpc-no-client-streaming A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: All at error. This rule checks whether any RPC uses client streaming. ## Rule details Client-streaming RPCs, whose request is declared with `stream`, are not supported by every transport: gRPC-Web and most HTTP/JSON gateways, for example, cannot carry them. They are also harder to retry, load-balance and debug than unary RPCs. The `rpc-no-client-streaming` rule reports `RPC '<rpc>' should not use client streaming` for every RPC with a streamed request, including bidirectional streaming RPCs. The rule is only part of the `all` ruleset. Turn the rule off if all clients use a transport that supports streaming, such as gRPC over HTTP/2. To allow a single RPC, add an `// apigenie-lint-disable rpc-no-client-streaming` comment to it. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc UploadPhoto(UploadPhotoRequest) returns (UploadPhotoResponse); } message UploadPhotoRequest { bytes photo = 1; } message UploadPhotoResponse { string url = 1; } ``` **Bad**. The linter reports `RPC 'UploadPhotos' should not use client streaming`. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc UploadPhotos(stream UploadPhotosRequest) returns (UploadPhotosResponse); } message UploadPhotosRequest { bytes photo = 1; } message UploadPhotosResponse { repeated string urls = 1; } ``` --- # rpc-no-server-streaming Source: https://apigenie.pl/docs/linter/protobuf/rules/rpc-no-server-streaming A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: All at error. This rule checks whether any RPC uses server streaming. ## Rule details Server-streaming RPCs, whose response is declared with `stream`, are not supported by every transport: most HTTP/JSON gateways, for example, cannot carry them, and long-lived streams are harder to load-balance and debug than unary RPCs. The `rpc-no-server-streaming` rule reports `RPC '<rpc>' should not use server streaming` for every RPC with a streamed response, including bidirectional streaming RPCs. The rule is only part of the `all` ruleset. Turn the rule off if all clients use a transport that supports streaming, such as gRPC over HTTP/2, and some RPCs need to push updates. To allow a single RPC, add an `// apigenie-lint-disable rpc-no-server-streaming` comment to it. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc ListPets(ListPetsRequest) returns (ListPetsResponse); } message ListPetsRequest { int32 page_size = 1; string page_token = 2; } message ListPetsResponse { repeated string names = 1; string next_page_token = 2; } ``` **Bad**. The linter reports `RPC 'WatchPets' should not use server streaming`. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc WatchPets(WatchPetsRequest) returns (stream WatchPetsResponse); } message WatchPetsRequest { string shelter = 1; } message WatchPetsResponse { string name = 1; } ``` --- # rpc-request-response-unique Source: https://apigenie.pl/docs/linter/protobuf/rules/rpc-request-response-unique A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether every message is used as the request or the response of a single RPC. ## Rule details A message shared by several RPCs, or used both as a request and as a response, ties these RPCs together: a field added for one of them appears in all the others, and cannot be removed again without breaking them. The `rpc-request-response-unique` rule goes through the RPCs of all the services of the file in order, first the request and then the response type of each. When a type was already used by an earlier RPC, or as the request of the same RPC, it reports, at the RPC that uses it again: `Message '<type>' is used more than once: as <first use> and as <this use>` where each use reads `the request of '<rpc>'` or `the response of '<rpc>'`; in files with several services, RPCs are named with their service, e.g. `'PetService.GetPet'`. An RPC whose request and response are the same message is reported too. In the message, `<type>` is the type name as written in the RPC. Types are compared by their fully-qualified names, so `GetPetResponse` and `acme.pets.v1.GetPetResponse` are the same message. Only the RPCs of the linted file are compared. The rule resolves the request and response types among the declarations of the file and of the files it imports; a type that cannot be resolved is compared by its name as written, without a leading dot. Turn the rule off if the RPCs are part of an existing API that you cannot change. To allow a single RPC, add an `// apigenie-lint-disable rpc-request-response-unique` comment to it. ## Configuration The configuration block is an object with boolean properties: - `allow_google_protobuf_empty_requests`: whether `google.protobuf.Empty` may be the request of several RPCs (default `false`). - `allow_google_protobuf_empty_responses`: whether `google.protobuf.Empty` may be the response of several RPCs (default `false`). **Configuration example** ```yaml version: "1.0" commands: lint: protobuf: rules: rpc-request-response-unique: - warning - allow_google_protobuf_empty_requests: true allow_google_protobuf_empty_responses: true ``` ## Examples **Good**. With the default configuration. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc GetPet(GetPetRequest) returns (GetPetResponse); rpc UpdatePet(UpdatePetRequest) returns (UpdatePetResponse); } message Pet { string name = 1; } message GetPetRequest { string name = 1; } message GetPetResponse { Pet pet = 1; } message UpdatePetRequest { Pet pet = 1; } message UpdatePetResponse { Pet pet = 1; } ``` **Bad**. With the default configuration, the linter reports `Message 'Pet' is used more than once: as the response of 'GetPet' and as the response of 'UpdatePet'`. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc GetPet(GetPetRequest) returns (Pet); rpc UpdatePet(UpdatePetRequest) returns (Pet); } message Pet { string name = 1; } message GetPetRequest { string name = 1; } message UpdatePetRequest { Pet pet = 1; } ``` --- # rpc-request-standard-name Source: https://apigenie.pl/docs/linter/protobuf/rules/rpc-request-standard-name A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the request type of every RPC is named after the RPC, for example `GetPetRequest` for the RPC `GetPet`. ## Rule details When every RPC has its own request message, fields can be added to the request of one RPC without changing the others. Naming the message after the RPC makes this one-to-one relation visible. The `rpc-request-standard-name` rule accepts two names for the request type of the RPC `<rpc>` in the service `<service>`: `<rpc>Request` and `<service><rpc>Request`. Only the last component of the type name is compared, so `acme.pets.v1.GetPetRequest` is accepted as well. For any other request type, the rule reports: `Request type of RPC '<rpc>' should be named '<rpc>Request' or '<service><rpc>Request', not '<type>'` where `<type>` is the type name as written in the RPC. To recognize `google.protobuf.Empty`, the rule resolves the request types among the declarations of the file and of the files it imports; `google/protobuf/empty.proto` is known built in. A type that cannot be resolved is compared as written, without a leading dot. Turn the rule off if the RPCs are part of an existing API that you cannot change. To allow a single RPC, add an `// apigenie-lint-disable rpc-request-standard-name` comment to it. ## Configuration The configuration block is an object with boolean properties: - `allow_google_protobuf_empty_requests`: whether `google.protobuf.Empty` is accepted as a request type (default `false`). The type is resolved, so `.google.protobuf.Empty` is recognized, too. - `allow_google_protobuf_empty_responses`: accepted for symmetry with the related rules, but ignored by this rule. **Configuration example** ```yaml version: "1.0" commands: lint: protobuf: rules: rpc-request-standard-name: - warning - allow_google_protobuf_empty_requests: true ``` ## Examples **Good**. With the default configuration. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc GetPet(GetPetRequest) returns (GetPetResponse); rpc ListPets(PetServiceListPetsRequest) returns (ListPetsResponse); } message GetPetRequest { string name = 1; } message GetPetResponse { string name = 1; } message PetServiceListPetsRequest { int32 page_size = 1; } message ListPetsResponse { repeated string names = 1; } ``` **Bad**. With the default configuration, the linter reports `Request type of RPC 'GetPet' should be named 'GetPetRequest' or 'PetServiceGetPetRequest', not 'PetId'`. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc GetPet(PetId) returns (GetPetResponse); } message PetId { string name = 1; } message GetPetResponse { string name = 1; } ``` --- # rpc-response-standard-name Source: https://apigenie.pl/docs/linter/protobuf/rules/rpc-response-standard-name A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the response type of every RPC is named after the RPC, for example `GetPetResponse` for the RPC `GetPet`. ## Rule details When every RPC has its own response message, fields can be added to the response of one RPC without changing the others: returning a bare `Pet` from `GetPet` leaves no room for metadata that only this RPC needs. Naming the message after the RPC makes this one-to-one relation visible. The `rpc-response-standard-name` rule accepts two names for the response type of the RPC `<rpc>` in the service `<service>`: `<rpc>Response` and `<service><rpc>Response`. Only the last component of the type name is compared, so `acme.pets.v1.GetPetResponse` is accepted as well. For any other response type, the rule reports: `Response type of RPC '<rpc>' should be named '<rpc>Response' or '<service><rpc>Response', not '<type>'` where `<type>` is the type name as written in the RPC. To recognize `google.protobuf.Empty`, the rule resolves the response types among the declarations of the file and of the files it imports; `google/protobuf/empty.proto` is known built in. A type that cannot be resolved is compared as written, without a leading dot. Turn the rule off if the RPCs are part of an existing API that you cannot change. To allow a single RPC, add an `// apigenie-lint-disable rpc-response-standard-name` comment to it. ## Configuration The configuration block is an object with boolean properties: - `allow_google_protobuf_empty_responses`: whether `google.protobuf.Empty` is accepted as a response type (default `false`). The type is resolved, so `.google.protobuf.Empty` is recognized, too. - `allow_google_protobuf_empty_requests`: accepted for symmetry with the related rules, but ignored by this rule. **Configuration example** ```yaml version: "1.0" commands: lint: protobuf: rules: rpc-response-standard-name: - warning - allow_google_protobuf_empty_responses: true ``` ## Examples **Good**. With the default configuration. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc GetPet(GetPetRequest) returns (GetPetResponse); rpc ListPets(ListPetsRequest) returns (PetServiceListPetsResponse); } message GetPetRequest { string name = 1; } message GetPetResponse { string name = 1; } message ListPetsRequest { int32 page_size = 1; } message PetServiceListPetsResponse { repeated string names = 1; } ``` **Good**. With `allow_google_protobuf_empty_responses: true`. ```proto syntax = "proto3"; package acme.pets.v1; import "google/protobuf/empty.proto"; service PetService { rpc DeletePet(DeletePetRequest) returns (google.protobuf.Empty); } message DeletePetRequest { string name = 1; } ``` **Bad**. With the default configuration, the linter reports `Response type of RPC 'GetPet' should be named 'GetPetResponse' or 'PetServiceGetPetResponse', not 'Pet'`. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc GetPet(GetPetRequest) returns (Pet); } message GetPetRequest { string name = 1; } message Pet { string name = 1; } ``` --- # service-comment-defined Source: https://apigenie.pl/docs/linter/protobuf/rules/service-comment-defined A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether every service of a Protobuf file has a leading comment. ## Rule details Comments are the documentation of a Protobuf API: `protoc` passes them to the code generators, which copy them to the generated code, and documentation generators render them. The `service-comment-defined` rule checks every service, and reports `Service '<name>' has no leading comment` when there is no leading comment, or when it contains only whitespace. A leading comment is the comment right before the declaration, as `protoc` attaches it: a comment separated from the declaration by a blank line is a detached comment, and a comment after the declaration on the same line is a trailing comment; neither counts. Both `//` and `/* */` comments count. Turn the rule off if the services of your files are documented elsewhere, or if their names are descriptive enough. Lines with an `apigenie-lint-disable` directive do not count as documentation: a leading comment made only of directives does not satisfy the rule. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; // Manages the pets of the shelter. service PetService { rpc GetPet(GetPetRequest) returns (GetPetResponse); } message GetPetRequest { string name = 1; } message GetPetResponse { string name = 1; } ``` **Bad**. The linter reports `Service 'PetService' has no leading comment`. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc GetPet(GetPetRequest) returns (GetPetResponse); } message GetPetRequest { string name = 1; } message GetPetResponse { string name = 1; } ``` --- # service-naming Source: https://apigenie.pl/docs/linter/protobuf/rules/service-naming A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the name of every service of a Protobuf file is in `PascalCase`. ## Rule details The service name becomes the base of the names of the generated client and server classes, so it should follow the type naming conventions of the target languages. The `service-naming` rule checks every service, and reports `Service name '<name>' should be PascalCase` for every name that is not in `PascalCase`. A name is in `PascalCase` when it starts with an upper-case letter and contains only letters and digits, such as `PetOwner` (acronyms such as `HTTPServer` are accepted). When the name converted to `PascalCase` differs from the original and is itself valid, the message ends with a suggestion, for example `, e.g. '<converted>'`. To convert a name, it is split into words at underscores and other separators, at lower-to-upper case changes and before the last capital of an acronym, and the words are capitalized and joined, so `pet_owner` becomes `PetOwner`. Turn the rule off if the names are part of an existing API that you cannot rename. To allow a single service, add an `// apigenie-lint-disable service-naming` comment to it. ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; service PetService { rpc GetPet(GetPetRequest) returns (GetPetResponse); } message GetPetRequest { string name = 1; } message GetPetResponse { string name = 1; } ``` **Bad**. The linter reports `Service name 'pet_service' should be PascalCase, e.g. 'PetService'`. ```proto syntax = "proto3"; package acme.pets.v1; service pet_service { rpc GetPet(GetPetRequest) returns (GetPetResponse); } message GetPetRequest { string name = 1; } message GetPetResponse { string name = 1; } ``` --- # service-suffix Source: https://apigenie.pl/docs/linter/protobuf/rules/service-suffix A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Recommended at warning, Strict at error, All at error. This rule checks whether the name of every service ends with a suffix, `Service` by default. ## Rule details A common suffix makes services easy to tell apart from messages in the Protobuf files and in the generated code, where the service name becomes the base of the client and server classes. The `service-suffix` rule reports `Service name '<service>' should end with '<suffix>'` for every service whose name does not end with the suffix. The comparison is case-sensitive. Turn the rule off if the service names are part of an existing API that you cannot rename. ## Configuration The configuration block can be a string or an object. If it is a string, its value is the suffix. If it is an object, it must contain only the `suffix` property, whose value is the suffix. The suffix cannot be empty. **Configuration example**. The following two examples are equivalent. They specify that service names must end with `API`. ```yaml version: "1.0" commands: lint: protobuf: rules: service-suffix: [warning, API] ``` ```yaml version: "1.0" commands: lint: protobuf: rules: service-suffix: - warning - suffix: API ``` ## Examples **Good**. With the default configuration. ```proto syntax = "proto3"; package acme.pets.v1; service PetStoreService { rpc GetPet(GetPetRequest) returns (GetPetResponse); } message GetPetRequest { string name = 1; } message GetPetResponse { string name = 1; } ``` **Bad**. With the default configuration, the linter reports `Service name 'PetStore' should end with 'Service'`. ```proto syntax = "proto3"; package acme.pets.v1; service PetStore { rpc GetPet(GetPetRequest) returns (GetPetResponse); } message GetPetRequest { string name = 1; } message GetPetResponse { string name = 1; } ``` --- # spell-check Source: https://apigenie.pl/docs/linter/protobuf/rules/spell-check A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. Since 0.9.0. In the rulesets: Strict at warning, All at warning. This rule checks the spelling of the comments of a Protobuf file. ## Rule details Comments are the documentation of a Protobuf API: code generators copy them to the generated code, and documentation generators render them. The rule reports every misspelled word, with up to three suggested corrections, for example `Misspelled word 'nmae' in comment (did you mean 'name', 'nae', 'mae'?)`, or `Misspelled word '<word>' in comment` when there is no suggestion. The rule checks the leading, trailing and detached comments of every declaration of the file: the syntax statement (including a license header before it), the package, imports and options, messages, fields, oneofs, enums, enum values, services and RPCs. The issue points at the declaration the comment is attached to. Comments inside a statement, such as `int32 /* type */ count = 1;`, are not checked. Comments are read as CommonMark: the rule checks their prose, and skips code spans, code blocks, raw HTML and link destinations. The rule also skips the tokens which are not plain words: - URLs, e-mail addresses, paths, and file and domain names (`pet.proto`, `example.com`), - identifiers: `snake_case`, `camelCase` and names with inner capitals (`PetService`), - acronyms, also in the plural (`RPC`, `APIs`, `ID's`), - tokens with digits (`v1`, `404`) and single letters. The spell checker is a C++ port of [Hunspell](https://hunspell.github.io). By default it uses the built-in English (US) dictionary from [SCOWL](http://wordlist.aspell.net) (as shipped with LibreOffice), extended with words common in API descriptions, such as `webhook`, `endpoint`, `namespace`, `nullable` and `json`. Any Hunspell dictionary can be used instead. The rule is part of the `strict` and `all` rulesets. Turn the rule off if your comments are written in a language you have no dictionary for. To accept the names of your products and other domain terms, add them to the `words` option rather than disabling the rule. ## Configuration This rule accepts an object with the following options: - `words`: extra words to accept, for example product names. A word is accepted as given, capitalized and in capitals: `petstore` accepts `petstore`, `Petstore` and `PETSTORE`. - `dictionary` and `affix`: paths of a Hunspell dictionary (`.dic`) and its affix file (`.aff`) to use instead of the built-in dictionary. They go together. Dictionaries in UTF-8, ISO-8859-1, ISO-8859-2 and ISO-8859-15 are supported. - `suggestions`: how many corrections to suggest for a word, from 0 to 10 (default 3). Suggestions are the costly part of the rule; on large files with many unknown words, `0` makes it much faster. **Configuration example** ```yaml version: "1.0" commands: lint: protobuf: rules: spell-check: - warning - words: [petstore] dictionary: path/to/en_GB.dic affix: path/to/en_GB.aff ``` ## Examples **Good**. ```proto syntax = "proto3"; package acme.pets.v1; // A pet that lives in the shelter. message Pet { // The name of the pet. string name = 1; // Must not be empty. } ``` **Bad**. The linter reports, both at the `name` field, `Misspelled word 'nmae' in comment (did you mean 'name', 'nae', 'mae'?)` and `Misspelled word 'emtpy' in comment (did you mean 'empty', 'mtpy'?)`. ```proto syntax = "proto3"; package acme.pets.v1; // A pet that lives in the shelter. message Pet { // The nmae of the pet. string name = 1; // Must not be emtpy. } ``` --- # Changelog Source: https://apigenie.pl/changelog What changed in each release of the CLI. The newest release is on the [downloads](/downloads) page. ## 0.12.0 (2026-11-08) `apigenie lint` loads Spectral ruleset files and gains the `camara` and `owasp` rulesets, and the commands of `apigenie`, `apigenie-generator` and `apigenie-catalog` take `--json`. The generators add Avro payloads for AsyncAPI and experimental Rust and Swift targets; `apigenie-mcp` (experimental) and the desktop editor's installers ship with the CLI. ### Added - **Spectral ruleset files in `apigenie lint`** (ADR-217): `extends` in the OpenAPI, AsyncAPI and Swagger sections takes the path of a ruleset file (`extends: [recommended, ./lint/team.spectral.yaml]`), and `--ruleset FILE` adds one from the command line. A file's own `extends`, `functions` and `functionsDir` resolve against it. `[ruleset, recommended|all|off]` pairs in `extends`, and `recommended: false` in ruleset files, work as in Spectral, and the configuration can re-tune or turn on the rules a file defines. Files are local: URLs are refused. In a ruleset file, `spectral:oas`, npm packages other than `@stoplight/spectral-owasp-ruleset` and settings of rules API Genie doesn't have are skipped with a warning, so the 41 rules of CAMARA's `.spectral-r4.yaml` and its functions load unchanged. - **The `camara` ruleset in `apigenie lint`**: `extends: [camara]` lints OpenAPI documents with the CAMARA project's `.spectral-r4.yaml` and its 14 JavaScript functions, which ship with API Genie. A CAMARA repository needs no copy of the file. Its 41 rules keep CAMARA's ids, 2 of them `recommended: false`, and `rules` re-tunes them. It extends the `owasp` ruleset, as the file does upstream, with CAMARA's settings of its rules; `spectral:oas`, which it also extends, is skipped without a warning. The file's `operation-success-response: true` turns on API Genie's rule of that id. - **`bundle: true` in the lint configuration**: `commands.lint.bundle` bundles the local files an OpenAPI 3.x document references into it before linting, on every run, as `--bundle` does. A CAMARA repository, whose APIs reference `../common/CAMARA_common.yaml`, lints with no flags once its configuration sets `extends: [camara]` and `bundle: true`. `--fix` ignores it and fixes each file as it is. - **The `owasp` ruleset in `apigenie lint`**: `extends: [owasp]` lints OpenAPI and Swagger 2.0 documents against the OWASP API Security Top 10 (2023) with Spectral's `@stoplight/spectral-owasp-ruleset` 2.0.1, its 32 rules and 2 JavaScript functions, which ship with API Genie. A ruleset file that extends `@stoplight/spectral-owasp-ruleset` gets it too, instead of a warning. On the upstream ruleset's 121 test documents it reports what Spectral reports, except on one that API Genie doesn't read (an `apiKey` scheme `in: path`). The upstream tests have no case for `owasp:api2:2023-read-restricted` and `owasp:api2:2023-write-restricted`. Like Spectral, they report each operation that no security scheme protects. As in Spectral, none of its rules lints AsyncAPI documents. - **`constructor.name` in JSONPath filters**: `@.type.constructor.name === 'Array'` tells an array from an object, as OpenAPI 3.1 rulesets do for `type: [string, "null"]`. - **JSONPath `^`, `console` and `documentInventory.graph`** (ADR-217): the jsonpath-plus parent operator `^` in `given` and `field`; `console.log`, `info`, `warn`, `error` and `debug` in JavaScript functions, whose output is dropped; and `context.documentInventory.graph.overallOrder()`, each distinct `$ref` value of the document. A `message` in a rule's `then`, which Spectral rulesets carry, is accepted and ignored. - **`apigenie-generator ... --check`** (ADR-227) on every `client`, `server` and `schema` target: the generator runs as usual but writes nothing, compares the files it would write with the output directory, prints the ones that would be created or changed, and exits with 1 when there are any, as `apigenie format --check` does. Files a target writes only when they are missing (controllers, implementation packages, tests) are compared only until they exist, and files the generator doesn't write are not compared. CI can check that the generated code in a repository matches the API description in one step: the guide "Generate a client and a server" shows it. - **`apigenie-generator client rust` and `apigenie-generator server axum` generate Rust crates (experimental)**: the client, on reqwest, has an async method per operation returning an enum of the documented responses. It has credentials per security scheme, typed server-sent event and JSON Lines streams, and multipart and form bodies. The server, on axum, has an `Api` trait to implement and a router whose handlers check security and validate parameters and bodies before calling it, answering invalid requests with problem details. Both share serde models that validate their constraints, need Rust 1.85, and pass `cargo fmt --check` and `cargo clippy -D warnings` as generated. The server doesn't send callbacks or webhooks yet, and AsyncAPI documents are refused. - **`apigenie-generator client swift` (experimental) generates Swift clients**: a SwiftPM package (Swift 6, iOS 16, macOS 13, tvOS 16, watchOS 9 and Linux) without dependencies, whose `Client` has an async method per operation returning an enum with a case per documented status (`.created(body: Shipment, headers: ...)`, `.notFound(Problem)`); an undocumented status throws `ClientError.undocumentedStatus`. Models are `Codable`, `Sendable` and `Hashable` structs and enums that tell missing properties from null ones (`Nullable<T>?`), decode `oneOf` by discriminator with `defaultMapping`, keep enum values the document doesn't list (`unknown(String)`), and check the constraints of their schemas with `validate()`, request bodies before they are sent. Requests go through an `HTTPTransport` protocol, URLSession by default; server-sent events, JSON Lines and JSON text sequences are `AsyncThrowingStream`s of their `itemSchema`, multipart bodies are structs of `MultipartFile`s and values, parameters are written in the `simple`, `label`, `matrix`, `form`, `spaceDelimited`, `pipeDelimited` and `deepObject` styles, operation and path servers are honoured, and `Credentials` holds a value per security scheme (API keys, HTTP basic and bearer, an OAuth 2 or OpenID Connect token provider, mutual TLS). Configured under `commands.generate.client_swift`. - **`apigenie-generator server vapor` and `server hummingbird` (experimental) generate Swift servers**: a SwiftPM package on Vapor 4 or Hummingbird 2 whose code is the same except the adapter registering the routes and `Package.swift`. An `APIHandler` protocol has an async method per operation taking its request (parameters, body, credentials) and returning the response enum of the Swift client; the routes check security requirements and decode and validate parameters and bodies (JSON, forms, multipart, JSON Lines, text, bytes) before the handler runs, answering 400 with RFC 9457 problem details that list JSON pointers, and stream server-sent events and JSON Lines as the items come. `WebhookSender` and `CallbackSender` send the document's webhooks and callbacks. Configured under `commands.generate.server_vapor` and `commands.generate.server_hummingbird`. - **`apigenie-generator client kafkajs` and `server kafkajs` generate Avro payloads, security, conditions and base64 strings**: Avro records and enums become TypeScript types, encoded in Avro's binary encoding by a dependency-free codec, with the schema id from `KafkaOptions.schemaRegistry` (a Confluent-compatible registry, or a function) in the payload or in a header, as the message's Kafka binding says. `kafka.ts` lists the SASL (SCRAM, PLAIN) and X.509 schemes of each server, and `securityConfig(server)` builds KafkaJS's `ssl` and `sasl` options from the environment variables of their credentials. The payload validators check `if`/`then`/`else`, `dependentRequired`, `dependentSchemas` and draft-07 `dependencies`, also in `server express`, and `contentEncoding: base64` strings are `Uint8Array`s. - **`apigenie-generator server spring` and `client java` generate Avro payloads**: a message with an Avro schema carries the class that `avro-maven-plugin` generates from its schema (`src/main/avro/<full name>.avsc`), encoded by `KafkaAvro` in Avro's binary encoding with the schema id from a registry (a `KafkaAvro.SchemaRegistry` bean or option, or the Confluent-compatible registry of the server's `schema-registry-url`) in the payload or in a header, as the message's Kafka binding says. - **`apigenie-generator server aspnet` and `client csharp` generate Avro payloads and security**: a message with an Avro schema carries an `ISpecificRecord` class of its record (`Avro/<full name>.cs`), encoded by `KafkaAvro` with Apache.Avro and the schema id from a registry (an `ISchemaRegistry` service or option, or the Confluent-compatible registry at `SchemaRegistryUrl`) in the payload or in a header. The `Security` setting names the SASL (SCRAM, PLAIN) or client certificate scheme the consumers and producers connect with, its credentials read from environment variables named after the scheme. - **`apigenie-generator server go` and `client go` generate Avro payloads and security for AsyncAPI documents**: a message with an Avro schema carries a struct of its record (`avro.gen.go`), written and read in Avro's binary encoding by the generated codec, with the schema id from `Options.SchemaRegistry` or the Confluent-compatible registry of the server binding's `schemaRegistryUrl` in the payload or in a header. `security.gen.go` has a function per SASL (SCRAM, PLAIN) or client certificate scheme returning its franz-go options, and `SecurityFromEnvironment` reads their credentials from environment variables named after the scheme (`main.go -security kafkaScram`). The models map `contentEncoding: base64` strings to `[]byte`, also in the OpenAPI `server go` and `client go`. - **The C#, Java, Python and Go models check `not` and draft-07 `dependencies`**: `server aspnet`, `client csharp`, `server spring`, `client java`, `server fastapi`, `client python`, the Python Kafka packages and the Go Kafka packages reject values that match a `not` schema on the presence and constant values of properties (in `if`/`then`/`else` too) and check `dependencies` as `dependentRequired` and `dependentSchemas`; C# conditions on properties with defaults tell set properties from defaulted ones, and closed tuples get their length as `MaxLength`. - **`apigenie-generator server spring` and `client java` configure the Kafka servers' security**: each SASL (SCRAM, PLAIN) or client certificate scheme gets a Spring profile in `application.yaml` (`--spring.profiles.active=kafka-scram`) and a `<scheme>Security(...)` method in the Java client's options, with `securityFromEnvironment()` reading the credentials from environment variables named after the scheme (`KAFKA_SCRAM_USERNAME`, `KAFKA_MTLS_CERT`, ...). - **`apigenie-generator client ws` and `server ws` generate security and the WebSocket binding's headers**: a channel takes the security schemes of its operations, or of its servers. Clients send the `credentials` of a scheme as its API key query parameter, header or cookie, as basic credentials, or as a bearer token in the `Authorization` header or the `access_token` query parameter; servers check them with the authenticators of `authenticate`, refuse a handshake without valid credentials with status 401 and one without a required binding header with 400, and give sessions `principal` and the typed `bindingHeaders`. Schemes that a handshake can't carry are reported. Types of `anyOf` alternatives with only `required` keep the object's properties, and `patternProperties` are typed as records. - **`apigenie-generator server phoenix` and `client elixir` generate Avro payloads, security, client ids and the WebSocket binding's headers for AsyncAPI documents**: a message with an Avro schema carries a struct of its record (`lib/<app>/avro/`), written and read in Avro's binary encoding by a dependency-free codec, with the schema id from a Confluent-compatible registry (the Kafka supervisor's `:schema_registry`, or `KAFKA_SCHEMA_REGISTRY_URL` in `server phoenix`) in the payload or in a header. `<Root>.Kafka.Security` has brod's configuration of each SASL (SCRAM, PLAIN) or client certificate scheme, with the credentials of environment variables named after the scheme (`KAFKA_SECURITY=kafkaScram`), and the brod clients take the client ids of the Kafka bindings. The Phoenix channels check the credentials of their security schemes with the `authenticate/2` callback of `<Root>Web.Security` and decode the binding's headers; the client's `connect` sends `:credentials` and `:headers` with the handshake. The models check `not`. - **`apigenie-generator client python` generates Avro payloads and security for AsyncAPI documents**: a message with an Avro schema carries a Pydantic model of its record (`avro.py`), written and read with fastavro, with the schema id from the `schema_registry` option (by default the Confluent-compatible registry of the server) in the payload or in a header. `security.py` has the aiokafka settings of each SASL (SCRAM, PLAIN) or client certificate scheme, and the `security` option names the one the client connects with, its credentials read from environment variables named after the scheme. - **`apigenie-generator server faststream` generates security, Avro payloads and the AMQP and MQTT message bindings**: `security.py` gives each broker the FastStream security object of the scheme its `<SERVER>_SECURITY` variable names (SASL, client certificates, MQTT tokens), with the credentials of environment variables. Kafka subscribers read Avro payloads with fastavro. AMQP messages are sent with their content type, `gzip` or `deflate` content encoding and message type, MQTT requests with their response topic and correlation data, and Kafka records with their key. Channel parameters with enums are `Literal`s, and those located in the payload are read from it. The models reject what their schemas don't allow and carry the payload examples for the AsyncAPI page. - **`apigenie-generator server elixir-grpc` and `client elixir` check the required fields of requests**: a generated `<Root>.Validation` module checks the fields marked `(google.api.field_behavior) = REQUIRED`, in the request and in the messages it holds. The server answers a request without a required field with INVALID_ARGUMENT, and doesn't call the implementation. The client doesn't send such a request: the call returns the same error, and a streamed call is cancelled. The messages in a partial update (a message with a `google.protobuf.FieldMask`) aren't checked. - **`apigenie-generator server absinthe` serves subscriptions**: when the schema has a subscription type, the application serves subscriptions over a WebSocket at the GraphQL endpoint with the graphql-transport-ws protocol, and `<Root>.PubSub.publish/2` publishes the values of a subscription field. The pubsub serves one node, and every subscription of a field gets every value published to it, whatever its arguments. The generator no longer warns that subscriptions have no transport. - **The client and server generators of `apigenie-generator` read Swagger 2.0 documents**: they convert a Swagger 2.0 document in memory to OpenAPI 3.2, with its polymorphism (a `discriminator` and the definitions extending it with `allOf`) as a union whose mapping comes from `x-discriminator-value`. What the conversion approximates is reported as a warning at its position in the Swagger document, as are the generators' own warnings; a reference to another document is an error. `--overlay` overlays apply to the Swagger document. The Java and Spring generators also read the `x-pattern-message`, `x-size-message`, `x-minimum-message` and `x-maximum-message` of a parameter from the parameter itself, where Swagger 2.0 documents have them. - **`apigenie-generator client python` sends content parameters, several media types, streams and client certificates**: a parameter described with `content` is sent whole, as JSON for JSON media types. A body with several media types takes a `content_type` argument, and JSON Lines and `application/json-seq` bodies are iterables of their `itemSchema`. A response that can be JSON or a stream gets a `<method>_stream` method returning a `Stream` of its server-sent events, JSON Lines or JSON text sequence items. Models check `if`/`then`/`else`, `dependentRequired` and `dependentSchemas` when they only test the presence and the values of properties, and `mutualTLS` schemes take a client certificate. - **`apigenie-generator server fastapi` decodes styled parameters, streams bodies and documents callbacks and webhooks**: `pipeDelimited`, `spaceDelimited`, non-exploded `form` and header arrays are split into their items, and `deepObject` and JSON `content` parameters are validated into their models. Server-sent events, JSON Lines and JSON text sequences are streamed when they are the only content of the response, or when the `Accept` header names them first, and streamed request bodies reach the implementation as async iterators. Callbacks, webhooks and response links are described in the served OpenAPI document, and `x-internal` operations are left out of it. - **`apigenie-generator server fastapi` models tuples, conditions and `readOnly`/`writeOnly`, and passes the client certificate of mutual TLS to `BaseSecurity`**: `prefixItems` are `tuple[...]` when the array has exactly one item per position, lists of the union of the positions otherwise. Conditions are checked by a `model_validator` when they only test the presence and the values of properties, `unevaluatedProperties: false` rejects unknown properties, and models with `readOnly` or `writeOnly` properties get an input variant for request bodies. `validate_<scheme>` of `BaseSecurity` receives the client certificate of the request, e.g. `validate_mutual_tls` for a scheme named `mutualTLS`. - **`apigenie-generator client elixir` and `server phoenix` models check constraints, tuples, `patternProperties` and conditions**: `new/1` checks the string, number, array and object constraints of the schemas. `prefixItems` are tuples when the array is closed, every position is required and the positions are simple types, otherwise lists checked position by position. `patternProperties` are the entries of a map checked against the schema of their pattern. `if`/`then`/`else`, `dependentRequired` and `dependentSchemas` are checked when they only test the presence and the values of properties. `readOnly` properties are left out of the requests a client sends and `writeOnly` properties out of the responses a server sends. - **`apigenie-generator client elixir` and `server phoenix` stream events and JSON Lines**: `text/event-stream`, JSON Lines and `application/json-seq` bodies are enumerables of their items, typed by the `itemSchema`. The client decodes a streamed response lazily as it arrives, and the server sends each item as a chunk. When a status of a Phoenix operation has several media types, the server sends the first one, in the document's order, that the `Accept` header accepts. - **`apigenie-generator server phoenix` sends webhooks and callbacks and serves mutual TLS**: `<App>.Senders` has a function per webhook and per request of a callback, sending it with Req. With a `mutualTLS` security scheme, `config/runtime.exs` also serves the API over https and verifies client certificates when `TLS_CERTFILE`, `TLS_KEYFILE` and `TLS_CACERTFILE` are set. - **`apigenie-generator client go` and `server go` model tuples, `patternProperties` and conditions**: a `prefixItems` tuple whose positions are references or scalars of one type is a slice of that type, and `Validate()` checks each position and the length of closed tuples. An object whose keys match one pattern is a map of the pattern's type, and `Validate()` checks the keys and values of each pattern. `Validate()` checks `dependentRequired`, and `if`/`then`/`else` and `dependentSchemas` when their schemas use only `required` and the `const` and `enum` of properties. The Go Kafka generators type tuples the same way and check `if`/`then`/`else` within the same limits. - **`apigenie-generator server go` streams events and sends webhooks and callbacks**: `text/event-stream` responses take a channel of `ServerSentEvent[T]`, and JSON Lines responses with an `itemSchema` a channel of their items, each written and flushed as it arrives. `WebhookSender` and one sender per callback send the requests the API makes, with their parameters serialized like the client's. - **`apigenie-generator client csharp` and `server aspnet` model tuples, `patternProperties`, `multipleOf` and conditions**: a `prefixItems` tuple is a list of the type its items share, with a maximum length when it is closed. An object whose keys match one pattern is a `Dictionary`; with several patterns it is a record whose `Entries` hold the values. A generated `[MultipleOf]` attribute checks `multipleOf`, and records with `if`/`then`/`else` conditions or key patterns implement `IValidatableObject`. The asyncapi C# generators share the models. - **`apigenie-generator client csharp` runs OAuth 2.0 flows**: an `OAuthClient` gets tokens with client credentials, the authorization code flow with PKCE and the device authorization flow. It renews them before they expire, with the refresh token when there is one. - **`apigenie-generator server aspnet` checks OAuth 2.0 scopes**: when each alternative of an operation's security requirements lists OAuth 2.0 or OpenID Connect scopes, the endpoint answers 403 unless the user has those of one alternative. - **`apigenie-generator server aspnet` reads object and `content` parameters**: `deepObject`, exploded form and delimited objects, and parameters described by JSON `content`. It also reads form fields with the `deepObject` encoding, and file arrays whose items have a `contentMediaType`. - **`apigenie-generator server aspnet` answers in every media type of a response**: files, text, `text/event-stream` (`ServerSentEventsHttpResult<T>`) and JSON Lines (`JsonLinesHttpResult<T>`), with streams typed by the item schema. - **`apigenie-generator server aspnet` sends webhooks and callbacks**: `Senders/` has typed HTTP clients, a `WebhookSender` and a class per callback of an operation, registered in a new `Program.cs`. - **`apigenie-generator client java` requests OAuth 2 tokens**: with the `RestClient` and `RestTemplate` libraries, an OAuth 2 scheme gets an `OAuth` authentication. It requests tokens with client credentials, renews them and uses refresh tokens, each flow at its own token URL. It runs the authorization code flow (with PKCE) and the device authorization flow (OpenAPI 3.2) step by step. `ApiClient` gets `setOAuthClientCredentials`. - **`apigenie-generator client java` presents client certificates**: with the `RestClient` and `RestTemplate` libraries and a `mutualTLS` scheme, `ApiClient` gets `withClientCertificate` (a key store and a trust store), `loadKeyStore` and `sslContext`. - **`apigenie-generator server spring` covers callbacks, webhooks, `deepObject` and streaming**: with `annotationLibrary: swagger2`, operations that register callbacks get `@Callback` annotations, and an `ApiWebhooks` interface documents the webhooks with `@Webhooks`. `deepObject` query parameters of objects and maps are read by a generated argument resolver (`@DeepObjectParameter`), which answers 400 when a value doesn't convert or two keys conflict. In Spring MVC (WebFlux already did), streaming responses (`text/event-stream`, JSON Lines, JSON sequences) of arrays return a `Flux` of their items. The SpringDoc configuration describes the flows of OAuth 2 schemes and `mutualTLS` schemes, and `writeOnly` properties get `Schema.AccessMode.WRITE_ONLY`. - **`apigenie-generator client java` and `server spring` model tuples, `patternProperties`, `multipleOf` and conditions**: a `prefixItems` tuple is a list of the type its items share, with a maximum size when `items: false` closes it. An object without properties whose keys match one pattern is a `Map`; with several patterns, or with `additionalProperties: false`, it is a class that reads each value as the type of its key's pattern. With `additionalProperties: false`, a key that matches no pattern fails to deserialize. With `useBeanValidation`, a generated `MultipleOf` constraint checks `multipleOf`. With it, `@AssertTrue` methods check the `if`/`then`/`else`, `dependentRequired` and `dependentSchemas` conditions on which properties are present and their constant values. - **`apigenie-generator client fetch` sends alternative request media types and JSON `content` parameters**: an operation with request media types of one kind (`application/merge-patch+json` and `application/json-patch+json`) gets a `contentType` param. A parameter described by JSON `content` is sent as JSON text; the client of `server mcp` does the same. The tools of `server mcp` take a body with several media types of one kind in any of them, with a `contentType` argument naming the one sent, and check the body against the schema of that media type. - **`apigenie-generator server mcp` reads a discriminator's `defaultMapping`** (`x-defaultMapping` before 3.2): a value without the discriminating property, or with a value of it that the mapping doesn't name, is validated against the default option, as `server orpc` does. - **`apigenie-generator server mcp` supports mutual TLS**: with a `mutualTLS` scheme, the server presents the client certificate that `<PREFIX>_<SCHEME>_CERT` and `<PREFIX>_<SCHEME>_KEY` name (PEM files), and checks the API's certificate against the CA bundle of `<PREFIX>_<SCHEME>_CA`, set with them or alone. Only the first `mutualTLS` scheme gets them. A package generated for such a document depends on `undici` 7. - **Five AsyncAPI lint rules**, the core rules of the AsyncAPI parser (`asyncapi validate`) that the linter lacked: `operation-messages-from-channel` reports a message of an operation, or of its reply, that is not a reference to a message of its channel; `operation-channel-in-channels` an operation of the root `operations` whose channel is not under the root `channels`; `channel-servers-in-servers` a server of a root channel that is not under the root `servers`; `channel-address-no-query` a channel address with a query or a fragment. These four are an `error` in `recommended`, `strict` and `all`. The first three report a reference to another file, which `asyncapi validate` accepts. `latest-version` suggests AsyncAPI 3.1.0 to an older document, as a `hint` in `strict` and `all`. - **Three OpenAPI lint rules**, a `warning` in `recommended` and an `error` in `strict` and `all`: `operation-tags-declared` reports a tag an operation uses that the document's `tags` does not declare, and `--fix` declares it; `server-urls-no-trailing-slash` reports a URL in the top-level `servers` that ends with a slash, and `--fix` removes it; `ref-no-siblings` reports, in OpenAPI 3.0, a key next to `$ref`, other than an extension, that the specification says to ignore. They are the counterparts of Spectral's `operation-tag-defined`, `oas3-server-trailing-slash` and `no-$ref-siblings`, and Redocly's `operation-tag-defined`, `no-server-trailing-slash` and `spec-ref-siblings`. When `server-urls` and `server-urls-no-trailing-slash` both fix one URL, one `--fix` makes one of the two changes and the next run the other. - **`apigenie-catalog versions` and `apigenie-catalog release`** (ADR-206): a release of a specification is a Git tag named by `catalog.tags.pattern` (`{name}-{version}` by default, so `orders-api-1.4.0`). `release NAME VERSION` creates the annotated tag at HEAD. It refuses when the version is not a semantic version above the latest release, the tag is taken, the file has changes that are not committed or its `info.version` is not the version; `--dry-run` only checks, `--push` pushes the tag. `versions NAME` lists the releases, newest first, and says when the file's `info.version` is not released. The catalog section gains `tags.pattern` and, per specification, `lifecycle` (`draft`, `active`, `deprecated`, `retired`; a retired specification can't be released) and `sunset`, which `list` shows in a LIFECYCLE column. Both commands have `--json` (`apigenie-catalog-versions-report.json`, `apigenie-catalog-release-report.json`). - **`--json` on every command** (ADR-198) of `apigenie`, `apigenie-generator`, `apigenie-catalog` and the `apigenie-server session` commands: the standard output holds one JSON document and nothing else. Commands with a report print it (`lint`, `diff` and `changelog` as with `--formatter json`, `test` its test report, `evolve plan`, `i18n check`, `config`, `config schema`, `apigenie-catalog list`), `format` prints each file and whether it changed (`apigenie-format-report.json`), and the other commands print the status of the run: the exit status, the error and warning messages and what they would have printed (`apigenie-status-report.json`), also when the command line can't be parsed. Exit statuses don't change, and messages still go to the standard error. - **Instructions for coding agents** (ADR-203): `distribution/agents/AGENTS.md` is a section to paste into the `AGENTS.md` (or `.github/copilot-instructions.md`, `.cursor/rules`, ...) of a repository, telling an agent to lint, format and diff the API descriptions it changes with `--json`, and the guide "Work with AI agents" shows it. The `api-genie` skill of the Claude Code plugin, which agents that load Agent Skills can use on its own, uses `--json`. - **`apigenie init`** (ADR-201) sets a repository up: it writes `apigenie.yaml` with the lint rules (`--ruleset`) of the families of API descriptions it finds, and the section of `distribution/agents/AGENTS.md` into `AGENTS.md` (or `--agents-file`), appending it to a file without it. Files that are there are kept, so a second run changes nothing; `--dry-run` writes nothing, and `--json` prints `apigenie-init-report.json`. - **Markdown copies of the documentation sites of `apigenie-generator docs`** (ADR-200): the `npm run build` of the project it writes puts a Markdown copy next to each page (`operation/getPet.md` beside `operation/getPet/`) for coding agents, with `llms.txt` and `llms-full.txt` at the root of the site, for OpenAPI, Swagger 2.0, AsyncAPI, Protobuf and GraphQL. `--no-markdown` leaves them out. - **`apigenie-mcp`** (ADR-202, experimental), a fifth binary installed with the CLI: a Model Context Protocol server on stdio for coding agents, with the tools `lint`, `check_breaking_changes` (against a file or a git revision), `changelog`, `format`, `bundle` and `describe` (an outline of an API). Each tool but `describe` runs `apigenie --json`, and `lint` and `check_breaking_changes` start their result with a one-sentence verdict. It writes nothing unless started with `--allow-write`. It works only on files inside the client's roots, else the `--root` directories, else its working directory. The Claude Code plugin starts it. - **`apigenie lint --bundle` and `apigenie diff --bundle`** (ADR-194) bundle the local files an OpenAPI document references into it before linting or comparing, as `apigenie bundle` does, so that what the references lead to is checked too. Lint issues in bundled content are reported in the file they come from, at their line; diff changes in bundled content have no position. A reference to a URL can't be bundled and fails the command; `--bundle` can't be combined with `lint --fix` or `diff --update-version`. - **CloudEvents in AsyncAPI documents** (ADR-205). Messages that are CloudEvents, in structured mode (an `application/cloudevents+json` content type) or binary mode (attribute headers such as `ce_id`), are checked as such. - The `cloudevents` lint ruleset (`extends: [recommended, cloudevents]`) has three rules: `cloudevents/required-attributes` (`id`, `source`, `specversion` and `type` declared and required, also when a later trait's `headers.required` replaced a CloudEvents trait's), `cloudevents/binding-headers` (the header prefix of the channel's protocol: `ce-` over HTTP, `ce_` over Kafka, `cloudEvents:` over AMQP) and `cloudevents/attribute-schemas` (`specversion` pinned to `1.0`, the formats of `time`, `source` and `dataschema`, extension names). `standard-media-types` accepts the CloudEvents media types. - `apigenie-server` and `apigenie test` report `message.cloudevents.invalid` (`error`) for a CloudEvent without a required attribute or with an invalid one, over every transport. - The mock gives generated events a UUID `id` (from the seed) and `specversion` `1.0`, and serves a message with the content type its traits set. - **Typed streams in `apigenie-generator client fetch`** (and the client of `server mcp`): an operation with a success response in `text/event-stream` or JSON Lines gets a function per format, `getTrackingEventsEventStream()` or `getTrackingEventsJsonl()`, returning an `AsyncIterable` of the items typed by `itemSchema` (`x-itemSchema` before OpenAPI 3.2). JSON Lines yield one parsed value per line, server-sent events an object with their `data`, `event`, `id` and `retry` fields (`ServerSentEvent` without an `itemSchema`); leaving the loop early closes the connection. - **Webhooks and callbacks in `apigenie-generator server express`**: `src/senders.ts` has `createWebhooks()` and `createCallbacks()`, typed senders that send the webhooks of the document and the callbacks of its operations with `fetch`. A callback's URL is resolved from the runtime expressions of its key, such as `{$request.body#/callbackUrl}`, against the request and response of its operation. A sender validates the parameters and a JSON, form or text body first, rejecting with an `InvalidRequestError` instead of sending an invalid request or one with a `contentType` the operation doesn't declare. It resolves with a declared response, typed per status, and rejects with an `UnexpectedResponseError` for any other. - **QUERY and other methods in `apigenie-generator server orpc`**: operations with methods other than GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS and CONNECT, such as QUERY with oRPC 1 or an `additionalOperations` COPY, are routed instead of skipped with a warning. The contract declares a method missing from oRPC's method type with a cast, and the CORS plugin allows it in its answer to a preflight. Node.js answers a request whose method is missing from `http.METHODS` with 400. - **Webhooks and callbacks in `apigenie-generator server orpc`**: `src/senders.ts` has `createWebhooks()` and `createCallbacks()`, typed senders that send the webhooks of the document and the callbacks of the procedures with `fetch`, like the Express server's senders. A sender validates the parameters and a JSON, form or text body with the Zod schemas of `OUTGOING_SCHEMAS`, and rejects with an `InvalidRequestError` instead of sending an invalid request or one with a `contentType` the operation doesn't declare. It rejects with an `UnexpectedResponseError` for an undeclared status or media type, or a JSON or text body its schema rejects. Its request and response types come from `src/schemas.ts`, such as `OnShipmentStatusChangedRequest` and `OnShipmentStatusChangedResponse`. A callback's URL is resolved against the input and output of its procedure. Both servers send the requests with the same module, `src/outgoing.ts`, which exports the errors and the types of the options. - **`createRootRouter()` in `apigenie-generator server express`**: a router to mount at the root that serves each operation under the path of its first server. An operation uses its own servers, else those of its path item, else `BASE_PATH`, so an operation served at the root of another host is routed at the root, not under the document's base path. `OPERATIONS` lists the servers of such operations, and the scaffold mounts the root router when the operations have paths other than `BASE_PATH`. `createRouter` is unchanged and serves every operation under `BASE_PATH`. - **Multipart bodies in `apigenie-generator server express`**: the router decodes a `multipart/form-data` body whose schema has properties into a typed object. Binary parts are `File` objects, object parts JSON and the others text converted to their schema's types; array properties collect repeated parts. A file of a media type its encoding doesn't allow, invalid JSON and a repeated single part are answered with 400, and the decoded body is validated against its schema. Such bodies were left to middleware and typed `unknown`. - **Streamed responses in `apigenie-generator server express`**: a handler can answer a `text/event-stream` or JSON Lines response with an `AsyncIterable` of its items, typed by `itemSchema` (`x-itemSchema` before OpenAPI 3.2). The router writes each item as it comes, one JSON line or one event, and calls the iterator's `return()` when the client disconnects; `RequestContext.signal` is aborted then too. - **A macOS installer**: `apigenie-X.Y.Z-macos-arm64.pkg` on the release page installs the five tools into `/usr/local/bin` on Apple silicon Macs, with a double-click and an administrator password. It is signed with a Developer ID Installer certificate, notarized and stapled, so macOS opens it without a warning, offline too. The macOS zip, the Homebrew formula and the npm package are unchanged. - **The desktop editor's installers on the release page**: API Genie Editor, the desktop editor, now ships with the CLI at its version. The release page has `apigenie-editor-X.Y.Z-macos-universal.dmg` for Apple silicon and Intel, signed, notarized and stapled. Windows gets `-windows-x64.msi` and `-windows-x64-setup.exe`, not code-signed yet, so SmartScreen warns before the first run. Linux gets `-linux-x64.deb`, `.rpm` and `.AppImage`. The release notes say which are signed, how to get past SmartScreen, and what the editor needs installed: `apigenie-server` for the mock server, and Node.js 20 or later for publishing and subscribing in AsyncAPI "Try it". ### Changed - **`{{property}}` in custom rules names a missing field by the path from its last existing member, as Spectral does**: for a field that doesn't exist, it is the path from the last member that does, such as `responses[429].content` or `post.summary`, where it was the last segment alone (`content`, `summary`). The messages of the core functions use it, so a missing field now reads `"post.summary" property must be truthy`. - **A JavaScript function's result path can hold segments of other types, as in Spectral**: a segment that is neither a string nor an index, such as a negative number or an array, names the member `String(value)` names, where the function failed. A path to a member that doesn't exist is reported at the closest one that does. - **`apigenie bundle`, `apigenie lint --fix` and `apigenie-server` stop on input that repeats a key in an object.** `bundle` and `lint --fix` print `duplicate key "<name>"` and exit with 2, instead of writing the key twice. `apigenie-server` prints `Cannot serve 'FILE': duplicate key "<name>"` and exits with 3. The message names the key, not its line. - **A JSONPath dot-notation name ends at `^`** (ADR-217): in the `given` and `field` of lint rules, `$.a^b` is now a syntax error; a member name that contains `^` is written in brackets, `$['a^b']`. Overlay `target` expressions are unchanged. - **The Java client and the Spring server leave the generation date out of `@Generated`** (ADR-227): `hideGenerationTimestamp` defaults to `true`, so generating twice from the same document gives the same files. The annotation keeps the generator version. Set `hideGenerationTimestamp: false` to get the date back; a configuration that sets only `generationTimestamp` now needs `hideGenerationTimestamp: false` as well. - **`apigenie format` lays out JSON output by the `array` and `object` styles**: `flow` writes an array or object on one line, with everything inside it. `block` and `best-fit` write one element or member per line, as in YAML output. The default `original` styles keep the previous JSON layout, one element or member per line, even for the flow collections of a YAML input: JSON keeps no styles, so formatting the output again would change them. `style_overrides` still apply to YAML output only. - **`apigenie-generator server ws` requires the authenticators of secured channels**: when a channel has security schemes, `createServer` takes `options` with `authenticate`, an `Authenticators` object with a function per scheme, and refuses connections that none of them accepts. Pass an authenticator for each scheme of your channels. - **`apigenie-generator client python` leaves out internal operations and sends `content` parameters as JSON**: operations marked `x-internal` are left out unless `internal_operations` is `true`, and a parameter described with JSON `content` is sent as JSON, not with the form style. Strings with a `contentMediaType` other than text or JSON are `File` values in requests and `bytes` in responses, not `str`. - **`apigenie-generator server fastapi` changes the signatures of some interface methods**: `deepObject` and JSON `content` parameters are arguments instead of `request`, delimited, non-exploded `form` and header arrays are lists instead of strings, and operations secured by mutual TLS take its token and call `validate_<scheme>`, which answers 501 until a `BaseSecurity` subclass implements it. Request bodies of models with `readOnly` or `writeOnly` properties are their `...Input` variant, the model leaves out its `writeOnly` properties, responses whose only content is a stream are `AsyncIterator`s of their items, and closed `prefixItems` arrays are `tuple[...]`. Update the signatures of existing implementations in `impl/`, which aren't regenerated. - **`apigenie-generator server go` moves operations with their own server and leaves out internal operations**: an operation or path item with `servers` is registered below the path of the first one's URL, not below `BaseURL`, e.g. `/health` instead of `/v2/health`. Operations marked `x-internal` are left out of `ServerInterface` and `StrictServerInterface`, and webhooks and callbacks marked so get no sender. Set `internal_operations: true` to keep them. - **`apigenie-generator server aspnet` widens some interface methods, moves routes and checks scopes**: operations whose responses have several media types return a `Results<...>` with a result per kind, and object and `content` parameters are now arguments. Update the signatures of existing implementations in `Apis/*Api.cs`, which aren't regenerated. Operations with servers of their own are mapped below the paths of those servers, e.g. `/health` instead of `/v2/health`. Operations whose security alternatives all list OAuth 2.0 or OpenID Connect scopes answer 403 when the user lacks them. `Program.cs` isn't regenerated either: register the senders with `builder.Services.AddHttpClient<WebhookSender>()` and one call per callback class. - **`apigenie-generator server spring` turns `contentMediaTypeAsBinary` on by default**: strings with a non-JSON `contentMediaType` and no `contentEncoding` are files and binary bodies, as with `format: binary` and as in `client java`. Set the option to `false` for the earlier `String`. - **`apigenie-generator client fetch` sends an operation to its own server, and leaves out internal and disabled operations**: an operation or path item with `servers` other than the document's first one is sent to the first of them, not to the configured `baseUrl`; `operationServers: false` in `configure()` sends every request to `baseUrl` again. The tools of `server mcp` do the same unless `<PREFIX>_BASE_URL` is set or `--mock` is given, and `<PREFIX>_OPERATION_SERVERS` (`true` or `false`) decides either way. Operations marked `x-internal` are left out unless `internal_operations` is `true`, and those marked `x-apigenie.codegen.disabled` always. - **The Swagger 2.0 linter reads documents through their conversion to OpenAPI** (ADR-209). An `operationId` or tag `name` that is empty or only whitespace is now an error of reading: `apigenie lint` prints `Operation ID must not be blank` or `Tag name must not be blank` and exits with status 2. Before, `operation-id-defined` reported an empty `operationId` with status 1, and a whitespace-only `operationId` or a blank tag `name` passed without an issue. - **`x-webhooks` of OpenAPI 3.0 documents are read as webhooks**, as `x-itemSchema` is read as `itemSchema`: the linters, `diff`, `changelog` and the generators see them, so linting an existing 3.0 document may report new findings in its webhooks. A 3.0 document is written with `x-webhooks` again. In 3.1 and 3.2 documents, and when its value isn't an object, `x-webhooks` stays an extension. - **`apigenie-generator server express` reads multipart bodies itself**: when middleware such as multer has already parsed a `multipart/form-data` body whose schema has properties, the router answers with 500 instead of passing the body on unvalidated. Middleware that only reads the raw body, such as `express.raw({ type: "multipart/*" })`, still works. - **`apigenie-generator client fetch` reserves `ServerSentEvent`, `AsyncIterable` and `requestStream`**: `index.ts` exports the runtime's `ServerSentEvent` type and the stream functions return `AsyncIterable`, so a component schema named `ServerSentEvent` or `AsyncIterable` is now generated as `ServerSentEvent2` or `AsyncIterable2`, and an operation named `requestStream` as `requestStream2()`. - **`apigenie-generator server express` reserves `ServerSentEvent` and `AsyncIterable`**: `index.ts` exports the runtime's `ServerSentEvent` type and the response types of streamed media types use `AsyncIterable`, so a component schema with either name is now generated as `ServerSentEvent2` or `AsyncIterable2`. - **`apigenie lint` is faster on large OpenAPI documents, and `apigenie lint --fix` much faster.** Checking the local references of the schemas no longer maps every value of the document to its JSON pointer, which took a fifth of the time of linting the GitHub specification, and `--fix` runs only the rules that offer fixes before applying them, then every rule once on the fixed document: about 40 percent less time. The reports and the fixed files are the same as before. ### Fixed - **`apigenie bundle` puts the referenced content in place of a component that only references its own name in another file**: `PhoneNumber: {$ref: common.yaml#/components/schemas/PhoneNumber}`, as CAMARA's APIs write their common schemas, becomes the `PhoneNumber` schema of `common.yaml`. The OpenAPI and Swagger bundles kept the reference and copied the schema next to it as `PhoneNumber_2`, which naming rules such as `camara-schema-casing-convention` reported. Commands that bundle a document before reading it do the same: `apigenie changelog`, `apigenie-generator docs` and, for OpenAPI documents only, `apigenie lint --bundle`, `apigenie diff --bundle` and `apigenie-server`. AsyncAPI bundles already put the content in place of any component that references another file, whatever its name. - **Custom rules report an issue whose path goes through a `$ref` at the definition it references**, as Spectral does. `apigenie lint` reported it at each reference, so a shared definition that breaks a rule was reported once per use. The OpenAPI, AsyncAPI and Swagger linters now report it once, at the definition, and its path and `{{path}}` name the definition too. Rules with `resolved: false` are unchanged. - **The JSON Schema of the `--formatter json` report allows the `hint` severity**: `apigenie lint` reports hints, as the reference says, but `apigenie-lint-report.json` allowed only `error` and `warning`, so a report with a hint failed validation against it. - **`apigenie-server --log-format json` writes `proxyValidation` once in its startup line**: with `--proxy-to mqtt://...` and no WebSocket or HTTP target, the line repeated the key. - **`apigenie convert` keeps the first Swagger 2.0 definition of a name `definitions` repeats**, the one references already resolved to, and leaves out the later ones. All of them went into `components/schemas`, which then had the name more than once. `apigenie-server`, `apigenie test --spec` and `apigenie-generator` do the same when they convert a Swagger 2.0 file in memory. They report each left-out copy at the line of the definition they keep. - **`.openapi-generator/FILES` of `server spring` and `server fastapi` no longer changes when the code is generated again** (ADR-227): it lists the controllers, the implementation package and the tests that exist and are kept, as it does when they are first generated. - **`apigenie-generator server phoenix` requires a client certificate for `mutualTLS` security schemes**: a connection without one was accepted as presenting the credential. - **`apigenie-generator client elixir`, `server phoenix` and the other Elixir generators keep a colliding module name that ends in a digit in PascalCase**: a second `PetOption1` is now `PetOption1V2` instead of `PetOption1_2`, which Credo's `ModuleNames` check rejects. Regenerating renames such modules: update code that refers to the `_2` names. - **`apigenie lint` checks AsyncAPI documents whose servers, channels or messages are in other files** instead of stopping with "Unspecified error". The rules skip what the other file holds. - **`patternProperties` in the TypeScript types of `apigenie-generator client fetch`, `server express`, `server mcp`, `client kafkajs` and `server kafkajs`**: when `additionalProperties` is `false` or a schema object, the properties an object doesn't list are typed by its `patternProperties` too. An object with `additionalProperties: false` whose keys follow patterns (`patternProperties: { '^dhl$': ..., '^ups$': ... }`) was generated as `Record<string, never>`, which allowed no property. It is now a `Record` of the union of the pattern schemas' types. - **`apigenie lint` and `apigenie diff` check OpenAPI documents with references to other files** (ADR-194) instead of stopping with "unresolved reference" (exit status 2). - The lint rules check what the file holds. A rule about keys checks a path or a response in another file too, and the others skip it. `path-parameters-defined` and `path-parameters-on-items` don't report path parameters that a parameter in another file may define. - `diff` compares such a reference, and a schema `$ref` to another file, by its `$ref`: the same one is no change, and another one is a `reference.$ref` change, `breaking` by default. An added or removed item in another file follows the rule of its place, with the strictest facts (a parameter may be required). `reference.$ref` now takes `add`, `remove` and `modify` rules. The changelog lists a parameter in another file by its `$ref`, in the location `$ref`. - **`openapi-json-schema-validation` accepts Path Item `$ref`s in OpenAPI 3.1 documents** (ADR-195, ADR-196). 3.1 documents are validated against the official 3.1 schema of 2026-08-03 instead of the 2022-10-07 one, whose Path Item had no `$ref`: every path under `paths` that referenced another path item was reported as "property was not successfully evaluated". The newer schema also accepts server URL templates such as `https://{region}.example.com` and the Link Object's `server`. As the specification says, it rejects `example` and `examples` side by side in a parameter, header or media type, and unknown fields next to the `$ref` of a webhook, a component path item or a callback, which went unchecked before. - **`openapi-json-schema-validation` accepts a comma-separated list of media ranges in an Encoding Object's `contentType`**, such as `image/png, image/jpeg`, as the OpenAPI 3.1 and 3.2 specifications allow (ADR-196). 3.0, 3.1 and 3.2 documents are validated against the official schemas of 2024-10-18, 2026-08-03 and 2026-08-30, which no longer check `contentType` for a single media range. The 3.2 schema requires the names of response headers, encoding headers and header parameters to be tokens (RFC 9110), and rejects braces in the name of a path parameter described by `content`. The 3.0 schema allows extensions in an Encoding Object, as `jv_schema`'s edited copy of the 2021-09-28 one did. - **`operation-id-defined` and `operation-id-unique` count an operation shared through a Path Item `$ref` once.** An operation of a component path item that paths or webhooks reference was reported once per reference, so `operation-id-defined --fix` failed with "conflicting edit", and `operation-id-unique` reported the operation's own ID as a duplicate. The generated ID is named after the first path that uses the operation, else the first webhook, else the component. - **`apigenie lint` no longer stops with "Unspecified error." on documents that nest too deep or expand aliases too far in parts the reader skips**, such as a recursive YAML alias under an unknown property or deep JSON in a 3.2 `components.mediaTypes` entry. The rule that walks them, `openapi-json-schema-validation`, checks such documents completely, and the other rules still run. A rule of the AsyncAPI and Swagger linters whose walk exceeds the limits reports "Cannot check the document: it exceeds the nesting or alias-expansion limits" next to what it found before. - **JSON Schemas that declare a dated OpenAPI dialect load**: `$schema` with `https://spec.openapis.org/oas/3.1/dialect/2024-11-10` (the default `jsonSchemaDialect` of the current 3.1 schema), `.../3.1/dialect/2024-10-25`, `.../3.2/dialect/2025-09-17` or `.../3.2/dialect/2026-02-26` failed with "unknown dialect", for example in `apigenie-generator schema zod`. They load as `https://spec.openapis.org/oas/3.1/dialect/base` does. - **`operation-id-defined` and `operation-id-unique` check the operations of callbacks**, those of operations and of `components.callbacks`. The specification requires an `operationId` to be unique among all operations of the API, callbacks included. `--fix` names a callback operation after its callback (`postCallbackOnEvent` by default), and an operation shared through a `$ref` is still counted once. - **The `apigenie diff` changelog lists an operation of a shared path item once, under its path.** An operation added, removed, modified or deprecated in a component path item that the last changed path references was listed again under that path's URL, for each webhook and for the component sharing it, in every formatter. The operations of component path items and webhooks are API operations only through the paths that reference them. A deprecated operation whose callback changed is no longer listed with the callback's method. - **`unused-shared-component --fix` keeps the security schemes that security requirements name.** It used to remove them, though the check didn't report them. ### Desktop editor - The right pane has no Code tab. *Show as code* on a file's root form, such as the *Specification* row's, shows the whole file as wide as the pane. While a file has syntax errors, its forms offer *Show the file as code*. A file picked in the file list opens its root form. The code no longer follows the tree's selection, and its cursor no longer selects in the tree. - With one spec open, the tree starts with a *Specification* row that opens the whole spec's form: its version and its sections. The form is headed *Specification*, in place of *Document*. - In a schema's rows, the type menu keeps its width and the description takes the rest. A long component name among the menu's references made the menu as wide as the name. - A long form, such as an operation's, lists its sections beside it: pick one to go to it, or *Overview* to go back to the start of the form. The list marks the section you are reading and hides when the form is narrow. - AsyncAPI's forms, such as a message's, list their sections as well. - A schema's form lists its sections too: the details of the row shown, in groups (Values, Limits, Flags, Composition) now headed in the details panel, and the keys edited as code. - Each key a form has no field for, such as `externalDocs` or a parameter's `style`, is a section of its own, named after the key and edited as code, in place of one *Other fields* section. - The forms' section headings, such as Parameters, Request body, Responses and Messages, are bands with an accent edge, set apart from the fields above them. - The parameters table's *In*, *Required* and *Schema* columns grow with their text in Safari and the macOS app, where a header parameter's *header* ran into *yes*. - The code view, *Show as code* and the text diffs use CodeMirror in place of Monaco: the app's code is less than half its former size, about 4.5 MB instead of 10 MB. Completion and hover still come from the spec's structure, and now work while the line you type is not valid YAML yet. The editor's colours follow the app's light and dark palettes. - YAML is highlighted in the code view and in a form's *Show as code*. - File › Close Spec (Ctrl+W, Cmd+W on macOS) closes the open spec and the files it brought, asking about unsaved changes first. The editor is then as it starts with no spec. - A *New spec…* button joins the toolbar. With no spec open, it asks for OpenAPI 3.1 or AsyncAPI 3.0, as File › New… does, then where to save the spec. The editor writes the spec there and opens it. - File › Open Recent lists the last ten specs opened, then Clear Recent. Started without a spec on the command line, the editor opens the newest one that still exists. - Files changed on disk, by a `git checkout` or another editor, are read again when you come back to the window. A file with unsaved changes keeps them: the status bar names it, and Save writes over the version on disk. A file deleted on disk is named in the status bar. - A View menu shows and hides the Side Bar (Ctrl+B), the Panel (Ctrl+J) and the Right Pane (Ctrl+Alt+B); on macOS, Cmd+B, Cmd+J and Cmd+Option+B. With the panel closed, the form and the right pane now reach the status bar. - *Export bundled* works in the desktop app for OpenAPI specs, and the Changes tab shows the API changes there. The installers now carry `openapi_bundle`, `openapi_diff` and `asyncapi_diff`, compiled to WebAssembly. - The splitters between the panes are thicker, with a grip in the middle. - A path's template and its path parameters change together in the forms. Each change is one undo step. A change that would give the path another path's template is refused, and nothing changes. - Setting a parameter's *In* to *path* makes it required and adds `/{name}` at the end of the template. - Renaming a path parameter renames its `{name}`, and the other path parameters of that name in the path and its operations. A name another path parameter already has is refused. - Removing a path parameter, or setting its *In* to another place, takes `{name}` out of the template (`/pets/{id}` becomes `/pets`). It stays when another path parameter of the path or its operations has that name. - The path's form and an operation's form do all three. A parameter's own form renames it and sets its *In*. - Editing the template in the path's form renames, adds or removes path parameters to match. A new `{name}` gets a required string path parameter on the path. When as many `{name}`s go as come, they are read as renames, in order. - Renaming a path parameter or editing the template leaves the parameters taken by `$ref` as they are. A rename then keeps their `{name}`, and a `{name}` of theirs renamed in the template gets a new path parameter. - In the path's form, a path parameter of the path or its operations that the template lacks has a button, *Add {name} to the template*, which adds `/{name}` at the end. - The tree lists these sections even when the spec lacks them: Servers, Tags, Paths, Webhooks (3.1 only) and Components in OpenAPI; Servers, Channels, Operations, Messages and Components in AsyncAPI. Each section, and each component section under Components, has a *+* that adds an entry and selects it, so that its form opens. A section the spec lacks is created with that entry. The *+* of Components asks which kind of component to add. The right-click menu has the same items, such as *Add server*, *Add operation…* and *Add schema*, and Insert on a focused row does what its *+* does. Shift+F10 opens that menu on keyboards without Insert. - The *+* of Paths asks for the method and the path of a new operation, and offers the paths the spec has, so that one path can get several operations (`GET /pets` and `POST /pets`). A new path is created with its operation. The right-click menu of an operation, and of a path without operations, has *Add operation to /pets…*, which starts with the path's first free method, and Insert on such a row opens it too. Adding a method the path already has, or a path of the same shape as one the spec has (`/pets/{petId}` beside `/pets/{id}`), says so. - The forms of a path item (a path, a webhook, a callback's path or one under Components) and of an operation have *Delete…* in their header. It asks first, names the references that would break, deletes as one undo step and opens what held the deleted entry. The right-click menu of an operation under Paths has *Delete path /pets…* too, since the tree lists a path with operations only through them; for a path that is a `$ref`, it deletes the path and keeps what the path refers to. - The forms of a tag, a server and every component (a schema, response, parameter, example, request body, header, security scheme, link or callback, in AsyncAPI too) have the same *Delete…*. Deleting a tag leaves the operations that list it as they are, and the confirmation says how many do. - A server variable's *Values* are chips, as an operation's tags are: Enter or a comma adds a value, its × removes it. - A schema's *Allowed values* are chips, as a server variable's values are. In a numeric or boolean schema a typed `3` or `true` is added as a number or a boolean, and the values already in the file keep their types. An object or array schema keeps the YAML text field. - Values chips no longer leave an empty line under them: the input after the chips takes what is left of their line. - Every example box (a schema's or a property's example, an Example object's value, a media type's and a message's examples) has a copy button in its top right corner. It copies the example as shown, JSON or YAML. - A form's header shows where its node is, from the file down (*openapi.yaml › Paths › /pets › GET › Responses › 200*), in place of its JSON pointer, which is now the tooltip. Each step opens that node's form. - The parameters tables of a path and an operation size their columns to what they hold: *In*, *Required* and *Schema* are as narrow as their content, *Name* takes a fifth of the width and *Description* the rest. - The tree's sections each have an icon (Info, Servers, Tags, Paths, Webhooks, Components, Channels, Operations, Messages), and so do the spec, shared-file and import-only groups. - Example fields show the value as JSON, with a switch to YAML that is kept for the next examples. These are the Example of schemas, parameters and media types, an Example's Value (formerly *Value (YAML)*), and a message example's payload and headers. A value with `.inf`, `.nan` or a recursive alias, which JSON can't hold, stays in YAML. Either is read back, and the file keeps its own style. - A schema's details show its Description, in Markdown with a Write / Preview switch. - A schema row's type menu offers one of, any of and all of, and a reference to each component schema. A schema the menu cannot show (several types, `not`...) reads *complex*, and *Edit in code* opens it in the code view. - The Example field of a schema's details is multi-line, and the other YAML fields there keep the lines of a mapping or a list: a generated object example no longer shows (and saves) as one joined line. - An operation's tags are a multi-select: chips that remove themselves, and an input that adds a tag, suggesting the declared ones. - The Problems panel filters by severity (Errors, Warnings, Info, Hints), and keeps the choice. - A form shown as code fills the height of the form pane. - The file list is headed *Spec and referenced files*, and the form's Raw section is split into *Other fields* and *Extensions*. - The desktop app lints OpenAPI documents with API Genie's own linter (the rules of `apigenie lint`), in the Problems tab and under the fields, with its quick fixes: the installers now carry it, compiled to WebAssembly. Until now only the web editor had it. - The linters read `commands.lint` of the project's `apigenie.yaml`, and `commands.lint.asyncapi` for AsyncAPI. The editor takes the file nearest to the spec, as `apigenie lint` run in the spec's folder finds it. It looks in the spec's folder on the desktop and the workspace folder in VS Code; in a browser, among the dropped files. On the desktop and in a browser, *Allow access to their folder…* widens that to a folder above the spec. Rulesets, severities and custom rules apply in the editor. A configuration the linter refuses is an error on the configuration file in the Problems tab, and then the default rules apply. Custom JavaScript functions don't run yet: the rules that call them are left out, with a warning. In VS Code an edit to the file applies as you type; elsewhere a change applies when the spec is opened again. - The linters read the ruleset files that `extends` names in `apigenie.yaml`, and the files those extend (ADR-217): from the spec's folder on the desktop; in a browser, from a folder allowed with *Allow access to their folder…*, or in Safari and Firefox among the dropped files when they sit beside `apigenie.yaml`. Their functions are left out with the rules that call them, and a warning says so. When a ruleset file extends a ruleset the editor's linter doesn't have (`spectral:oas`, `owasp`, an npm package), that ruleset is left out with a warning. A ruleset file's `aliases` and `overrides` are skipped with a warning too. An `extends` entry with an absolute path, or a relative path more than 8 folders up, is an error on that entry, and so is a ruleset file that can't be read or doesn't parse. The default rules then apply. - AsyncAPI documents are linted with API Genie's AsyncAPI linter (the rules of `apigenie lint` for AsyncAPI), with its fixes, in every host. - The editor no longer runs Spectral's rulesets (`spectral:oas`, `spectral:asyncapi`) or a `.spectral.yaml`. The Problems tab shows the findings of API Genie's linters under their own rule names, without Spectral's second report of the same problems. Spectral rules with no counterpart in API Genie are no longer reported. To keep a `.spectral.yaml`'s rules, move them to `apigenie.yaml`: see [Migrate from Spectral](https://apigenie.pl/docs/guides/migrate-from-spectral). A Spectral ruleset (`.spectral.yaml`, `.yml` or `.json`) with no configuration file in the spec's folder or above it gets an info finding that names that guide. - AsyncAPI documents are checked by API Genie alone (ADR-212): the AsyncAPI parser's findings are gone, and what it checked comes from API Genie's AsyncAPI linter, which gains 5 rules for the parser's core checks it lacked (`apigenie lint` reports them too). A structure error in another file of the spec shows on that file, where the error is. - The AsyncAPI docs preview shows API Genie's own AsyncAPI docs, as `apigenie` publishes them: the overview, servers and security of the spec, or the operation, channel or message selected in the tree or the code view. It no longer loads the official AsyncAPI renderer, and the editor carries no React. - The editor opens specs, not folders (ADR-197). *Open folder…* is gone: *Open spec…* (File › Open Spec…, Ctrl+O, on the desktop) opens a spec with the files it refers to. The desktop app starts on a spec given on its command line (`apigenie-editor openapi.yaml`), dropped spec files open in the browser, and a dropped folder is refused. A new file never overwrites a file on disk the editor did not read: suggested names skip it, and Save refuses and says why. - *Open spec…* opens one spec and the files its references reach, read as references name them, also after an edit adds one (ADR-197). Files that can't be read are listed under the file list, with *Allow access to their folder…* on the desktop and in Chromium browsers. In VS Code, the document is the spec and only the files it reaches join it. - The opened spec is the file being edited (ADR-197). The other files are referenced: shown in the tree, the file list (under Referenced), the code view and Problems, but read-only, with *Edit this file* to change one. - Path parameters have no Required checkbox: they are always required, and moving a parameter into the path sets `required: true` with the change. - Schema findings on examples, bindings and Try it name the field as code reads it (`[0].owner: Unexpected property 'age'`) instead of a JSON pointer and Ajv's message. - The editor fits its window: in a short window the bottom panel gives way, and the page never scrolls. - A tag's form lists the operations that have the tag, each a link to its form. - My schemas in the Library are editable: *Edit* opens one in the schema editor and the code view, and every change is kept in the library at once, with nothing to save. - The Flow tab shows only while the current file is an AsyncAPI spec. - A panel under the form and the right pane, as in VS Code, with a Problems tab: every finding of the folder by file, with its rule and line, a filter, and a click that goes to the node. The status bar's error and warning counts show and hide it, and its height is resizable. The tree and the file list no longer show problem counts. - The theme switch in the toolbar is one icon button that steps through the system's palette, light and dark. - The app icon is the website's favicon, the genie over the word API, in the desktop shell and as the web editor's favicon. - Restyled forms: sections with headings, short fields side by side, Write and Preview tabs opening into the description's bordered text box, quiet add and remove buttons, aligned table rows, tags and servers as pill toggles, and the operation's method badge. The schema editor draws guide lines from each schema to its properties and branches, and its Details panel puts paired keywords side by side. - Splitters between the panes: drag the borders between the side bar, the form and the right pane, and between the outline, the files and the Library, to resize them. Arrow keys move a focused splitter, a double-click or Enter puts its pane back to the default size, and the sizes are kept for the next visit. - A menu bar: File (New…, Open Folder…, Open File…, Save, Save As…, Exit) and Edit (Undo, Redo), with their shortcuts; on macOS, About and Quit are in the application menu and Edit has Cut, Copy, Paste and Select All. New… starts an OpenAPI 3.1 or AsyncAPI 3.0 spec in the open folder; Open File… opens the file's folder with the file selected; Save As… writes the current file anywhere on disk. - Closing the window, quitting, or opening another folder with unsaved files asks whether to save them first. - The web editor at https://apigenie.pl/editor/, deployed with the website: the same bundle as the desktop shell's, with the repository's WebAssembly modules. The status bar and About show the commit the editor was built from. - About, in the toolbar: the editor's version, the app's, and where to read what each host offers (the website's "The editor's hosts" page). - The app opens a folder given on its command line (`apigenie-editor <folder>`). - The desktop shell: the editor in its own window on macOS, Windows and Linux, opening folders in the native dialog and saving to them in place. - Try it for AsyncAPI operations: publish a message, with its payload and headers checked against the message's schemas first, or subscribe and watch what arrives, on the operation's Kafka, AMQP, MQTT or WebSocket servers. Needs Node.js 20 or later on the machine. - A mock server for OpenAPI specs, started from the toolbar: `apigenie-server` serves the spec as it is in the editor, saved or not, on this computer, and answers and validates requests as it does on the command line. Try it out in the preview can send to it, and its log shows each request and what didn't match the spec. Needs API Genie 0.11.0 or later installed (`npm install -g @mykulyak/api-genie` or `brew install mykulyak/apigenie/apigenie`), or `APIGENIE_SERVER` set to the `apigenie-server` binary. ## 0.11.1 (2026-11-01) A maintenance release with no changes to the tools: 0.11.1 republishes 0.11.0 to check the new local release flow. ## 0.11.0 (2026-11-01) A Claude Code plugin, released with the CLI, makes coding agents lint every API description they edit and check it for breaking changes. `apigenie convert` downgrades JSON Schema to draft-07, draft-04 and OpenAPI 3.0, and the linters gain a rule for poorly supported schema keywords and an opt-in `privacy` ruleset. ### Upgrading - **`apigenie-mock` is gone: run `apigenie-server`.** The deprecated name of the server (ADR-147) is no longer installed by any archive or package; scripts, Dockerfiles and CI jobs that still call `apigenie-mock` need the new name. - **`apigenie generate`, `apigenie mock` and `apigenie catalog` are unknown commands.** They no longer print the binary they moved to; run `apigenie-generator`, `apigenie-server` and `apigenie-catalog`. - **The naming rules of the OpenAPI, AsyncAPI and Swagger linters take the convention names of the GraphQL linter.** `parameter-naming`, `schema-enum-naming` and `schema-property-naming` accept `camelCase`, `camelCaseStrict`, `PascalCase`, `PascalCaseStrict`, `snake_case`, `kebab-case`, `CONST_CASE` (or `UPPER_CASE` and `SCREAMING_SNAKE_CASE`) and `Header-Case`. The short names `camel`, `camel-strict`, `pascal`, `pascal-strict`, `snake`, `kebab`, `const` and `header` are configuration errors now (`Unknown naming convention: camel`); rename them in `commands.lint`. The defaults are unchanged, and so is the Spectral `casing` function's `type`. ### Added - **A Claude Code plugin** (`distribution/claude-code`, ADR-182), released with the CLI and carrying its version. - A skill teaches coding agents the API Genie loop: lint after every spec edit, check breaking changes with `apigenie diff` before calling a change done, mock with `apigenie-server`, and generate with `apigenie-generator`. - A hook lints each OpenAPI, Swagger, AsyncAPI, GraphQL or Protobuf file Claude edits and reports only the findings the edit added. - The commands are `/api-genie:lint`, `/api-genie:breaking` and `/api-genie:mock`. - Install it with `/plugin marketplace add` on the folder. - **`apigenie convert --from jsonschema --to draft7|draft4|openapi30` (experimental) downgrades JSON Schema documents.** A schema of draft 2019-09 or 2020-12 becomes a draft-07 or draft-04 document, or a Schema Object of OpenAPI 3.0. The main rewrite is composition: a schema with `allOf` and `unevaluatedProperties` becomes one flat object schema with `additionalProperties`, the members' `properties`, `required`, `patternProperties`, `propertyNames`, `minProperties`, `maxProperties` and `dependentRequired` merged into it, local `$ref` members inlined (chains and nested `allOf` followed) and the definitions kept for other references. A member that can't be merged (`additionalProperties: false`, `anyOf`, `oneOf`, `if`, `enum`, a `discriminator`, a reference to another document, a cycle) keeps the `allOf`, drops `unevaluatedProperties` and says why on the standard error, as does a property two members define differently (kept as an `allOf` of both). The other keywords follow the target: `$defs` becomes `definitions` (references follow), `prefixItems` a tuple `items`, `dependentRequired` and `dependentSchemas` `dependencies`, `$dynamicRef` `$ref`; below draft-06 `const` becomes `enum`, numeric exclusive bounds the boolean form and boolean schemas objects; for OpenAPI 3.0 `null` types and alternatives become `nullable`, `examples` `example`, exact-match `patternProperties` `properties`, and a `$ref` with siblings is wrapped in `allOf`. What has no counterpart (`if`, `contains`, `propertyNames` and `dependentRequired` below draft-07; `minContains`, `$anchor`, `$vocabulary` everywhere) is dropped with a note. `--from` is optional: a document without `swagger` is a JSON Schema. The library is `src/jsonschema_convert`; the design is ADR-180. - **A lint rule for poorly supported schema keywords: `schema-keyword-support`**, in the OpenAPI and AsyncAPI linters (off in `recommended` and `strict`, a warning in `all`). It reports the keywords, and value forms, that the configured targets don't support, with the rewrite where one exists: `prefixItems`, `unevaluatedProperties`, `$dynamicRef`, `dependentRequired`, `if`, `contentSchema`, `const`, `type` arrays, numeric `exclusiveMinimum`, `nullable`, `$ref` with constraining siblings and more. The targets are `draft4`, `draft6`, `draft7`, `draft2019-09`, `openapi30` and `codegen` (the keywords most code generators ignore, the default); the options take a target, a list of targets, or `targets` and `allow` (keywords never reported). - **A `privacy` lint ruleset for OpenAPI: no credentials or personal data in URLs.** `extends: [recommended, privacy]` adds two rules that look at path and query parameters, the properties of object parameters, and `format`: - `privacy/no-credentials-in-url` (error) reports passwords, tokens, API keys, session ids and the like, and `apiKey` security schemes with `in: query` (OWASP API2:2023, CWE-598). Paging cursors such as `pageToken` are not reported. - `privacy/no-personal-data-in-url` (warning) reports e-mail addresses, names, dates of birth, phone numbers, national identifiers, bank and card numbers, and special categories of personal data (GDPR Art. 4(1), 9, 10). - Both take `allow` (names never reported) and `terms` (more names to report). - **The `openapi`, `openapi_i18n` and `asyncapi_i18n` WebAssembly modules have a browser flavour** (`<name>.web.mjs` and `<name>.web.wasm`, for browsers and workers), like the other modules in `src/wasm`. ### Changed - **Seeded mock data is the same on every platform, and differs from earlier versions.** `apigenie-server --seed`, `apigenie-generator` data and the other users of the schema value generator chose numbers, string and array lengths, enum values, `oneOf` branches, optional properties and nulls, and simulated latencies and failures, with the C++ standard library's distributions, whose values differ between Linux, macOS and Windows. They now sample mt19937_64's raw output with algorithms of their own, as faker already did, so a seed gives the same data everywhere; the values of a given seed change on every platform. Faker's own values do not change. - **The links to the documentation lead to the new addresses of the website** (ADR-183). Lint reports (`html`, `sarif`) link each rule under `https://apigenie.pl/docs/linter/<standard>/rules/<rule>`, `--version` the compatibility policy at `https://apigenie.pl/docs/reference/cli/compatibility`, and the configuration schema the configuration reference at `https://apigenie.pl/docs/reference/cli/configuration`. The old addresses redirect to the new ones. ### Removed - **`apigenie-mock`, the deprecated name of `apigenie-server` (ADR-147).** The archives, `.deb`, `.rpm`, Homebrew and the npm package no longer install it; run `apigenie-server`. The `APIGENIE_MOCK_*` variables and the `apigenie-mock.yaml` configuration file still work until 1.1. - The hints `apigenie generate`, `apigenie mock` and `apigenie catalog` printed, naming the binary that took the command over (ADR-123, ADR-147, ADR-160). ### Fixed - **OpenAPI linting reports missing local schema `$ref` targets** (#1014). `openapi-json-schema-validation`, enabled in `recommended`, `strict` and `all`, reports an unresolved reference at its `$ref` value. Local JSON Pointers and anchors respect schema `$id` resources; recursive references remain valid, and example data and external references are not checked. - **Phoenix server READMEs name a generated behaviour in their configuration example** (#1015), rather than always naming `Pets`. The example follows tag filtering and normalization, uses `Default` for untagged operations, and is omitted when no behaviours are generated. - **Unsupported numeric configuration versions are reported on one line** (#1016). `apigenie config check` no longer inserts a line break inside the quoted value for `version: 1.0`; the version must still be the string `'1.0'`. - **OpenAPI version changes use the configuration property name in diff reports** (#1017). Detailed reports now say `openapi.openapi` instead of `openapi.specVersion`, and their JSON `config_key` is `openapi`, matching the rules table and the existing configuration. - **The rule links of the AsyncAPI, Swagger, GraphQL and Protobuf linters lead to their rules.** The website publishes the rules and rulesets of all five linters; the links of the AsyncAPI and Swagger linters led to the OpenAPI rules, those of the GraphQL and Protobuf linters and of the `privacy/*` rules to no page. - **YAML output of strings that are not UTF-8.** Neither reader validates its text, so a JSON or YAML string with a stray byte (`"single\x9d"`) reached the YAML writer, which read past the end of the string, escaped the byte as another character, or wrote it raw. `apigenie format` and `convert` now write every ill-formed UTF-8 sequence of a string, a key or a comment as U+FFFD (one per maximal subpart), as the XML writer does (ADR-129); a comment also gets U+FFFD for a control character or a line break it cannot hold. - **Generated values keep the bounds of a property that `allOf` members define twice.** When one member gave a property `type: array` and a later one only `maxItems: 1` (or `maxLength`, `minimum` and other keywords that imply a type), the mock and `apigenie-generator` used the first definition and could make arrays that were too long. - **`standard-response-codes` accepts the `default` response.** It reported every `default` entry of a Responses Object as a non-standard response code (#1012). - **Three OpenAPI rules that reported nothing now check what their pages describe (#1013).** - `schema-example-defined` (in `recommended`, `strict` and `all`) reports an object, an array or a string with a `pattern` without an example, among the entries of `components/schemas` and the inline schemas of media types, parameters and headers; an example on the media type, parameter or header counts too. - `json-api/resource-type-unique` reports a resource object of a JSON:API response whose `type` is not a `const` or a one-value `enum`, and two resource objects with the same type. - `json-api/schema-validation` checks the shape of JSON:API request and response documents and their resource objects. It was not registered at all; it now is, and joins the `json-api` ruleset. - **`apigenie format` names a discovered configuration file in its configuration errors.** When the file came from the search for `apigenie.yaml` instead of `--config`, the `Invalid format configuration in '...'` message read the absent option (#1010). ## 0.10.0 (2026-10-25) The mock server is now `apigenie-server`, with a document store for CRUD resources and several services in one process, and a fourth binary, `apigenie-catalog`, keeps a repository's API catalog. `apigenie-generator` applies OpenAPI overlays before generating, and the three binaries share one table of exit statuses. ### Highlights - **`apigenie-server`**, the mock server and validating proxy under its new name, with a dashboard at `/__apigenie/ui` (Traffic, Operations, Scenarios, Contract, Data and, for AsyncAPI, Channels), several services on one port with a prefix each, a document store (`ctx.db`, `db.crud: auto` resources, seeding, snapshots), session recording and replay (`--record DIR`, `--replay DIR`), client certificates, MQTT 5 properties, and validating proxies for Kafka (`--proxy-to kafka://`) and AMQP (`--proxy-to amqp://`) brokers. - **`apigenie-catalog`** (experimental), a fourth binary: `catalog list` finds the API specifications of a repository and `catalog init` records them in `apigenie.yaml`. - **Code generation:** `--overlay FILE` on every OpenAPI and AsyncAPI target; the Elixir family (`client elixir` and `server phoenix` for OpenAPI and AsyncAPI, `server absinthe` for GraphQL, `server elixir-grpc` and the Elixir gRPC client for Protobuf); `server mcp` (experimental), a Model Context Protocol server from an OpenAPI document; `server orpc` at the conformance bar. - **`apigenie test`** speaks Kafka and AMQP (`KAFKA` and `AMQP` regions), GraphQL subscriptions over graphql-ws, gRPC client and bidirectional streams, MQTT 5 and mutual TLS. - **Towards 1.0:** one table of exit statuses for the binaries, `formatVersion` in every JSON report with published JSON Schemas, a JSON Schema for `apigenie.yaml` behind `apigenie config`, `config check` and `config schema`, configuration discovery without `--config`, the Compatibility page, and experimental labels on what is outside the coming promise. - **Linting and diffing:** the OpenAPI format registry as the list of formats, with `schema-format-deprecated`, `schema-format-unknown` and a `hint` severity; `diff` knows sunset dates and no longer rates deprecating as breaking; `apigenie evolve plan OLD NEW` (experimental) plans an expand/contract migration. - **Also:** `convert --from wsdl --to openapi31`, `i18n check` and `i18n sync`, OpenAPI formatting at every depth with layout options, Windows console colors, and a docs package published as `@mykulyak/apigenie-docs`. ### Upgrading - **Upgrading from 0.9: `apigenie-mock` is now `apigenie-server`.** The mock server and validating proxy is installed as `apigenie-server` by every archive and package, the npm package and Homebrew, and its Docker image is `mykulyak/apigenie-server`. The old names keep working until 1.1, each with a one-line deprecation notice on standard error: `apigenie-mock` is a symlink to `apigenie-server` (a copy in the Windows archive, a command of the npm package), and the `APIGENIE_MOCK_*` variables are read when the `APIGENIE_SERVER_*` variable of the same name is unset. The last `mykulyak/apigenie-mock` image (`latest` and this version) only prints the new name and exits with 2; older tags are unchanged. `apigenie-server.yaml` is read before `apigenie-mock.yaml`, which still works; `commands.mock`, the `x-apigenie-mock` extensions, the `X-Apigenie-Mock-*` headers and the `/__apigenie` admin API are unchanged. What the server sends says `apigenie-server` instead: the `Server` and `Via` headers, the HAR creator, the admin status `name`, the `Basic` realm, the MQTT client ids, and the contract report's `report` member (`apigenie-server-contract`) and JUnit suite name (`apigenie-server contract`). The reference page moved to [server](https://apigenie.pl/docs/reference/server); the old address redirects. The design is ADR-147. - **One table of exit statuses for `apigenie`, `apigenie-generator` and `apigenie-server`.** 0 success, 1 findings (lint errors, breaking changes, `format --check` differences, `i18n apply --strict` unknown keys, `overlay --validate` problems), 2 a usage, input or unexpected error, 3 and 4 `apigenie-server`'s document and address errors, 5 a failed contract report (`apigenie-server`, `apigenie test`). The 1.0 compatibility promise freezes it. Scripts that check for the old numbers need these changes: - errors that exited with 255 (`-1`) now exit with 2: unreadable or invalid input files in `bundle`, `convert`, `changelog`, `diff`, `i18n`, `lint` and `overlay`, bad configurations, and every error of `apigenie-generator`; - errors that exited with 1 now exit with 2: unknown options and commands, missing files, configuration files that can't be parsed, `format` on a file with syntax errors or an unsupported document, `bundle` of a `.proto` file with errors, `license --library` with an unknown name, and unexpected errors in `apigenie-server` and `apigenie test`; - `apigenie test` exits with 2 instead of 3 when a request file, an environment file or the specification can't be read or parsed; - `apigenie` and `apigenie-generator` without a command, or with an unknown one, exit with 2 (255 before) and print the help of the command above it on the standard error. `apigenie-server` keeps 3, 4, 5 and 130. The design is ADR-141 ([exit status](https://apigenie.pl/docs/reference/cli#exit-status)). - **`--version` lists the binaries installed next to it.** `apigenie --version` prints the version on its first line, then `apigenie-generator VERSION` and `apigenie-server VERSION` for those found in the same directory (the same for the other two binaries). Scripts comparing the version should read the first line: `apigenie --version | head -n 1`. The GitHub Action, the Homebrew formula and the release workflows do. Subcommands no longer have a `--version` of their own (`apigenie lint --version` printed 1.0). - **`lint --formatter json` and `diff --report detailed --formatter json` write an object.** Lint JSON is `{ "formatVersion": 1, "results": [...] }` and the detailed diff report `{ "formatVersion": 1, "changes": [...] }`; both were bare arrays. Read `.results` and `.changes` instead ([compatibility](https://apigenie.pl/docs/reference/cli/compatibility)). - **`diff` no longer rates deprecating as breaking.** In the `recommended` rules, setting or clearing `deprecated` on an operation, a parameter, a header or a schema is `non_breaking`: it announces a removal, and the removal is the breaking change (rated by `sunset_passed`, see Added). Gates that relied on it should set `operation.deprecated: breaking` (and `parameter`, `header`, `schema`) in `commands.diff.rules`. The design is ADR-172. - **Seeded faker values change.** Faker now draws its values with algorithms of its own, the same on every platform, and `name`, `email` and other values of a `--seed` differ from 0.9.0's. Usernames and emails are ASCII (`Cieślar` becomes `Cieslar`), and `date.between` is a range (`{date.between: {from: 2024-01-01, to: 2024-12-31}}`) rather than an alias of `date.recent`. - **Faker arguments are checked.** `x-faker`, `@mock(faker:, args:)`, `graphql.fields` and `fake()` reject arguments a provider doesn't take, of the wrong type or out of bounds (a negative length, a probability above 1) with faker's message, where they were clamped or ignored. - **`apigenie format` keeps the format of OpenAPI, Swagger and AsyncAPI files without a configuration.** Formatting `api.json` with no `--config` used to write `api.yaml` next to it; JSON files now stay JSON. Set `format: yaml` to convert them. - **The OpenAPI format configuration is checked.** Unknown keys (`indnet`), unknown objects in `property_order`, indents outside 2 to 9 and unknown output formats are reported with their line and column, and nothing is formatted; they used to be ignored or to abort the command. - **The `recommended` OpenAPI preset changes more of a document.** It now reaches nested schemas, inline callbacks and the objects of OpenAPI 3.2, sorts the path templates of `paths` (its `paths: sorted` had no effect), orders more schema keywords (`$ref`, `$id`, `$defs`, `default`, `examples`, `readOnly`, `writeOnly`, `deprecated`...) and the fields of 3.2 objects, and orders Reference Objects by `reference`. Expect a one-time diff when reformatting with `extends: [recommended]`. `property_order.responses` applies to the status codes of operations; the names of `components.responses` follow the new `componentNames` key. - **The configuration file is validated against a JSON Schema when it is loaded**, by `apigenie`, `apigenie-generator` and `apigenie-server`. Settings that were silently ignored are now errors (exit status 2) with the line, the column and the JSON pointer of the value: unknown keys under `commands.*` (the OpenAPI, AsyncAPI and Swagger linters, and the WebSocket generators, used to skip them), sections of commands that have no settings (`commands.bundle`, `commands.changelog`: `changelog` uses `commands.diff`), and values of the wrong type. `apigenie config check` lists the errors of a file; fix them, or remove the settings that did nothing. The design is ADR-145. - **`apigenie` and `apigenie-generator` find the configuration file without `--config`**: `apigenie.yaml` (`.yml`, `.json`, or `.apigenie.*`) in the current directory or a parent up to the root of the git repository. Pass `--no-config` to run with the defaults, as before, in a repository that has such a file. `apigenie-server` falls back to the same file after its own `apigenie-server.yaml` and `apigenie-mock.yaml`. - **The docs package is `@mykulyak/apigenie-docs`.** The npm project that `apigenie-generator docs` writes now depends on `@mykulyak/apigenie-docs` (`^0.1.0`), the new name of the web components package. 0.9.0 wrote `@mykulyak/apigenie-web-components` into `package.json`, and that package was never published under that name, so `npm install` failed. In a project generated by 0.9.0, replace that dependency with `"@mykulyak/apigenie-docs": "^0.1.0"`, or run `apigenie-generator docs` into it again. - **`apigenie test` speaks MQTT 5.** MQTT regions connect with MQTT 5 (falling back to 3.1.1 when the broker refuses it), and the messages they publish are checked with their MQTT 5 properties against the AsyncAPI MQTT bindings. A region publishing to a channel whose binding states properties (a `payloadFormatIndicator`, `contentType`, `correlationData`, `responseTopic`, or an operation's `messageExpiryInterval`) fails with `message.properties.invalid` until it gives them with `# @property` lines, or keeps MQTT 3.1.1 with the `version: 3.1.1` setting. The design is ADR-110 (amended). ### Added - **The OpenAPI format registry (https://spec.openapis.org/registry/format/) is API Genie's list of formats.** `apigenie-server` (mock and `--proxy-to`, OpenAPI and AsyncAPI), `apigenie test`'s contract checks and every other JSON Schema validation check the registry's formats beyond JSON Schema's: - int8, int16, uint8, uint16, uint32, uint64 and double-int ranges, with int64 and uint64 also as integer text; - decimal and decimal128, as numbers or text (decimal128: 34 significant digits, NaN, INF); - date-time-local and time-local (RFC 3339 without an offset); - http-date (IMF-fixdate and RFC 9110's obsolete forms) and unixtime; - ipv4-cidr and ipv6-cidr; - language (RFC 5646 tags); - media-range and char; - base64url and the RFC 8941 structured field items (sf-binary, sf-boolean, sf-decimal, sf-integer, sf-string, sf-token). commonmark, html, password and binary stay unchecked, as the registry allows. `openapi.custom_formats` in `apigenie.yaml` (or the server's configuration file) now reaches `apigenie-server`. Its formats are accepted as declared, and an entry naming a registry format replaces that format's type and turns its check off. The registry is vendored by `scripts/update-format-registry` (`--check` verifies the copy is current). The design is ADR-166. - **Lint rules for formats: `schema-format-deprecated` and `schema-format-unknown`**, in the OpenAPI, AsyncAPI and Swagger linters. - `schema-format-deprecated` (a warning in every ruleset) reports `byte`, `binary` and `base64url`, which the format registry deprecates from OpenAPI 3.1, with what replaces them (`contentEncoding: base64`, `contentMediaType`, `contentEncoding: base64url`). In OpenAPI 3.0 and Swagger 2.0 documents, which have no replacement, the issues are hints. - `schema-format-unknown` (off in `recommended`, a warning in `strict` and `all`) reports a format that is neither in the registry nor in `openapi.custom_formats`, such as a misspelled `date_time`. - `apigenie lint` passes `openapi.custom_formats` to the format rules. - **A `hint` severity for lint issues.** Hints are shown by every formatter (SARIF `note`, checkstyle and Visual Studio `info`, `hint` elsewhere, and `N hints` in the stylish summary), but never count as errors or warnings and never change the exit status. Rules can be configured with `hint` (or `info`) in `apigenie.yaml`. - **The generators map the format registry's formats.** - Java, Spring and the AsyncAPI Java targets: `uint32`, `double-int`, `unixtime` and `sf-integer` become `Long`, and `uint64` becomes `BigInteger` in the OpenAPI targets. `date-time-local` and `time-local` become `LocalDateTime` and `LocalTime` in the AsyncAPI targets too. - C# and ASP.NET: `int8` to `uint64` become `sbyte`, `short`, `byte`, `ushort`, `uint` and `ulong`; `double-int` and `unixtime` become `long`, `decimal128` becomes `decimal`, and `date-time-local` becomes `DateTime`. - Go: `double-int`, `unixtime` and `sf-integer` become `int64`. - Python and FastAPI: numbers of format `decimal128` become `Decimal` like `decimal` ones, `date-time-local` becomes pydantic's `NaiveDatetime`, and `time-local` becomes `datetime.time`. Decimals of `type: string` stay strings in every generator but C#, keeping their `pattern`. - Elixir: `date-time-local` becomes `NaiveDateTime.t()`, and `time-local` becomes `Time.t()`. - TypeScript validators and Zod schemas check the ranges of `int8` to `uint64` and `double-int`. Zod validates `date-time-local` with `z.iso.datetime({ local: true })` and `time-local` with `z.iso.time()`. - `apigenie-generator data` and the server's generated values pass the checks of every registry format: integer widths keep to their range, `unixtime` is a time in 2020..2029, and `http-date`, the CIDRs, language tags, media ranges, the `sf-*` items, JSON pointers and regular expressions get values of their syntax. - **The documentation components link formats to the format registry.** A schema's `format`, in `apg-schema`'s type label or its facts, links to the format's page of the registry (part `format-link`), and the generated examples have values for the registry's formats. The website's new Formats page lists every registry format with its JSON types and API Genie's support, and the lint rules, the configuration page and the server page link to it. - **`apigenie-server --proxy-to kafka://host:port` contract-tests an AsyncAPI document's Kafka channels against a real cluster.** There is no broker in the server: it is a validating client of the cluster (ADR-170). - **Reading.** It reads the channels' topics (the Kafka binding's `topic`, else the address; parameters match the topic's segments) from the offsets they had at start, outside any consumer group, so the application's consumers and offsets are left alone. - **Checking.** Every record is checked as the application's (a channel with only `send` operations), a client's (only `receive` operations) or whichever matches. The value is checked against the messages, the headers against the message's `headers`, the key against the Kafka binding's `key` (new check `message.key.invalid`) and the partition against the channel binding's `partitions` (new check `message.partition.invalid`). - **Results.** Records are logged as `kafka-in` and `kafka-out` events and count in the coverage and the contract report like any other messages. Enforce mode reports, as records can't be stopped. - **Admin publishes.** `POST /__apigenie/asyncapi/publish` produces a Kafka channel's record to the cluster after the same checks, with the new `key`, `headers` and `partition` fields, and answers where it went. - **Connection.** `kafkas://` connects over TLS. SASL PLAIN credentials come from `APIGENIE_KAFKA_USERNAME` and `APIGENIE_KAFKA_PASSWORD`. The cluster needs Kafka 2.3 or later; compressed record batches are reported and skipped. - **`apigenie-server --proxy-to amqp://host:port/vhost` contract-tests an AsyncAPI document's AMQP channels against a real AMQP 0-9-1 broker (ADR-171).** It is a client of the broker, not a broker. - **Reading.** It binds an exclusive queue of its own to the exchange of every channel whose address is a routing key (the address's parameters as `*` words of a topic exchange, any key of a fanout or headers exchange) and checks the messages it gets like the Kafka tap's records, plus their properties against the AMQP bindings (`deliveryMode`, `priority`, `expiration`, `userId`, `replyTo`, `timestamp`, `contentEncoding`, `messageType`; `message.properties.invalid`). Queue channels are left alone, as reading them would take the application's messages, and the tap says so. - **Results.** Messages are logged as `amqp-in` and `amqp-out` events and count in the coverage and the contract report. - **Admin publishes.** `POST /__apigenie/asyncapi/publish` publishes an AMQP channel's message to the broker, with the new `routingKey`, `properties` and `headers`, mandatory and confirmed (409 when no queue takes it). - **Connection.** `amqps://` connects over TLS. Credentials come from `APIGENIE_AMQP_USERNAME` and `APIGENIE_AMQP_PASSWORD`. - **`AMQP` requests in `apigenie test`.** An `AMQP amqp://host:port/vhost` region publishes its body's messages to `exchange` and `routing-key` with `# @property` basic properties and headers, and reads `subscribe` queues and private queues bound with `bind: EXCHANGE KEY`; a message no queue takes is an error. The messages are checked like the tap's, and replies are paired by a correlation id in a header or a property (RabbitMQ's direct reply-to works). `--generate --amqp-url` makes one region per operation of an AMQP channel. - **`KAFKA` requests in `apigenie test`.** A `KAFKA kafka://host:port` region produces its body's records to `topic` with a `key`, a `partition` and `# @property NAME VALUE` headers, and reads `subscribe` (or `topic`) until `# @expect` records came; the region's own records are left out. - A `topic` that a cluster creating topics on first use (`auto.create.topics.enable`) doesn't have yet is created by the region's first record and read from its start, also on Kafka 4, which reports such a topic unknown while it creates it. - With an AsyncAPI `--spec`, the records are checked like MQTT messages, plus their key and partition, and replies are paired with requests by a correlation id in a header or the payload. - Credentials come from `username` and `password`, else `APIGENIE_KAFKA_USERNAME` and `APIGENIE_KAFKA_PASSWORD`, and are redacted. - `kafkas://` uses `--ca-cert`, `--insecure` and `--client-cert`. - `--generate --kafka-url kafka://host:port` makes one region per operation of a Kafka channel. - **`apigenie convert --from wsdl --to openapi31` imports SOAP services.** A WSDL 1.1 document with SOAP 1.1 or 1.2 document/literal bindings over HTTP becomes an OpenAPI 3.1 document. The command also reads the WSDL documents and XML Schemas it imports and includes, as local files; remote ones aren't fetched. In the result: - Each SOAP operation is `POST {address path}/{operation}`, with `x-soap-address` and `x-soap-action`. The operations of a SOAP 1.1 and a SOAP 1.2 binding at one address merge, with a `text/xml` and an `application/soap+xml` body. - Requests and responses are SOAP envelopes whose schemas carry `xml` objects, so `apigenie-server` validates SOAP requests and answers SOAP envelopes. Faults are 500 responses, and one-way operations answer 202. - The XML Schema types (sequences, choices, attributes, simple content, restrictions and enumerations, extensions, occurrence bounds, nillable elements) are components, and the WSDL documentation is in the descriptions. - What has no counterpart is told as warnings with file, line and column: `xs:any`, substitution groups, lists, and decimals. WSDL 2.0, rpc/encoded and rpc/literal services are refused with exit status 2. The result lints without errors with `recommended`, and `diff` and the generators read it. `--from swagger2|wsdl` is optional: an XML input is WSDL. The library is `src/wsdl_convert`, tested on Apache CXF, NWS, ONVIF and WSDL 1.1 Note documents vendored in `data/tests/wsdl` with their licences. The design is ADR-164. - **`apigenie evolve plan OLD NEW` (experimental) plans safe API changes.** It splits the breaking changes between two OpenAPI 3.x documents into an expand wave (ship now: the old elements stay next to the new ones, `deprecated: true` with an `x-sunset` date) and a contract wave (ship after the window: the target document), writes `1-expand.yaml`, `2-contract.yaml` and `plan.yaml` to `--out` (default `evolve-out/`), and proves the plan with `diff` before writing anything: the expand wave is non-breaking against the old document, the contract wave has only scheduled removals (and what its units and the residue own) against the expand wave, and it equals the target. Ten recipes: removed operations and paths, moved paths (`--hints FILE` with `renames` as `METHOD /path` or diff's location syntax, a `window` and a `reason`), removed and renamed response properties, renamed request properties and parameters, removed request parameters, newly required request properties and parameters, removed request enum values (`x-deprecated-enum`); renames are detected when one member goes and one with the same schema comes. What no recipe makes safe is residue, listed with a reason (exit status 1). Each unit carries a server note (emit both, accept both, apply a default) and the report lists them as a checklist. `--window 90d|12w`, `--today DATE`, `--config` (the `commands.diff` block), `--format text|json` (`formatVersion: 1`, [apigenie-evolve-report.json](https://apigenie.pl/schemas/apigenie-evolve-report.json)). The reference page is [evolve](https://apigenie.pl/docs/reference/cli/evolve); the design is ADR-172. - **`diff` knows sunset dates.** The rule condition `sunset_passed` holds when the removed element is deprecated and its `x-sunset` (an RFC 3339 date or date-time) is on or before the date of the comparison, `--today` (default: the current date; OpenAPI documents only). The `recommended` rules use it for `remove_item` of operations, path items (every operation sunset), parameters, component schemas and parameters, response properties and their `required` items, and request enum values listed in the schema's `x-deprecated-enum`: a removal after the sunset is non-breaking, before it breaking, and documents without `x-sunset` are rated as before. A property deprecated next to its `$ref` counts as deprecated. - `apigenie-generator <target> --overlay FILE` applies OpenAPI Overlays (1.0 to 1.2) to the input before generating, in order, so the vendor extensions of a target can live in an overlay of their own instead of in the API description. Every target of OpenAPI and AsyncAPI documents takes it (AsyncAPI ones bundled first), and `commands.generate.<target>.overlay` lists overlays in the configuration file, relative to it, applied before the `--overlay` ones. An action whose target selects nothing is a warning with its position in the overlay, and an error with `--strict` (nothing is generated, exit status 2). Warnings and read errors about a value an overlay set point at the overlay's line (`spring.overlay.yaml:9:9 Warning ...`), and the document's own lines are kept, since `apigenie overlay` and every document built with `jv::JVBuilder` now keep the positions of what they copy. Each generator's reference page lists the `x-` extensions it reads. The codegen conformance suite generates its Spring target with `--overlay --strict` instead of a separate `apigenie overlay` step. The design is ADR-156. - **Client certificates (mutual TLS) for `apigenie-server` and `apigenie test`.** `--client-cert FILE --client-key FILE` presents a certificate to the servers that ask for one: the `https://`, `wss://`, `mqtts://` and gRPC TLS upstreams of `apigenie-server --proxy-to` (also `tls.client_cert` and `tls.client_key` in the configuration, `APIGENIE_SERVER_CLIENT_CERT` and `APIGENIE_SERVER_CLIENT_KEY`), and every `https://`, `grpcs://`, `wss://` and `mqtts://` request of `apigenie test`, with `--insecure` too. `apigenie-server --tls-client-ca FILE` (`tls.client_ca`, `APIGENIE_SERVER_TLS_CLIENT_CA`) requires a client certificate issued by those authorities on every HTTPS, WSS, gRPC and MQTTS connection, the admin API included. A refused client is a warning in the log that says why. The subject of an accepted certificate is `clientSubject` in the JSON log and the admin API's log, and the contract report lists the clients (`clients` in JSON, a `client` property in JUnit, a `Clients:` summary line). A client certificate or key that can't be loaded, a lone `--client-cert` or `--client-key`, and `--tls-client-ca` without `--tls-cert` exit with status 2. A server that refuses the client's certificate now says so in the error (`the server requires a client certificate`) instead of "the connection closed before a response". Session resumption and revocation checks (CRL, OCSP) are not supported. The design is the amendment of ADR-104 ([server](https://apigenie.pl/docs/reference/server/tls#client-certificates-mtls), [test](https://apigenie.pl/docs/reference/cli/test)). - **`apigenie-server --tls-cert` serves MQTT over TLS.** The MQTT broker of an AsyncAPI document uses the server's certificate (and `--tls-client-ca`), on port 8883 unless `--mqtt-port` or `asyncapi.mqtt_port` says otherwise; the startup line names it `mqtts://`. Before, it stayed cleartext on 1883. - `apigenie-server` has a dashboard at `http://127.0.0.1:4010/__apigenie/ui` (the startup banner names it): Traffic as it happens, with an exchange's request, answer and validation problems, Copy as curl, Replay, Save as stub and Add to `.http`; Operations by tag with their hits and what answers them, and a fixed answer per operation (a status, an example, a generated body, a latency) saved as an override, with the `Prefer` header that does the same for one request; Scenarios with their rules and hits, a rule builder and the network simulation with the last response times; Contract with the gate against `--fail-on` and `--min-coverage`, the coverage, the violations by check, the operations never called and the report files; Data with the document store's collections, seeds and snapshots and `ctx.state`. Every panel copies its settings as configuration YAML or `x-apigenie-mock`. The page is built from the web components (`src/app_web`, the `apg-server-*` elements, `@mykulyak/apigenie-docs/server`) and embedded in the binary; it follows the admin API's rules (`--admin off`, `admin.allow_remote`, `admin.port`). The admin API says more for it: `/routes` items carry `tags`, `deprecated`, the declared `responses` with their examples and `lastSource`, `GET /overrides` answers whole rules and the scenarios list theirs as `ruleList`, the status gains `url`, `startedAt` and `logSize`. The design is ADR-167 ([Dashboard](https://apigenie.pl/docs/reference/server/dashboard#dashboard)). - The dashboard has a Channels screen for AsyncAPI documents, listed when a served document has channels: the channels by WebSocket, MQTT and HTTP with their operations, the clients connected and the messages counted; for a channel, its messages in and out as they happen, its clients, and Publish, a message sent as the application would (`POST /__apigenie/asyncapi/publish`) to every client of the channel or to one, with a payload started from the document's examples or left to the server; a payload the message's schema refuses shows the violations and goes nowhere, until Send anyway; Copy as curl. The admin API says more for it: `GET /__apigenie/asyncapi/channels` items carry `messageList`, each message with its `contentType`, `summary` and `examples` (payload and headers), and `POST /__apigenie/asyncapi/publish` takes `client`, an id of `/asyncapi/clients`, to send to that one client (404 `asyncapi-unknown-client` when it isn't connected). The design is the amendment of ADR-167 ([Dashboard](https://apigenie.pl/docs/reference/server/dashboard#dashboard)); gRPC and GraphQL variants of the dashboard come after 1.0. - `apigenie-server`'s admin API serves what a dashboard needs. `GET /__apigenie/events` streams the log as it happens, as Server-Sent Events: the entry's id as `id:`, its kind as `event:` (`request`, `ws-out`, `reload`, and the new `scenario` and `contract-updated`), a `violation` event after an entry with violations, `?type=`, `?level=`, `?service=`, and `?after=` or `Last-Event-ID` to replay what the log still holds. While a stream is open every exchange's request and response headers and bodies are captured; entries gain `responseHeaders`, Base64 bodies for bytes that aren't UTF-8, and `*BodyTruncated`, and `log.body_limit` now bounds what the log keeps and what `/log` returns. `/routes` and `/scenarios` count `hits` with `lastStatus` and `lastAt` (`DELETE /__apigenie/hits` starts over). `POST /__apigenie/stubs {"id": 42}` makes a stub file of a logged exchange, written to `dir` or `proxy.record_dir`, or answered. `GET /__apigenie/contract.json` and `/contract.xml` download the report as `--report` and `--report-junit` would write it. For AsyncAPI documents, `GET /__apigenie/asyncapi/channels` and `/asyncapi/clients` list the channels and the WebSocket and MQTT clients, and `POST /__apigenie/asyncapi/publish` sends a message (given, or made as the schedule would) to a channel's clients, answering 422 when it doesn't match. A server of several services names the service of every item and event. The design is ADR-161 ([Admin API](https://apigenie.pl/docs/reference/server/dashboard#admin-api)). - `apigenie-server` serves several services at once, on one port with a prefix per service: several `SPEC`s (`apigenie-server pets.yaml orders.yaml events.yaml` mounts `/pets`, `/orders` and `/events`) or the configuration's `services` list, each with `name`, `spec`, `mount` (a path prefix, default `/<name>`; `{host: ...}`; `{port: ...}`, which a `.proto` file's service needs) and its own `proxy`, `stubs`, `scenarios`, `validation`, `security`, `operations` and other document settings over the server's. AsyncAPI WebSocket channels share the port; the MQTT broker is one per server, and services whose MQTT channels collide have their topics served under `<name>/`. Every event, admin API item (`/routes`, `/scenarios`, `/overrides`, `/log`, the status's documents), HAR entry and report section names its service; `GET /__apigenie/services` lists them and `?service=NAME` narrows any admin endpoint. The contract report has a section per service and a combined summary, to which `--fail-on` and `--min-coverage` apply. The startup line lists the services and their URLs. One `SPEC` is served as before. The design is ADR-159. - `apigenie-generator server mcp` (experimental) generates a Model Context Protocol server in TypeScript from an OpenAPI 3.x document, on the official MCP SDK (`@modelcontextprotocol/server` 2), so that AI agents call the API through typed tools: one tool per operation, named after its `operationId`, described by its summary and description, with a Zod input schema of its parameters and body. The tools call the API through a generated fetch client (`src/client`) and return the status and body of the response as structured content, with an output schema; failed requests and responses the document doesn't describe are error results that keep the body. Binary bodies and multipart files are base64 strings. `include_tags`, `exclude_tags` and `x-mcp: false` select the operations; the base URL and the credentials of the security schemes come from environment variables (`<PREFIX>_BASE_URL`, `<PREFIX>_API_KEY`...). `--mock` adds `npm run mock`, serving the document with `apigenie-server`, and makes it the default base URL for demos. Configured under `commands.generate.server_mcp`; the design is ADR-158. The codegen conformance suite checks it at Levels 1 to 3, Level 3 driving the tools with an MCP client against `apigenie-server --proxy-to`. The fetch client generator exposes how its functions call the operations (`client_fetch::Plugin::bindings()`), and the operation selection of the Elixir and Go generators moved to `openapi_generator`. - `apigenie-generator client elixir` also takes AsyncAPI 3.x documents and generates an Elixir library for the counterpart of the described application (or, with `perspective: application`, the application's Kafka library). Its WebSocket channels connect on Mint.WebSocket, with the Phoenix Channels protocol of `server phoenix` (topics joined on `/socket/websocket`, replies to refs, heartbeats) or with the plain frames of the document at the channels' addresses: `connect` takes the address parameters and the ws binding's query, `send_*` sends, a request function waits for its reply (matched by correlation id on plain connections), and what the server sends is decoded and given to the callbacks of a behaviour. Its Kafka channels have `send_*` and `request_*` functions on brod and a consumer group (`:brod_group_subscriber_v2`) per received operation, sharing the dispatch, decoding and replies of `server phoenix`'s pipelines; the library depends on `snappyer`, so that brod reads Snappy-compressed records. Configured under `commands.generate.client_elixir.asyncapi`; the design is ADR-154. The codegen conformance suite checks both perspectives at Levels 1 and 2 (with `mix dialyzer`) and, at Level 3, runs it against `server phoenix`: the WebSocket channels in both framings, the plain one through `apigenie-server --proxy-to ws://…`, and the Kafka channels both ways on the broker of the workflow's service container. - `apigenie-generator server phoenix` also takes AsyncAPI 3.x documents and generates a Phoenix application of their WebSocket and Kafka channels. Each WebSocket channel is a Phoenix channel (its address as the topic, `/tracking/{shipmentId}` as `tracking:<shipmentId>`, joined on `/socket/websocket`) and also a plain WebSocket at its address, whose frames are the messages of the document; both decode the address parameters, the ws binding's query and the received messages into model structs before a behaviour's callbacks get them, and the channel module's `push_*` and `broadcast_*` functions send. A request's callback returns its reply, which gets the request's correlation id. Each received Kafka operation is a Broadway pipeline (broadway_kafka) dispatching records by `ce_type`, payload property or decoding to the callbacks of its behaviour, with `on_unknown` and `on_invalid` hooks (a replier's `:ok` sends no reply) and batching from `x-apigenie-broadway` of the Kafka binding or the configuration; each sent operation has `send_*` functions on brod, and requests wait for their replies by correlation id on the reply topic; the project depends on `snappyer`, so that brod reads Snappy-compressed records. MQTT, AMQP and HTTP channels are skipped with an info line, Avro payloads with a warning. Configured under `commands.generate.server_phoenix.asyncapi` (`perspective: counterpart` generates the Kafka counterpart); the design is ADR-154. The codegen conformance suite checks both perspectives at Levels 1 and 2 (`mix compile --warnings-as-errors`, `mix format --check-formatted`, `mix credo --strict`) and, at Level 3, the plain WebSockets through `apigenie-server --proxy-to ws://…` and the application against its counterpart on the Kafka broker of the workflow's service container. - `apigenie-generator server absinthe` generates an Absinthe server of a GraphQL schema: a Mix project on Absinthe 1.12, Absinthe.Plug, Plug and Bandit. Its schema module imports the SDL shipped with the project (`import_sdl`, descriptions, deprecations, defaults and `@oneOf` included), and `hydrate/2` attaches: - resolvers: a behaviour per object type with a callback per root field and per field with arguments, calling the implementation configured for it (`config :app, App.Resolvers.Query, impl: MyApp.Query`), an error without one; - the resolution of interfaces and unions (`__typename` or an implementation); - parse and serialize stubs of the custom scalars. Custom directives are declared in a prototype schema. An optional Dataloader source is added with `dataloader`, and the router serves the endpoint and, in dev, GraphiQL. Subscriptions get resolvers but no transport. Configured under `commands.generate.server_absinthe`; the design is ADR-152. The codegen conformance suite checks it at Levels 1 to 3 (`mix compile --warnings-as-errors`, `mix format --check-formatted`, `mix credo --strict`, and the application answering `apigenie test` and the fixture's dataset with the data of `apigenie-server`). - The foundation of GraphQL code generation (ADR-151): `graphql_generator` reads a GraphQL schema into a target-neutral model (types with their extensions merged, fields, arguments, enum values, input types, scalars, directives, descriptions, deprecations and default values) for the GraphQL targets of `apigenie-generator`, and the codegen conformance suite gains a GraphQL fixture: the Carpet Express GraphQL API (`data/fixtures/graphql/carpet-express.graphql`), the GraphQL face of the OpenAPI and AsyncAPI fixtures, with its feature catalog, field coordinates (`Query.shipment`) as probe identifiers, and a dataset of operations whose answers from `apigenie-server` back the Level 3 of GraphQL servers. - `apigenie-generator server elixir-grpc` generates an Elixir gRPC server of a `.proto` file set on elixir-grpc (`grpc_server` 1.0) and protobuf-elixir 0.17: the modules of the messages, enums and services as protoc-gen-elixir writes them (no protoc needed), a behaviour per service with a callback per method (client and server streams as Elixir enumerables), a `GRPC.Server` calling the implementation configured with `config :app, <Service>, impl: ...` (UNIMPLEMENTED without one), the endpoint and the application (`mix run --no-halt`, port 50051 or `PORT`). `apigenie-generator client elixir` given a `.proto` file generates a gRPC client on `grpc` 1.0 and Mint: the same modules with the stubs, and a module per service with a typed function per method returning `{:ok, response}` or `{:error, %GRPC.RPCError{}}`, deadlines and metadata as options. Configured under `commands.generate.server_elixir_grpc` and `commands.generate.client_elixir.protobuf`; the design is ADR-153. The codegen conformance suite checks both at Levels 1 to 3 (`mix compile --warnings-as-errors`, `mix format --check-formatted`, `mix credo --strict`, `mix dialyzer`; the server under `apigenie test`, the client calling all 24 methods through `apigenie-server`). - Protobuf code generation starts: the `protobuf_generator` library gives the Protobuf targets of `apigenie-generator` a model of a `.proto` file set (the file and its imports, found with `-I/--proto-path` and among the embedded `google/protobuf`, `google/api` and `google/rpc` files) on the resolved descriptors of the Protobuf runtime: messages with their nesting, fields with their cardinality, oneofs, maps, enums, services and the streaming kind of their methods, comments, deprecations and `(google.api.field_behavior)`. Proto3 only. The codegen conformance suite has a Protobuf fixture, the gRPC services of Carpet Express (`data/fixtures/protobuf`: 7 services, 24 methods of all four streaming kinds, a catalog of 42 features), and runs Protobuf servers under the gRPC contract tester and clients through `apigenie-server` as a validating gRPC proxy. The design is ADR-150; Connect-ES and connect-go are the next targets. - The [Compatibility](https://apigenie.pl/docs/reference/cli/compatibility) page states the 1.0 promise: what semantic versioning covers from 1.0.0 (commands, options, configuration keys, environment variables, exit statuses, JSON report versions, the docs bundle, the `apigenie-server` admin API, the `x-apigenie-*` extensions), what it doesn't, and how a removal is deprecated first. The `--help` of `apigenie`, `apigenie-generator` and `apigenie-server` links to it. The design is ADR-155. - **`apigenie-catalog`, a fourth binary (experimental), keeps the API catalog of a repository.** Every archive, the `.deb` and `.rpm`, the npm package and Homebrew install it next to `apigenie`, `apigenie-generator` and `apigenie-server`; `--version` and `--help` of each binary name it, and `apigenie catalog ...` prints the `apigenie-catalog` command to run instead ([catalog](https://apigenie.pl/docs/reference/catalog)). The design is ADR-160. - `apigenie-catalog list [DIR]` lists the API specifications of a repository with no configuration: every OpenAPI, AsyncAPI and Swagger document, Protobuf file and GraphQL schema that git tracks or doesn't ignore (every file outside git), less `catalog.exclude`, with its name (from the catalog section, `info.title`, the Protobuf package or the file name), format and version, owner, path and the commit that last changed it. `--json` writes a report with `formatVersion` and a published schema, [apigenie-catalog-report.json](https://apigenie.pl/schemas/apigenie-catalog-report.json). - `apigenie-catalog init [DIR]` writes a `catalog` section to `apigenie.yaml` (created at the root of the repository when there is none) with one entry per specification: name, path and an `owner: null` placeholder. Running it again adds new specifications, keeps edited entries and their comments, and reports the entries whose files are gone (`--prune` removes them); `--dry-run` prints the file. Only the section's lines change in an existing YAML file. - The `catalog` section of the configuration file (`specs` with `path`, `name` and `owner`; `exclude`) is part of the configuration schema, so `config check`, `config --for catalog` and editors know it ([configuration](https://apigenie.pl/docs/reference/cli/configuration#catalog)). - `apigenie-server` keeps documents in a store that scripts share (see [Document store](https://apigenie.pl/docs/reference/server/store)). Scripts get `ctx.db.<collection>` with `insert`, `get`, `find(where, {limit, offset, sort})`, `count`, `all`, `update` (a JSON merge patch), `replace`, `delete` and `clear`; `where` takes equality and `$eq`, `$ne`, `$in`, `$gt`, `$gte`, `$lt`, `$lte` and `$contains` on fields and paths (`address.city`), and documents get the next id unless they bring one. `ctx.state` is unchanged. With `db.crud: auto` (or `--crud`), an OpenAPI document's `/shipments` and `/shipments/{id}` are served from the store without a script: `POST` stores the body (its `readOnly` properties generated, the document checked against its schema), `GET` lists with the operation's own paging, filter and `sort` parameters (envelopes get `total` and friends), `PUT`, `PATCH` (a merge patch) and `DELETE` change it, and an unknown id is 404; `x-apigenie-mock: {resource: ...}` names a resource (always served), binds it to a schema or switches it off. Writes that don't match the schema are reported, or refused with `--strict`. Collections are seeded from the files of `db.seed`, else the list operation's example, else `db.generate` documents generated with the run's seed, and `ctx.db.reset()` or `POST /__apigenie/db/reset` puts them back. A request's `X-Apigenie-Test` header gives each test run a namespace of its own that starts from the seeds. The admin API shows the store (`GET /__apigenie/db`, `/db/{name}`), replaces or clears a collection, and takes and restores named snapshots (`PUT /__apigenie/db/snapshots/{name}`, `POST .../restore`). `--db-file` (`db.file`, env `APIGENIE_SERVER_DB_FILE`) keeps the store in a JSON file across runs, written when the server stops or on `POST /__apigenie/db/save`; writes are `db` events in the log. With several services, each has a store of its own (and `--db-file` is refused). Configured under `commands.mock.db`; the design is ADR-157. - `apigenie-generator server phoenix` generates a Phoenix 1.7 application of an OpenAPI 3.x document, on Bandit and Jason, without Ecto, HTML or OpenApiSpex: a router with a route per operation (static segments first, `QUERY` and `COPY` through `match`, segments with several parameters split by the runtime), a behaviour per tag whose callbacks receive the decoded parameters and body, and a controller per tag calling the configured implementation (501 without one). Requests are checked before they reach it: missing credentials give 401, parameters and bodies that don't match their schemas 400, other media types 415, all as problem documents; credentials go to an optional authenticator. `mix phx.server` serves it. Configured under `commands.generate.server_phoenix`; the design is ADR-131. The codegen conformance suite checks it at Levels 1 to 3 (`mix compile --warnings-as-errors`, `mix format --check-formatted`, `mix credo --strict`, and `apigenie test` against `mix phx.server`). - `apigenie-generator client elixir` generates an Elixir client of an OpenAPI 3.x document on Req and Jason: a Mix project with a module per tag and a function per operation, `op(client, [body,] params \\ [], opts \\ [])`, returning `{:ok, body}` (the response decoded into its model, a list of them, text, bytes or `nil`) or `{:error, %ApiError{}}`, and a `!` variant raising the error. Parameters are a keyword list encoded in their styles (`deepObject`, delimited arrays, `content` parameters as JSON), bodies are model structs or maps sent as JSON, forms or multipart parts (files, lists of files), and `new/1` takes the base URL, Req options for retries and timeouts, and credentials for every security scheme: API keys in headers, the query or cookies, HTTP bearer and basic, OAuth2 and OpenID tokens, or a supplier called before each request. Configured under `commands.generate.client_elixir`; the design is ADR-131. The codegen conformance suite checks it at Levels 1 to 3 (`mix compile --warnings-as-errors`, `mix format --check-formatted`, `mix credo --strict`, `mix dialyzer`, and every operation called through `apigenie-server --proxy-to`). - Elixir models for the coming Elixir targets (`client elixir`, `server phoenix`): one module per schema with a struct, `@type t` and `new/1`, `new!/1` and `to_map/1` decoding and encoding JSON maps; string enums as atoms, `oneOf`/`anyOf` with a discriminator dispatching on the tag, `allOf` flattened, dates, times and base64 decoded, `additionalProperties` as a map field. The code passes `mix format --check-formatted` and `mix compile --warnings-as-errors`, which `WITH_ELIXIR_TESTS` checks (`ctest -L elixir`); the design is ADR-131. - `apigenie i18n check` compares a translation file with the texts of a spec, Protobuf or GraphQL file (or an `i18n extract` output) and fails unless every text is translated and every key is a text; it reports missing, empty, unknown and invalid keys and the coverage, as text or JSON (`--format json`, `--allow-empty`) ([i18n](https://apigenie.pl/docs/reference/cli/i18n)). - `apigenie i18n sync` updates a translation file after the document changed: it keeps the translations of unchanged texts and reports the new texts, the changed ones whose translations may be stale (`--drop-changed` drops them) and the removed ones (`--prune` drops them). - `i18n extract` extracts more OpenAPI texts: the `summary` and `description` of Reference Objects (3.1+), keyed at the `$ref`, the `summary` of tags and `name` of servers (3.2), the descriptions of OAuth scopes, and the titles and descriptions of schemas under `$defs`, `dependentSchemas` and `additionalItems`. - The `openapi_i18n` WebAssembly module applies translations (`apply`), compares and updates translation catalogs (`compare`, `sync`), and its `Translator` lists, replaces and removes locales and falls back on other locales (`translateWithFallback`). - `apigenie generate ...` exits with 2 and prints the command to run instead: `code generation moved to apigenie-generator; run: apigenie-generator <the same arguments>`. `apigenie mock ...` points to `apigenie-server` the same way. - The `--help` of each binary ends with the exit statuses and a line naming the other two binaries and what they do. - Experimental commands, outside the 1.0 compatibility promise, say so in their `--help` and on the first line they print (on the standard error, so that their output stays usable): `apigenie convert` (one target) and `apigenie-generator schema zod` (no conformance Level 3 yet). Their reference pages and the CLI overview carry the same label; `docs/experimental.md` lists what is experimental and why. - Every JSON report has a top-level `formatVersion` (1): lint, diff (`status`, `changelog`, `detailed`), changelog, the `apigenie test` report and the summary line of `apigenie test --formatter json`, the contract report of `apigenie-server`, and the docs bundle manifest (next to `apigenieDocs`). Adding fields keeps the version; removing or changing one bumps it (ADR-140). - JSON Schemas of these formats, published at `https://apigenie.pl/schemas/` (`apigenie-lint-report.json`, `apigenie-diff-report.json`, `apigenie-changelog-report.json`, `apigenie-test-report.json`, `apigenie-contract-report.json`, `apigenie-docs-manifest.json`) and linked from each command's reference page, and a Compatibility page listing the versioned outputs. - XML request and response bodies (`application/xml`, `text/xml`, `+xml`) are checked by `apigenie-server`, its validating proxy and `apigenie test`: a body is parsed, mapped to the JSON value its schema's `xml` objects describe (`name`, `namespace`, `prefix`, `attribute`, `wrapped`, OpenAPI 3.2 `nodeType`) and validated like a JSON body. A body that isn't well-formed is `request.body.malformed` (400) or `response.body.malformed` with its line and column; a root element other than the schema's is reported too. The mock answers XML media types with XML, and `apigenie test --generate` sends XML bodies, written the same way ([XML bodies](https://apigenie.pl/docs/reference/server/validation#xml-bodies)). The design is ADR-130. - **`apigenie test` streams.** GraphQL subscriptions go over WebSocket with the graphql-ws protocol (`graphql-transport-ws`) instead of a single `POST`. The request's headers go on the handshake and in `connection_init`. The events are the response (`?? body $[0].data...`, `response.messages`), and each is checked against the operation's selection set at `next[i]`. `# @expect` and `# @timeout` end the subscription, and `--generate` adds a request per `Subscription` field. gRPC client- and bidi-streaming methods are no longer skipped. Their messages are written as for WS regions, with `===` between them and `=== wait-for-server` to wait for an answer. Each message is checked against the `.proto` file at `message[i]`, and a bidi call's body is the array of its answers. `--generate` sends two messages to each stream. Both count in the coverage. The design is ADR-109 and ADR-111 (amended 2026-10-12) ([GraphQL subscriptions](https://apigenie.pl/docs/reference/cli/test/graphql#subscriptions), [gRPC requests](https://apigenie.pl/docs/reference/cli/test/grpc)). - The OpenAPI model reads 3.2's `xml.nodeType` (`x-nodeType` in 3.0 and 3.1 documents) and writes it back. - Internal: the `xml` library, a strict XML 1.0 + Namespaces 1.0 parser (a pull reader and an immutable tape DOM like jv's, positions on every node) and a streaming writer with `escapeText`/`escapeAttribute`. DTDs and entities other than the five predefined ones are refused, so external entities and entity expansion ("billion laughs") are errors; depth, attribute count and input size are limited. The design is ADR-129. - Colored output in Windows consoles: the CLI, `apigenie-generator` and `apigenie-server` style their output when it goes to a console, as they do in terminals elsewhere, and still not when it is redirected or `NO_COLOR` is set. - `lint --watch` prints the files whose change triggered the run (on standard error, so that the report stays parseable), and no longer misses edits made while a run is in progress. - **Faker providers take typed and named arguments and describe themselves.** `x-faker` accepts `{"string.alpha": {length: 6, casing: upper}}` and `{provider, args, options}`, the GraphQL mock's `args` and `graphql.fields` take a list or an object, and mock scripts call `fake('internet.email', {provider: 'example.org'})`. 295 providers (from 215) cover a person's sex and country, an email's names and host, phone formats, string casing, address countries, date formats and more ([faker reference](https://apigenie.pl/docs/reference/cli/faker)). - **Faker records**: `person.profile`, `location.address`, `finance.card`, `finance.currency` and `commerce.product` make related values together (one sex for a person's names, a username and email of those names, one country for an address with its time zone, one issuer for a card), written as objects in mocked responses and generated data. - `helpers.fromPattern` (alias `helpers.fromRegExp`) and `helpers.replaceSymbols`, and `date.between`, `date.birthdateByYear` and `date`/`time` formats for dates. - **OpenAPI formatting at every depth.** The formatter recognizes the objects of OpenAPI 3.0, 3.1 and 3.2 by walking the document from its root: schemas under `properties`, `items`, `allOf`, `$defs`, `if`/`then`/`else` and every other applicator, path items and operations of callbacks at any depth, 3.2 `query` operations, `additionalOperations`, `itemSchema`, `prefixEncoding` and `itemEncoding`, the content and examples of headers, and individual OAuth flows (`oauthFlow`). Example payloads and extension values are never taken for OpenAPI objects. The design is ADR-149. - **Independent orders for named maps and raw values**: `componentNames`, `webhooks`, `callbacks`, `callback`, `content`, `headers`, `properties`, `scopes`, `extension` and `exampleValue`, so that, for example, component schemas can be sorted by name while the properties of each schema keep their order. - **Layout options for OpenAPI**: `line_width`, `newline` (`lf`, `crlf`), `final_newline` and `document_marker`, backed by new jv write options. - **`style_overrides`** give chosen fields their own YAML styles, by field name and object kind, such as literal descriptions or flow `required` lists. - **`apigenie format --openapi-fragment KIND`** formats files holding a single OpenAPI object (a schema, a path item, a response...) with the rules of that object. - **A typed options API** (`openapi_format::FormatOptions`, `Formatter::setOptions`) for C++ consumers of the formatter library, validated like the configuration file. - `apigenie config` prints the effective configuration (YAML, or JSON with `--json`): the values of the file, those set by `APIGENIE_SERVER_*` environment variables (or their `APIGENIE_MOCK_*` fallbacks), and the defaults of the settings the file leaves out. `--origin` annotates each value with the file, the variable or `default` that set it, and `--for <section>` limits it to one section (`lint`, `format`, `diff`, `generate`, `generate.<target>`, `mock`) ([config](https://apigenie.pl/docs/reference/cli/config)). - `apigenie config check [FILE]` validates a configuration file and exits with 2 on errors, reporting every unknown setting at once with a suggestion for a misspelled name, and the allowed values of a setting with a fixed set. - `apigenie config schema [--for <section>] [--standalone-server] [--out FILE]` prints the JSON Schema (draft-7) of the configuration file, of one section, or of a standalone `apigenie-server.yaml`. Each release publishes them at `https://apigenie.pl/schemas/apigenie-config/<version>.json` and `.../apigenie-server-config/<version>.json`, with `latest.json`, for `# yaml-language-server: $schema=...` comments in editors. - `--no-config` for `lint`, `format`, `diff`, `changelog` and every `apigenie-generator` target. - MQTT 5 message properties end to end. `apigenie-server --proxy-to mqtt://` relays user properties, payload format indicator, content type, response topic, correlation data and message expiry both ways and checks them against the AsyncAPI MQTT bindings (0.2.0): the new contract check `message.properties.invalid` (error) for a payload format, content type, correlation data or response topic other than the message binding says, and a missing or longer message expiry than the operation binding's; the user properties are checked as the message's `headers` (`message.headers.invalid`); a reply's header correlation id and Correlation Data are compared with the request's. The mock's own broker sends the properties its bindings and headers state, checks its MQTT 5 clients' and answers requests on their reply address or Response Topic. `apigenie test` connects with MQTT 5 (`version: 5`, `3.1.1` or `auto`), sets properties with `# @property content-type ...`, `response-topic`, `correlation-data`, `payload-format-indicator`, `message-expiry-interval` and `user NAME VALUE`, subscribes to its response topic, pairs replies by reply-address user property or Response Topic, and `--generate` writes the properties of the bindings. Reports count the messages whose properties were checked (`summary.properties`). The design is ADR-112 and ADR-110 (amended); see [test](https://apigenie.pl/docs/reference/cli/test) and [server](https://apigenie.pl/docs/reference/server). - `apigenie-server --record DIR` records the session: every exchange the server answered, of every service and every protocol (HTTP, GraphQL operations, gRPC calls with their streams, WebSocket and MQTT messages of both sides), in the order it happened, each as a file under `DIR/<service>/` numbered across the session, with `session.yaml` naming the services (with the SHA-256 of their documents) and listing the exchanges. Each exchange carries `sequence`, `service` and `test`, the test being the request's `X-Apigenie-Test` header, a gRPC call's `x-apigenie-test` metadata, or the mark set with `POST /__apigenie/record/mark {"test": ...}`. HTTP and gRPC exchanges keep the stub forms of `--record-dir`, so `--stubs DIR/<service>` still loads them; GraphQL operations the example form; messages a form of their own. `POST /__apigenie/record/start` and `/stop` record a part of a run, `GET /__apigenie/record` says whether one is on, and the dashboard's Traffic screen has Record session and Save session. `--record-redact` (and `record.redact`) hides more headers and, by JSON pointer, values of bodies and messages. `apigenie-server session export DIR --har FILE` writes a session's HTTP exchanges, GraphQL operations and gRPC calls as HAR 1.2, in order, with the test of each entry. `--record-dir` and `--record-har` are unchanged. The design is ADR-168 ([Session recording](https://apigenie.pl/docs/reference/server/recording#session-recording)). - `apigenie-server --replay DIR` replays a recorded session for a test suite, without the real servers: each request gets the next unused recorded exchange of its test that matches it, so the same request twice in a test gets the first recorded answer, then the second. The test is the `X-Apigenie-Test` header (`x-apigenie-test` metadata for gRPC); untagged requests share one test drawing from the whole session; `POST /__apigenie/replay/reset {"test": ...}` restarts a test's counters. Matching leaves out dates, the `readOnly` fields of OpenAPI request bodies, volatile headers and what `--replay-ignore HEADER|/POINTER` names. `--replay-missing` says what a request none matches gets: `fail` (a 502 problem naming the closest recording and the differences, the default), `generate` (the mock's answer) or `passthrough` (`--proxy-to`'s, and with `--replay-update` the run replaces the session). Every protocol replays: HTTP, GraphQL operations and subscriptions, AsyncAPI WebSocket, MQTT and HTTP channels (the recorded messages as the server's side, in order) and gRPC calls, bidirectional streams in their recorded interleaving. When the server stops it reports the exchanges never replayed and the requests that matched none, and exits with status 5 if there are any; `GET /__apigenie/replay` gives the report at any time, and `replay:` configures it all. The reference page has a Playwright example. The design is ADR-169 ([Session replay](https://apigenie.pl/docs/reference/server/recording#session-replay)). ### Changed - `apigenie` and `apigenie-server` are about 360 KB smaller: Mbed TLS is built with only what their TLS uses (TLS 1.2 and 1.3 with certificates, AES-GCM and ChaCha20-Poly1305, x25519 and the NIST P-256, P-384 and P-521 curves). HTTPS, WSS, gRPC and MQTTS servers that offer only static RSA or DHE key exchange, or only other ciphers, can no longer be reached by `--proxy-to` or `apigenie test`; the handshake fails with a fatal alert. ADR-104. - **`schema-format-type-mismatch` and `schema-format-defined` follow the OpenAPI format registry**, in the OpenAPI, AsyncAPI and Swagger linters, and accept the formats of `openapi.custom_formats`. `schema-format-type-mismatch` used to check a fixed list of formats; it now checks every registry format (`int8` on a string, `date-time-local` on an integer, ...), so existing specifications can get new errors. Its messages say which values the format is for (`Schema type and format do not match: "int8" is a format of number values`). Some pairs it used to report are accepted now, as the registry allows them: `int64` and `uint64` on strings, `decimal` on strings and numbers, an integer format on `type: number`. `schema-format-defined` accepts the registry's integer formats (and `unixtime`) for integers and its number formats (`decimal`, ...) for numbers. The Swagger linter keeps to the formats Swagger 2.0 defines. - Declarative lint rules with `severity: info`, `hint`, `2` or `3` report hints instead of warnings. - `apigenie-generator server orpc` meets the codegen conformance bar of the other servers: Level 1 runs on OpenAPI 3.0, 3.1 and 3.2, and Levels 2 (tsc, ESLint) and 3 (`apigenie test` against the generated server) are wired, with only QUERY and COPY, which oRPC doesn't route, expected to fail; it is no longer listed as not settled in `docs/experimental.md`. The generated server now reads what oRPC doesn't decode by itself: cookie parameters, `content: application/json` parameters, a path segment of several parameters (`/labels/{labelId}.{extension}`), JSON media types other than `application/json` and JSON Lines bodies (parsed by the server), form fields converted to their types, and file uploads; bodies and responses take every media type of the operation, with binary responses as `Blob`s and `text/event-stream` as an `eventIterator()` of the `itemSchema`. A discriminator's `defaultMapping` selects the default option, operations with servers of their own are also served at their paths, `4XX`/`5XX` ranges and `default` responses become errors, `writeOnly` properties are left out of responses, and the handler stubs and `server.ts` pass typescript-eslint's recommended rules (regenerate `server.ts` and the handlers, which are written once, to get them). - The Zod schemas of `generate schema zod`, `server mcp` and `server orpc` check `unevaluatedProperties: false` against the properties the schema and its `$ref`, `allOf` and conditional schemas declare, instead of ignoring it with a warning: closed allOf subtypes such as Person or ParcelShipment reject unknown properties. - `apigenie-server`'s status (`GET /__apigenie`) counts the clients' requests only: the admin API's and the dashboard's own exchanges and CORS preflights are no longer in `requests` (ADR-167). - XML bodies of `apigenie-server`, its validating proxy and `apigenie test` (ADR-130) changed in three ways, found serving SOAP envelopes (ADR-164): - Child elements are written in the order the schema declares its properties, as XML Schema sequences require. Before, generated values put required properties first. - An element with the local name of a property but in another namespace than the property's `xml.namespace` is no longer taken for it. It is kept as `{namespace}name`, so `additionalProperties: false` reports it and the property counts as missing. - A request without `Accept` (or with `*/*`) gets its response in the media type of its body when the response has it: a SOAP 1.2 request (`application/soap+xml`) gets a SOAP 1.2 envelope rather than the first media type listed. - **`diff` rates a component schema by where it is used.** An OpenAPI component schema referenced only from parameters and request bodies (following the references between schemas, in either document) gets the `request` rules, one referenced only from responses the `response` rules; before, every component schema got the stricter of the two, so removing a property from a request-only schema, or adding a required one to a response-only schema, was breaking. Schemas used both ways, or not at all, are rated as before. Callbacks and webhooks swap the directions, as they always did. - The GraphQL contract checks of `apigenie test` and of `apigenie-server`'s GraphQL proxy warn about field errors (`response.field-error`): every error of an operation the server ran, next to `data` that is `null` or partial. Before, such answers passed silently. A server answering every field with an error passed `apigenie test --generate` with no violations. `--fail-on warnings` fails on them; `--severity` or `contract.severity` changes the level. Errors without `data` stay `response.request-error`. - `apigenie-mock` is renamed `apigenie-server`, with `apigenie-mock` and the `APIGENIE_MOCK_*` variables kept as deprecated aliases until 1.1, and the `mykulyak/apigenie-server` Docker image (see Upgrading). - `i18n apply` translates only the texts `i18n extract` extracts from OpenAPI, Swagger and AsyncAPI specs: a key pointing to another string, such as an `operationId` or a URL, is now reported as addressing nothing (a warning, an error with `--strict`) instead of being applied, and a key pointing to an object is no longer an error. The spec must be valid. - The OpenAPI reader reads the schemas under `$defs`, `dependentSchemas` and `additionalItems` as schemas, so `lint` rules, `generate` and the other commands see them; `$defs` and `dependentSchemas` are written after `patternProperties`. - Loading translations into the `Translator` (`apigenie-generator docs --i18n`) is atomic: an invalid file changes nothing, and the error names the locale and the key. Empty translations are skipped, so the source text is shown. - JUnit reports (`--report-junit` of `apigenie-server` and `apigenie test`) escape element content and attribute values separately: quotes in `<failure>` and `<system-out>` text are written as they are, line breaks in attribute values as ` `, and characters XML can't carry as U+FFFD instead of `?`. - `response.body.unvalidatable` no longer covers XML bodies, which are now checked. - File errors name their cause: "Failed to open file: openapi.yaml (not found)." instead of "Failed to open file: openapi.yaml.". - The notes "not checkable over MQTT 3.1.1" of `apigenie test` appear only for regions that speak MQTT 3.1.1; over MQTT 5 header correlation ids and reply addresses are checked. A broker's MQTT 5 refusal names its reason code (`reason code 0x86 (bad user name or password)`). ### Deprecated - `version` in the contract report of `apigenie-server` and in the `apigenie test` report: it duplicates `formatVersion` and will be removed in the next release. ### Removed - `apigenie credits` no longer lists TinyXML2, which API Genie stopped using long ago. ### Fixed - Bidirectional gRPC session replay preserves recorded response order when several requests arrive before the initial replies are sent, including when mock latency delays those replies. - Format checks of numbers: `format: int32`, `int64`, `float` and `double` were only applied to strings, so they rejected every string and never checked a number. A format now applies to its JSON types: int32 checks that a number is an integer in range (1.0 counts), and a string under it is left to `type`. `format: password` no longer rejects an empty string. - The gRPC answers `apigenie-server` generates set the fields marked `(google.api.field_behavior) = REQUIRED`, messages, lists and maps included, and not to their default values, so a validating proxy in front of the mock no longer reports `response.message.incompatible` for its own answers; fields marked `INPUT_ONLY` are left out. The requests of `apigenie test --generate` for `.proto` files set REQUIRED fields too and leave out `OUTPUT_ONLY` ones. A REQUIRED field whose message would contain itself stays optional. - The gRPC checks of `apigenie-server` (mock and `--proxy-to`) and `apigenie test` report a field whose wire type isn't its declared type's, such as a string where the `.proto` file declares an `int64`. Decoding drops such a field, as protobuf parsers do, so the message used to pass as if the field were absent. It is now `request.message.incompatible` or `response.message.incompatible` (code `wire-type`), at the field's location, and the mock in enforce mode refuses such a request with INVALID_ARGUMENT. - `@mykulyak/apigenie-docs` is published on npm (2026-10-11, `docs-0.1.0`). The 0.9.0 release notes said that the web components were "on npm" before they had been published, and under their old name. The release gate now installs and builds a generated docs project against the npm registry, so a CLI can't be released while the package it depends on is missing or out of range. - `format --output` with more than one input, or with an output file of an unknown extension, failed with an empty error message; it now says what's wrong. - `license --library` with an unknown name printed its error on the standard output. - `apigenie-server` answered `Accept: application/xml` with a JSON body under an XML `Content-Type`. - Paths longer than 260 characters work on Windows, without the system-wide long-path setting. - `test import --output` no longer fails when the output directory's name contains a dot (`--output api.v2`): the directory used to be mistaken for a file and left uncreated. - `lint --fix` and the other writers that replace a file in place create their temporary file exclusively, next to the target, and never leave it behind. - Faker's IBANs have valid check digits, routing numbers a valid ABA checksum, `book.isbn` a valid ISBN-13 check digit, and Polish, US, Spanish and British national ids follow their rules. - Faker's full names use one sex for first and last names, female middle names are generated, git commit dates name their own weekday, and usernames get their `.`, `_` and `-` separators back. - JSON output writes empty objects and arrays as `{}` and `[]` instead of spreading them over three lines with a blank one in between (`format`, `diff` and `changelog` JSON reports, `lint --formatter json` and `sarif`, docs bundles). - `property_order.paths` was ignored: `/paths` was ordered by the default order. - `property_order.reference` was never applied: Reference Objects are recognized by their `$ref`, except in schemas, where `$ref` is a keyword, and in path items that have their own operations. - The error for an `openapi.custom_formats` that is not an array said an object was expected; errors in the configuration file now name the file and the position. - `apigenie-server` named no file in its error for an invalid configuration file that it found itself. ## 0.9.0 (2026-10-10) API Genie 0.9.0 translates OpenAPI, Swagger 2.0, AsyncAPI, Protobuf and GraphQL files, and its mock server (`apigenie-mock`, now `apigenie-server`) mocks and contract-checks HTTP, WebSocket, MQTT, gRPC and GraphQL APIs. The new GitHub Action `mykulyak/api-genie-action` installs the CLI in workflows on Linux, macOS and Windows. ### Highlights - **Translations for all five standards.** `apigenie i18n extract` and `i18n apply` work on OpenAPI, Swagger 2.0, AsyncAPI, Protobuf and GraphQL files: the texts are extracted keyed by JSON pointers, declaration names or schema coordinates, and translations are put back without touching the rest of the file ([i18n](https://apigenie.pl/docs/reference/cli/i18n)). - **Contract testing across OpenAPI, Swagger, AsyncAPI, gRPC and GraphQL, with TLS.** `apigenie test` runs `.http` files (HTTP, gRPC, WebSocket, MQTT and GraphQL requests) and generated requests against a live API, and `apigenie-mock --proxy-to` sits between clients and a real server or broker (HTTP, WebSocket, MQTT, gRPC, GraphQL), checking every request and response against the contract. Both report coverage, JSON and JUnit reports, and fail CI with `--fail-on` and `--min-coverage`. TLS is supported throughout: the mock serves HTTPS, WSS and gRPC over TLS (`--tls-cert`, `--tls-key`), and requests and upstreams can be `https://`, `wss://` and `mqtts://`, verified against the system's CA certificates (`--ca-cert`, `--insecure`) ([test](https://apigenie.pl/docs/reference/cli/test), [mock server](https://apigenie.pl/docs/reference/server)). - **Code generation for five stacks.** Clients and servers for TypeScript (fetch, Express, oRPC, WebSocket, Kafka on KafkaJS, Zod), Python (httpx, FastAPI, FastStream), Go (`net/http`, Kafka), Java (Spring clients and servers, Kafka) and C# (`HttpClient`, ASP.NET Core, Kafka), from OpenAPI 3.0–3.2 and, for event-driven APIs, AsyncAPI 3.x. Every target is checked by a conformance suite: snapshots, the target's own compiler and linter, and a run against `apigenie-mock --proxy-to`. The generators are a separate executable, `apigenie-generator`, installed with the CLI ([apigenie-generator](https://apigenie.pl/docs/reference/generator)). - **Web components for every spec type, and `generate docs`.** The `apg-*` custom elements (`@mykulyak/apigenie-web-components` on npm) document OpenAPI, Swagger 2.0, AsyncAPI, Protobuf/gRPC and GraphQL APIs, with Try it out for HTTP and GraphQL, built on the same engine as the CLI compiled to WebAssembly. `apigenie-generator docs` compiles any of these files, several at once, into a docs bundle that the components render into a static site (`npm install && npm run build`), with translations, the git changelog and example files; it replaces `generate doc html` (see Upgrading). ### Upgrading - **`apigenie generate` is now `apigenie-generator`.** The code generators moved out of `apigenie` into a separate executable, `apigenie-generator`, installed next to it by every archive and package, the npm package and Homebrew, and included in the `mykulyak/apigenie` Docker image (`docker run --entrypoint apigenie-generator ...`). Drop `generate` from the command line: `apigenie generate client fetch spec.yaml -o out` becomes `apigenie-generator client fetch spec.yaml -o out`. The options and the `commands.generate` section of the configuration file are unchanged; `apigenie generate` fails as an unknown command. The banners of generated files name the new command. The entries below still call the generators `generate <target>`. The design is ADR-123. - **`generate doc html` is replaced by `generate docs`**, with no alias. `apigenie-generator docs openapi.yaml -o docs` replaces `apigenie generate doc html openapi.yaml --output docs`; it takes several inputs of mixed families (OpenAPI, Swagger 2.0, AsyncAPI, GraphQL, Protobuf) and makes one site, and `-c/--config`, `--i18n LOCALE=FILE`, `--package-name` and `--package-version` keep their meaning. The output is no longer an Astro project but a docs bundle (`apigenie-docs.json` and `documents/<id>/document.<locale>.json`, ADR-122) with a `package.json` that depends on `@mykulyak/apigenie-web-components` instead of `@mykulyak/api-genie-doc-html-template`; `npm install && npm run build` still builds the static site, now into `dist/`, prerendered from the web components. `--bundle-only` writes the bundle alone, for a site built by other means. The CLI does not run Node. The configuration section `commands.generate.doc_html` is `commands.generate.docs`: `html_title_prefix` is `title`, `i18n.default_locale` and `i18n.prefix_default_locale` move to the top of the section (the locales come from `--i18n`), `changelog` keeps its name (also `--changelog`), and `documents` lists the inputs (`file`, `id`, `title`, `proto_paths`, `examples`). `pages`, `operations`, `resources`, `search`, `sidebar`, `html_meta`, `template`, `openapi_schema`, `request_code_examples`, `use_request_body_examples`, `generate_response_schema`, `use_response_examples` and `fail_on_generator_error` described the Astro layout and have no replacement: the site has the layout of `<apg-api-reference>` (navigation with search, one page per operation and schema), themed with the components' CSS custom properties and `::part()`. Generated Astro projects keep building with the template they depend on, but nothing regenerates them: run `generate docs` into a new directory. - **New dependency: Mbed TLS.** `apigenie` and `apigenie-mock` link Mbed TLS 3.6 (Apache-2.0) for `https://`, `wss://` and `mqtts://` connections; release binaries grow by about 0.9 MB. Builds from source get it from vcpkg (`mbedtls >= 3.6.2`). Verifying servers needs the system's CA certificates: the Docker images now include them; in your own minimal images install `ca-certificates`. `apigenie credits` and `apigenie license --library mbedtls` list it. - **Telemetry is opt-in.** The CLI no longer writes `.apigenie.telemetry` in the current directory, and sends nothing. Set `APIGENIE_TELEMETRY_FILE` to a path to keep a local telemetry log; old `.apigenie.telemetry` files can be deleted. - **`i18n` has subcommands.** `apigenie i18n FILE --output DEST` becomes `apigenie i18n extract FILE --output DEST`. - **`lint` fails on errors.** `lint` exits with status 1 when issues of severity `error` remain (after `--fix`), so CI jobs that ran it only for its report fail now; lower the severities in the configuration to keep them passing. - **`apigenie-mock --stubs`** with a GraphQL schema or an AsyncAPI document exits with status 2 instead of ignoring the option. ### Added - `generate docs` documents OpenAPI, Swagger 2.0, AsyncAPI, GraphQL and Protobuf files, several at once, as one static site: it writes a docs bundle (`apigenie-docs.json`; per document and locale the resolved document, or the documentation model of AsyncAPI, GraphQL and Protobuf files; with `--changelog` the git changelog, as `apigenie changelog` computes it; the example files next to a GraphQL schema and those listed in the configuration) and the npm project that renders it with `@mykulyak/apigenie-web-components` (`npm install && npm run build`): prerendered pages with declarative shadow DOM that hydrate in the browser, Try it out, a sitemap, a locale switcher for the `--i18n` locales, a changelog page and the examples. `--bundle-only` writes the bundle alone. Internal: the `docs_bundle` library (`compileDocsBundle`), `changelog_helpers` (the changelog of any family, shared with the `changelog` command), and `graphql_describe` and `protobuf_describe`, which write the documentation models that the `graphql` and `protobuf` WebAssembly modules used to write themselves, as `asyncapi_describe` does for AsyncAPI. The design is ADR-122. - `generate server spring` (OpenAPI) routes QUERY operations and `additionalOperations` such as COPY: their handlers carry `@ExtensionMethod("QUERY")`, which the generated `ExtensionMethodConfiguration` matches through a custom request condition of the request mapping (`WebMvcRegistrations`, or `WebFluxRegistrations` with `reactive=true`). `pipeDelimited` and `spaceDelimited` array query parameters are split on their separator (`@DelimitedParameter`), and query parameters with JSON `content` are read as JSON into their model (`@JsonParameter`), which is null and left unvalidated when the parameter is absent; both converters are registered by `ParameterConversionConfiguration`. Request media types whose bodies have different types get a handler each, named as the methods of `generate client java` (`updateShipment` for `application/merge-patch+json`, `updateShipmentWithJsonPatch` for the `application/json-patch+json` array). The new `ApiExceptionHandler` answers invalid requests with a 400 Problem (`type`, `title`, `status`, `detail` and, for constraint violations of the parameters, `errors` with the `name`, `path` and `message` of each), where a `ConstraintViolationException` used to answer 500. Conformance Level 3 of the target only expects the x-internal operation, which servers leave out, to fail. - `generate server aspnet` (OpenAPI) falls back to the default mapping of a discriminator (`defaultMapping`, or `x-defaultMapping` before 3.2): unions are read and written by the converters of `generate client csharp`, written next to the abstract record and attached with `[JsonConverter]` instead of `[JsonPolymorphic]`, so a missing or unmapped discriminator reads as the default type, and the discriminator may be anywhere in the object on .NET 8 too. Request media types whose bodies have different types get an endpoint and API method each, named as the methods of the C# client (`UpdateShipment` for `application/merge-patch+json`, `UpdateShipmentJsonPatch` for the `application/json-patch+json` array) and restricted to their media types with `Accepts<T>()`, so routing picks the endpoint by Content-Type; the JSON Patch array used to be bound as a `ShipmentPatch` object (400). Conformance Level 3 of the target passes with only the x-internal operation, which the server leaves out, expected to fail. - The codegen conformance runner decides that the x-internal operations of the fixture are expected to fail for servers that leave them out: `omitsInternalOperations` on a Level 3 entry of `tests/conformance/targets.json` (set for the ASP.NET and Spring servers) expects every request of those operations, the request set's and the generated one, to fail, instead of hand-written `expected` entries; a server that starts serving one still fails the level. - `generate client kafkajs` and `generate server kafkajs` generate TypeScript (Node.js) packages for the Kafka channels of AsyncAPI 3.x documents, on KafkaJS 2.2.4: the server for the described application (`KafkaApp`, taking a handler per received operation, with `start()` and `stop()`), the client for its counterpart (`KafkaClient`, with `connect()`, `listen<Operation>(handler)` and `close()`); `perspective` swaps either. Every sent operation gets a sender with a `send<Message>(message)` method per message, which validates the message, writes the constant headers (e.g. `ce_type`), the key and the topic, and, for an operation with a reply, sends the request with a new correlation id unless it has one and resolves with the typed reply, matched by correlation id on one reply consumer per operation (`ReplyTimeoutError` when none arrives in time). Received operations get handler interfaces with `on<Message>(message, record)` and `onUnknown`, dispatched by `ce_type` header, payload property or deduction; repliers return the reply, sent with the request's correlation id. Payloads are validated by dependency-free functions generated from the schemas (`MessageValidationError`), headers by their constraints. Avro payloads, topics with parameters and replies at runtime-expression addresses are skipped with a warning. Configured under `commands.generate.client_kafkajs` and `commands.generate.server_kafkajs` (`layout`, `import_extension`, `perspective`, `validation`); the design is ADR-120. The codegen conformance suite checks both commands in both perspectives at Levels 1 and 2 (`tsc` and ESLint) and, at Level 3, runs the client against the server on the Kafka service container both ways, as for Go and C#. - `generate client ws` and `generate server ws` generate the replies of operations whose `reply` is on the request's channel: the client gets typed `on<Message>` handlers for the reply messages and, when the messages have a correlation id in their payloads, `request<Operation>(payload, { timeoutMs })` resolving with the reply carrying the request's id; the server session gets `send<Message>` methods for them and `replyTo<Operation>(request, reply)`, which copies the request's correlation id into the reply. On the AsyncAPI conformance fixture, `requestPickup()` and `replyToRequestPickup()`. Replies on another channel or at a runtime-expression address are still reported as unsupported. - `apigenie test` sends WS regions to `wss://` and MQTT regions to `mqtts://` (or `ssl://`) URLs, with ports 443 and 8883 by default. Their certificates are checked as for `https://`, with SNI and the URL's host name, so `--ca-cert` and `--insecure` apply. MQTT regions send their `username` and `password` settings in CONNECT (MQTT 3.1.1). A setting the region doesn't give comes from `APIGENIE_MQTT_USERNAME` and `APIGENIE_MQTT_PASSWORD`. A refusal names the reason (bad user name or password, not authorized). Credentials show as `[redacted]` in the console and the JSON and JUnit reports, as OAuth 2 secrets do, and a URL's `user:password@` is shown as `***@`. These URLs used to fail with "speaks plain WebSocket/MQTT only", and the credentials were noted as not sent. MQTT 5 is still not supported. The design is the amendment of ADR-110. - `apigenie test` with an AsyncAPI `--spec` checks HTTP requests against the document's HTTP channels, with the code and checks of the validating proxy: the channel and operation by path and method (a `receive` operation's HTTP binding's method, GET for a `send` one) or by `# @operation`, a `receive` operation's body, query and header fields against its messages and a 2XX response against its reply, a `send` operation's response against its messages. The requests count for their operations in the coverage, which used to show them as not tested, and `--generate` sends one request per HTTP channel operation (to `--base-url`, a `ws://` URL taken as `http://`). A path of no HTTP channel is a note. Both `apigenie test` and `apigenie-mock --proxy-to` now check the `query` of an operation's HTTP binding (`operation.query.invalid`) and the header fields of a message's `headers` and HTTP binding `headers`, its traits' included (`message.headers.invalid`); responses other than 2XX are still not checked. The design is ADR-118, which amends ADR-110 and ADR-112. - `apigenie test` runs httpYac's OAuth 2 authorization instead of skipping it: `Authorization: oauth2 [GRANT] [PREFIX]` (and `openid`) with the `client_credentials`, `password` and `refresh_token` grants requests a token from `<prefix>_tokenEndpoint` (or the OpenID Connect discovery document of `<prefix>_issuer`) with the `<prefix>_clientId`, `_clientSecret`, `_scope`, `_audience`, `_username`, `_password` and `_useAuthorizationHeader` variables, keeps it for the run, requests it again (with its refresh token) when it expires, and sends `Authorization: Bearer <token>`. Token endpoints are reached like other requests, `https://` included (`--ca-cert`, `--insecure`); a refused token request fails its request, which isn't sent. The `authorization_code`, `implicit` and `device_code` grants are still skipped, with a reason naming the grant. With `--spec`, requests sent with a token are checked by the new `request.authorization.oauth2-scheme` and `request.authorization.oauth2-scope` warnings (the operation has no OAuth 2 scheme, the requested scopes aren't its). Tokens, client secrets, passwords and `Authorization` credentials show as `[redacted]` in the output, the reports and warnings. `apigenie test import` maps Postman's client credentials and password grants to these variables instead of disabling the requests. The design is ADR-117. - The `asyncapi` WebAssembly module (`asyncapi.mjs`, and `asyncapi.web.mjs` for browsers) exports `describe(text, {fileName, files})`. It returns the documentation model of an AsyncAPI 3.0 or 3.1 document as plain JSON (`{"apigenieAsyncAPI": 1, …}`): - servers, channels, operations and messages with their JSON pointers and source positions; - references followed and external files given in `files` bundled as `apigenie asyncapi bundle` does; - traits applied with JSON Merge Patch, and the defaults of the specification; - headers and payloads as schemas (other formats, such as Avro, kept with their `schemaFormat`), and a position table; - the problems found as `issues`. AsyncAPI 2.x is an error. It is built on the new `asyncapi_describe` library; the JSON Merge Patch of traits moved into the `asyncapi` library (`asyncapi/traits.hpp`), where the models generators use it too. ADR-119 has the design. - `apigenie-mock`, its validating proxy (`--proxy-to`) and `apigenie test --spec` take Swagger 2.0 documents: they convert them to OpenAPI 3.2 in memory, as `convert --to openapi32` does, each time the document is read, and write no file. Locations stay those of the Swagger file: the lines of warnings, the lines and JSON pointers of `x-apigenie-mock` problems, and the new `pointer` of each operation in the contract reports. What the conversion can only approximate is told once at startup as `info:` lines with the Swagger file's line and JSON pointer (`{"event":"info"}` with `apigenie test --formatter json`). Swagger 2.0 documents used to be refused with exit status 3. - `apigenie-mock --proxy-to mqtt://host:port` (or `mqtts://`, verified like `https://` upstreams) with an AsyncAPI document contract-tests a real MQTT broker: the mock's broker relays, each client getting a connection of its own to the broker with its identifier, version, clean start, keep-alive, will and credentials, and the broker's CONNACK and SUBACK. Every PUBLISH is checked against the topic's channel: what clients publish against its `receive` operations, with the QoS of their MQTT binding (`message.qos.unexpected`), what the broker delivers against its `send` operations (a channel without them: its `receive` operations and the replies sent there). In enforce mode invalid messages aren't forwarded (MQTT 5 clients get reason code 0x99). Wills, refusals and an unreachable broker (server unavailable) are passed on, clients stay connected across reloads, the log has `mqtt-connect` and `mqtt-disconnect` events, and coverage, `--report`, `--report-junit`, `--fail-on` and `--min-coverage` work as for WebSocket. `--proxy-to` can be repeated to proxy a WebSocket server and an MQTT broker at once (`proxy.target` takes a list). The design is ADR-112, which supersedes parts of ADR-097. - An AsyncAPI document's HTTP channels are proxied to the `http(s)://` or `ws(s)://` server of `--proxy-to` through the OpenAPI proxy's transport and checked against the AsyncAPI document: a `receive` operation's request body against its messages and a 2XX response's body against its reply, a `send` operation's response (GET) against its messages. In enforce mode invalid requests get 422 and invalid responses are replaced by 502; paths of no channel get 404 or 405. - The AsyncAPI checks have `channel.parameter.invalid`: a value of an address parameter (a topic level, a path segment) outside the parameter's `enum`, for WebSocket, MQTT and HTTP channels. - `mqtt::ClientConnection`, an MQTT 3.1.1 and 5 client on the event loop (over TLS too), and broker hooks that decide CONNECT and SUBSCRIBE later and let the owner relay instead of delivering. - `apigenie test` runs GraphQL requests instead of skipping them: `GRAPHQL URL` requests of httpYac and the JetBrains HTTP client (the query, then its variables as JSON after a blank line; `# @operation` is the `operationName`) and `POST` requests whose body is a query are sent as GraphQL over HTTP, and JSON `{"query": ...}` bodies as they are. With a GraphQL schema as `--spec` (`.graphql`, `.graphqls`, `.gql`), each operation is validated against the schema before it is sent (an invalid one fails its request, not the run, and isn't sent), and each response is checked as `apigenie-mock --proxy-to` checks it: the shape of `data` and `errors`, value types, `null` in non-null fields that no error explains, `__typename` of abstract types and schema drift. Coverage is per field and per root field (`--min-coverage` is the share of fields), and `--report` and `--report-junit` are the GraphQL contract report of `apigenie-mock` with the run's `tests` and `requests`. `--generate` sends one request per field of `Query` and `Mutation`, with required arguments made up from their types as the mock makes up values; `--base-url` is the endpoint. `--severity` takes the GraphQL checks. The design is ADR-111; the GraphQL contract report moved from the `apigenie-mock` executable into the `graphql_mock` library, with the same output. - `apigenie test` runs httpYac's `WS` and `MQTT` requests and checks their messages against an AsyncAPI 3.x `--spec`. A region connects to a `ws://` server or an `mqtt://` broker (MQTT 3.1.1; `topic`, `publish`, `subscribe`, `qos`, `retain` headers), sends the messages of its body (separated by `===`, `=== wait-for-server`) and waits for the server's until `# @expect N` came or `# @timeout` (`--message-timeout`, 5000 ms) passed; the messages received are the response, a JSON array (`?? body $[0].type == pickup.confirmed`, `?? body $.length == 2`, `response.messages` in scripts). The channel comes from the URL's path or the topic (`# @channel` names it); messages sent are checked against the channel's receive operations and messages received against its send operations, with the AsyncAPI proxy's checks. A message of a request/reply operation is paired with its reply, checked by the new contract checks `message.reply.missing` (warn) and `message.reply.uncorrelated` (error, a payload `correlationId` that differs); correlation ids and reply addresses in message headers are noted as not checkable over MQTT 3.1.1. Coverage per operation and message and the reports (`--report`, `--report-junit`, `--formatter json`, `--min-coverage`) are the AsyncAPI proxy's. `--generate` sends a region per WebSocket and MQTT channel with the receive operations' example messages, at `--base-url ws://...` and the new `--mqtt-url`. The design is ADR-110, extending ADR-136 and ADR-097. - `apigenie-mock --proxy-to` contract-tests a real gRPC server against its `.proto` file: the proxy checks the upstream's messages against their output types (also fields marked `[(google.api.field_behavior) = REQUIRED]`, under proto3's presence rules, and deprecated fields and enum values), its status (HTTP status, content type, `grpc-status`, the percent-encoding of `grpc-message`, `grpc-status-details-bin` as a `google.rpc.Status` whose code is `grpc-status`), the number of messages of unary calls and the `-bin` metadata, with check ids such as `response.message.incompatible` and `response.status.details-incompatible` that `contract.severity` changes. Locations name the field (`message[0]/items/2/sku`). It counts the calls of each service and method, and writes the contract reports the OpenAPI, GraphQL and AsyncAPI proxies write (`--report` with `"specification": "grpc"`, `--report-junit` with a test case per method, `--fail-on`, `--min-coverage` as the share of methods, exit status 5, `GET /__apigenie/contract`). `--strict` (or `grpc.validation.response: enforce`) checks each upstream message before forwarding it and fails the call with INTERNAL. The upstream is `HOST:PORT` (cleartext HTTP/2) or `https://host[:port]` (HTTP/2 over TLS). The design is ADR-109. - `apigenie test` sends `GRPC` requests of `.http` files (httpYac's `GRPC host:port/package.Service/Method` with the request message as a proto3 JSON body, metadata as headers) with a `.proto` file as `--spec`, its imports looked up in the new `--proto-path` directories. Unary and server-streaming calls are made over HTTP/2, cleartext or over TLS for `grpcs://` URLs (with `--ca-cert` and `--insecure`), and checked like the proxy's; a body that isn't a valid message fails the request with the field's path before it is sent. Assertions and scripts see the status code as `status` (`?? status == 0`), metadata and trailers as headers and the message as a JSON body (an array for server streaming). Client- and bidi-streaming requests are reported as skipped with a warning. `--generate --base-url HOST:PORT` (or `grpcs://HOST:PORT`) sends a request per method with a generated message. The reports are the gRPC contract report plus the requests (`grpc`, `grpcStatus`). - `apigenie-mock --tls-cert FILE --tls-key FILE` serves HTTPS, WSS and gRPC over TLS. Clients that ask for `h2` by ALPN, such as browsers and gRPC clients, get HTTP/2. The settings are also `tls.cert` and `tls.key` in the configuration, and `APIGENIE_MOCK_TLS_CERT` and `APIGENIE_MOCK_TLS_KEY`. A separate admin port uses the same certificate, and the MQTT broker stays cleartext. The startup line shows `https://` and `wss://` URLs and `"tls": true`. TLS 1.2 and 1.3 come from Mbed TLS; the design is ADR-104. - `apigenie-mock --proxy-to` reaches TLS upstreams: `https://` for the OpenAPI and GraphQL validating proxies, `wss://` for the AsyncAPI WebSocket proxy, and `https://host[:port]` for gRPC (HTTP/2 over TLS with ALPN `h2`, shown as `grpcs://`). Certificates are verified against the system's roots: the macOS keychains, the Windows ROOT store, the Linux CA bundle, or `SSL_CERT_FILE` and `SSL_CERT_DIR`. `--ca-cert FILE` (repeatable; `tls.ca_certs`, `APIGENIE_MOCK_CA_CERT`) adds authorities, and `--insecure` (`tls.insecure`, `APIGENIE_MOCK_INSECURE=1`) skips verification. A rejected certificate gets the usual 502 with the reason. - `apigenie test` sends `https://` requests, with the same `--ca-cert FILE` and `--insecure` options. Imported collections no longer need their HTTPS URLs pointed at a cleartext server. - `generate server go` also takes AsyncAPI 3.x documents and generates a Go module (Go 1.22) for their Kafka channels on franz-go (`github.com/twmb/franz-go/pkg/kgo`, pinned at v1.18.1, with a complete `go.sum`): structs, enums and sealed-interface unions with `json` tags and `Validate` methods for the payloads, a struct per message (key, typed headers, payload) validated before it is sent and after it is received, and an `App` with a consumer group and a handler interface per receive operation (several messages told apart by a constant payload property or header, e.g. the `ce_type` of binary-mode CloudEvents; others go to `OnUnknown`) and a typed sender per send operation. Request/reply operations with a reply channel return the reply from the sender, matched by its correlation id, and repliers send the handler's reply with the correlation id copied. Consumer groups and client ids come from the Kafka operation bindings. `cmd/<package>/main.go` takes the brokers from `-brokers` or `KAFKA_BROKERS`, wires stub handlers and stops cleanly on SIGINT and SIGTERM. Channels of other protocols are skipped with an info line, Avro payloads with a warning. Configured under `commands.generate.server_go.asyncapi`; the design is ADR-105. The codegen conformance suite checks both perspectives at Levels 1 and 2 and, at Level 3, has the application and the counterpart exchange the fixture's Kafka messages on the conformance workflow's new Kafka service container, including the `requestLabelRender` reply, an unknown `ce_type` and an invalid payload. - `generate client go` also takes AsyncAPI 3.x documents and generates a Go Kafka client package (a Go 1.22 module on franz-go v1.18.1, without `main.go`), by default for the counterpart of the described application and with `perspective: application` for the application itself. `NewClient(options)` creates the producer, `Close()` closes every client, and `Options` takes the brokers, a client id and franz-go options passed to every client. A send operation gets `Send<Operation>(ctx, message)`, which writes the constant headers (e.g. `ce_type`), the key and the topic from the bindings; with several messages it takes an interface they implement. A request/reply operation gets a blocking `Request<Operation>(ctx, message)` that sets a fresh correlation id, waits for the reply until the context's deadline and returns it typed (an interface of the replies when there are several), with one reply consumer per operation shared by all requests. A receive operation gets `Listen<Operation>(handler)`, consuming in the background with the server's dispatch, validation and repliers. Configured under `commands.generate.client_go.asyncapi`; the design is ADR-106. The codegen conformance suite checks both perspectives at Levels 1 and 2 and, at Level 3, runs the client against `generate server go` on the Kafka service container both ways: the server's events and label requests reach the client's listeners and replier, and the client's sends and requests (concurrent ones and one ending at its context's deadline included) reach the server's handlers. - `Options.ClientID` of the Go Kafka code of `generate server go` and `generate client go` replaces the producer's client id. - `generate server aspnet` also takes AsyncAPI 3.x documents and generates an ASP.NET Core project (.NET 8) for their Kafka channels on Confluent.Kafka 2.15.1, so a REST API and its events can live in one application: the payload models of `generate client csharp` (records, enums, unions read by converters of the System.Text.Json source-generated context), a record per message (key, typed headers with DataAnnotations, payload) validated before it is sent and after it is received, and per receive operation a handler interface, registered with dependency injection and resolved per record, and a consumer hosted as a `BackgroundService` in the operation's consumer group (several messages told apart by a constant payload property or header, e.g. the `ce_type` of binary-mode CloudEvents; others go to `OnUnknownAsync`). Records are committed once their handler returns and handled again when it throws; invalid records are logged and committed. Each send operation gets a typed sender; request/reply operations with a reply channel return the reply from `Request<Message>Async`, matched by correlation id, and repliers send the handler's reply with the correlation id copied. The `AsyncApi:Kafka` section of `appsettings.json` holds the brokers, topics, group and client ids (from the Kafka operation bindings) and further librdkafka properties, overridable by environment variables; stopping the host closes the consumers. Configured under `commands.generate.server_aspnet.asyncapi`; the design is ADR-107. The codegen conformance suite checks both perspectives at Levels 1 and 2 and, at Level 3, runs the application and the counterpart on the conformance workflow's Kafka service container, as for Go. - `generate client csharp` also takes AsyncAPI 3.x documents and generates a C# Kafka client library (.NET 8 class library on Confluent.Kafka 2.15.1), by default for the counterpart of the described application and with `perspective: application` for the application itself. `<Name>KafkaClient` has a producer per channel it sends to, whose `Send<Message>Async` writes the constant headers (e.g. `ce_type`), the key and the topic from the bindings; a request/reply operation gets `Request<Message>Async`, which sets a fresh correlation id, waits for the reply with a timeout (`ReplyTimeout` or an argument) and a `CancellationToken`, and returns it typed (an interface of the replies when there are several), with one reply consumer per client and a pending request per correlation id. Receive operations get the handler interfaces and hosted consumers of `generate server aspnet`, with its dispatch, validation and repliers. `Add<Name>KafkaClient(configuration, configure)` binds the options to the `AsyncApi:Kafka` section and registers the client and its producers, and its builder's `Add<Operation>Handler<THandler>()` registers a handler with its consumer. `--package-name` is the root namespace (default: the title followed by `.Client`), as for OpenAPI. Configured under `commands.generate.client_csharp.asyncapi`; the design is ADR-108. The codegen conformance suite checks both perspectives at Levels 1 and 2 and, at Level 3, runs the client against `generate server aspnet` on the Kafka service container both ways, including concurrent requests, a request timing out and a cancelled one. - `generate client java` also takes AsyncAPI 3.x documents and generates a Java Kafka client library (a Maven project for Java 21 on the Apache Kafka client 4.1.0, Jackson and Hibernate Validator, without Spring), by default for the counterpart of the described application and with `perspective: application` for the application itself. It shares the message records, models, dispatch, validation and repliers of `generate server spring`. `<Name>KafkaClient` (with `<Name>KafkaClientOptions`: servers, topics, client and group ids, reply timeout, producer and consumer properties) gets `send<Message>(message)` per send operation, writing the constant headers (e.g. `ce_type`), the key and the topic from the bindings; `<operation>(message[, timeout])` per request/reply operation, which sets a fresh correlation id (header, payload pointer or `kafka_correlationId`) and completes with the typed reply, with one group-less reply consumer per client; and `listen<Operation>(handler)` per receive operation, consuming on a virtual thread with `onUnknown` and `onError` defaults. `--library` and `-p` are errors with AsyncAPI input. Configured under `commands.generate.client_java.asyncapi`; the design is ADR-121. The codegen conformance suite checks both perspectives at Levels 1 and 2 (`mvn package`, `javac -Xlint:all -Werror`) and, at Level 3, runs the client against `generate server spring` on the Kafka service container both ways, including concurrent requests and a timeout. - `generate client python` also takes AsyncAPI 3.x documents and generates an asyncio Kafka client package on aiokafka with the Pydantic models of `generate server faststream`, by default for the counterpart of the described application and with `perspective: application` for the application itself. `messages.py` has a dataclass per message (payload, headers, key) with headers models and their constant headers; `<Name>KafkaClient`, an async context manager, gets `send_<message>()`, `request_<operation>(message, *, timeout=None)` (fresh correlation id, typed reply, one group-less reply consumer per client, `TimeoutError`) and `listen_<operation>(handler)` with abstract handler classes (`on_unknown` and `on_error` defaults), by the Kafka rules of ADR-102. The package passes `mypy --strict` and ruff, and depends on `aiokafka[lz4,snappy,zstd]`, so it reads topics other producers compress. Configured under `commands.generate.client_python.asyncapi`; the design is ADR-121. The codegen conformance suite checks both perspectives at Levels 1 and 2 and, at Level 3, runs the client's counterpart against the Kafka broker of `generate server faststream`'s application and the client's application against its counterpart on the Kafka service container, including concurrent requests and a timeout. - `generate server spring` also takes AsyncAPI 3.x documents and generates a Spring Boot application (Maven project) for their Kafka channels: a record per payload and per message (key, payload, headers) with Jackson and Jakarta Bean Validation annotations, a `@KafkaListener` and a handler interface per receive operation (several messages told apart by a constant payload property or header, e.g. the `ce_type` of binary-mode CloudEvents), and a sender over `KafkaTemplate` per send operation. Request/reply operations with a reply channel use `ReplyingKafkaTemplate`, and replies carry the correlation id from the `correlationId` location. Topics, group and client ids (from the Kafka bindings) and servers go to `application.yaml`; message headers are merged with those of their traits as AsyncAPI does. Constraints Bean Validation can't express (draft-07 `dependencies`, `if`/`then`/`else`, tuples) become comments. Channels of other protocols are skipped with an info line, Avro payloads with a warning. Configured under `commands.generate.server_spring.asyncapi`; the design is ADR-102. The codegen conformance suite builds both perspectives at Level 2 and, at Level 3, has the application and the counterpart exchange the fixture's Kafka messages on an embedded broker (`@EmbeddedKafka`), including the `requestLabelRender` reply. - `generate client go` generates a Go client for the `net/http` package of Go 1.22 from an OpenAPI 3.x document, using the standard library only. One `Client` over a configurable `*http.Client` takes functional options (base URL, request editors, user agent, an option per security scheme such as `WithAPIKey`), and has a method per operation and request media type taking a `context.Context` first. Each method returns a response struct with one typed field per documented status and media type (`JSON200`, `ApplicationProblemJSON404 *ProblemDetails`) and the raw `*http.Response`; statuses of 400 and above also return an `*APIError` with the RFC 9457 problem details. `text/event-stream` and `application/jsonl` responses are iterators typed from `itemSchema` (`x-itemSchema` in 3.0 and 3.1), binary responses stay open as `io.ReadCloser`, multipart bodies are structs whose binary parts (from `contentMediaType` or `format: binary`) are `File` values honouring `encoding`, `content` parameters are sent as JSON, operation and path servers are honoured (`WithOperationServers(false)` ignores them), credentials go to the operations that accept them, and `x-internal` operations are left out. Types and validation are shared with `generate server go`. Configured under `commands.generate.client_go`. - `generate client csharp` generates a C# client of an OpenAPI 3.0, 3.1 or 3.2 document for .NET 8 (or 9 and 10), built on `HttpClient` and `System.Text.Json`: a class library with one client per tag taking the `HttpClient` in its constructor (`client.Shipments.ListShipmentsAsync()`), a client of the whole API, and `Add{Api}Client()` registering them with `IHttpClientFactory`. Methods are `async` with a `CancellationToken`; they return the body of the success response, or a `*Result` by status when statuses have different bodies, and throw `ApiException` with the RFC 9457 problem details of error responses. Every parameter style is supported, objects and `content` parameters (as JSON) included; bodies are JSON, text, binary, forms and multipart with `FilePart`s for `format: binary` and `contentMediaType` fields; other media types of bodies and responses are methods of their own (`UpdateShipmentJsonPatchAsync`); server-sent events and JSON Lines are `IAsyncEnumerable<T>` typed by `itemSchema` (or `x-itemSchema`). Operation and path servers are honoured, `x-internal` operations left out, and bearer, basic, OAuth 2.0, OpenID Connect and API key credentials sent by `DelegatingHandler`s. The models are those of `generate server aspnet`, with a source-generated `JsonSerializerContext` and converters that read every `oneOf`/ `anyOf` with a discriminator wherever the discriminator is, falling back to `defaultMapping` (or `x-defaultMapping`). The code builds with `-warnaserror` and the .NET analyzers. Configured under `commands.generate.client_csharp`. - The OpenAPI reader reads `itemSchema` of media types and `defaultMapping` of discriminators (OpenAPI 3.2), and the writer keeps them. - `apigenie test import COLLECTION -o DIR` imports Collection Format v2.0/v2.1 JSON exports into folder-based `.http` tests with environments, bearer/basic/API-key references, upload assets, inherited scripts and a marker-gated QuickJS `pm` compatibility subset. Status-only tests become `??` assertions; unsupported script blocks are preserved as comments with source-line warnings, and OAuth 2 requests are disabled. `--spec` adds operation bindings and saved-response example overlays without editing the spec. `--environment` can be repeated; `--force` opts into replacing generated files. Authentication secrets are stored only in the generated environment file. - `apigenie test` reads `QUERY` requests (the safe method with a body of OpenAPI 3.2) in `.http` files, and `--spec` takes OpenAPI 3.2 documents. - `apigenie test` runs the requests of `.http` files (the httpYac flavour, which the JetBrains HTTP client and VS Code's REST Client read too) against a live server and validates every request and response against an OpenAPI document (`--spec`) with the checks of `apigenie-mock`'s validating proxy. Files have `###` regions, `{{var}}` variables, `@var = value` definitions, `# @name`/`# @ref`/`# @forceRef` chaining with `{{name.response.body.$.id}}` references, `{{ }}` scripts and JetBrains `> {% %}` handlers (QuickJS: `request`, `response`, `client`, `exports`, `test`, `assert`, `console`), `??` assertions, and `.env` and `http-client.env.json` environments (`--env`, `--env-file`, `--var`). Requests are bound to operations by method and path; `# @operation <operationId>` picks one, `# @operation off` skips the checks. `--generate` sends one request per operation, from the document's examples or generated values. The run fails with exit status 5 when a request fails or when the contract gate (`--fail-on`, `errors` by default, and `--min-coverage`) does; `--report` and `--report-junit` write `apigenie-mock`'s contract report with the requests added. Unknown directives are warnings. GraphQL, gRPC, HTTPS and OAuth 2 are not supported yet. - `--strip-comments` for `format`, `overlay` and `lint --fix` drops the comments of the files they write, which they keep otherwise (ADR-093): YAML comments of OpenAPI, Swagger and AsyncAPI documents, comments of Protobuf files and `#` comments of GraphQL documents, whose descriptions are kept. - `i18n apply` applies translations to Protobuf (`.proto`) and GraphQL (`.graphql`, `.graphqls`, `.gql`) files, keyed as `i18n extract` writes them: the leading comments of Protobuf declarations and the descriptions of GraphQL definitions are rewritten in place, in their style (`//` lines, `/* */` blocks, block or quoted strings), and every other byte of the file is kept, comments included, so applying untranslated texts returns the file unchanged. Keys addressing no comment or description are warnings, or errors with `--strict` (ADR-103). - `i18n extract` extracts the texts of Swagger 2.0 documents, recognized by their `swagger` property, as it does for OpenAPI: titles, summaries and descriptions keyed by JSON pointers, which `i18n apply` puts back (ADR-103). - `i18n apply --strip-comments` drops the YAML comments of a spec or the `#` comments of a GraphQL file (descriptions are kept), as `format`, `overlay` and `lint --fix` do (ADR-093); it is refused for Protobuf files, whose translated texts are comments. - `i18n apply` applies translations to OpenAPI and AsyncAPI documents (JSON or YAML): each key of a translation file, a JSON pointer as `i18n extract` writes it, has the string it points to replaced by its value, and everything else is kept, YAML comments included. `--translations` can be repeated (later files override earlier ones), the result goes to `--output` or the standard output in the input format or that of `--format`, and keys pointing to nothing are warnings, or errors with `--strict`. - `apigenie-mock --proxy-to ws://host:port` with an AsyncAPI document is a validating proxy for contract testing of a WebSocket API: clients of a WebSocket channel are relayed to the real server (handshake headers and subprotocol passed on, 502 or 504 when it can't be reached), and every message of both sides is checked against the channel's `receive` (client messages) and `send` (server messages) operations. Violations carry checks such as `message.incompatible` and `channel.send.undeclared`, go to the log, and `--strict` keeps invalid messages from going on (the client gets an `invalid-message` or `invalid-upstream-message` problem instead). Coverage counts each message of each operation; `--report`, `--report-junit`, `--fail-on`, `--min-coverage` and `GET /__apigenie/contract` work as for OpenAPI. HTTP channels and the MQTT broker keep being mocked. `contract.severity` accepts the new checks. - `apigenie-mock --proxy-to ... --record-dir DIR` with an OpenAPI document writes each exchange the server answered as a stub file (`getPet-1.yaml`, or `GET_health-1.yaml` for a route of no operation: the request's method, path, query, headers and body, and the response's status, headers and body), which `--stubs DIR` (or `stubs:` in the configuration) replays without the server: before the document's examples, after `Prefer` and scenario rules, with `X-Apigenie-Mock-Source: stub:getPet-1`. `--record-har FILE` writes the whole session through the proxy, the mock's own answers included, as a HAR 1.2 file when the server stops, with `comment` (`proxy` or `mock`) and `_apigenie` (source, operation, upstream status, violations) on each entry. Both hide the values of `Authorization`, `Cookie`, `Set-Cookie`, `Proxy-Authorization` and `X-Api-Key`; `proxy.redact` sets the list. Also `proxy.record_har` and `APIGENIE_MOCK_RECORD_HAR`. - `apigenie-mock --proxy-mode fallback` with an OpenAPI document and `--proxy-to`: every request still goes to the real server, but when the server can't be reached, doesn't answer in time, or answers 404 or 501 for an operation of the document, the mock answers as it would without `--proxy-to` (examples, generated data, scenarios, `Prefer`). Such answers carry `X-Apigenie-Mock-Upstream-Status`, are logged with `fallback: true` and aren't `response.status.unknown` violations. The contract report tells the server's answers from the mock's: `summary.sources`, each operation's `sources` and `mockedResponses`, two JUnit properties and a `Sources:` line in the summary. Configured under `proxy.mode`. - `apigenie-mock` serves OpenAPI 3.2 documents: the `query` method and the methods of `additionalOperations` (such as `COPY`) are routed, validated and recorded in contract reports like the others. Streams described by `itemSchema` are answered with an empty body. - A codegen conformance suite runs every OpenAPI generator on one shared, realistic OpenAPI 3.2 fixture, the Carpet Express Shipping API (`data/fixtures/openapi`, with its 3.1 and 3.0 variants, Spring and mock overlays and a feature catalog). Level 1, part of every ctest run, compares each generator's output byte for byte with a checked-in snapshot and checks a per-target manifest of the features it doesn't support yet. Levels 2 and 3 type-check and lint the output with the target's own toolchain and run the generated code against the fixture's contract (clients behind `apigenie-mock --proxy-to`, servers with `apigenie test --generate` and a hand-written request set), for the fetch, C#, Go, Java and Python clients and the FastAPI, Spring, Go, ASP.NET and Express servers, and the zod schemas at Level 2, in a Linux workflow that runs on generator changes and on demand. The results are in `docs/codegen_conformance.md`; the design is ADR-098. - The codegen conformance suite covers the AsyncAPI generators: `generate client ws` and `generate server ws` run on the Carpet Express Event Platform (`data/fixtures/asyncapi`), the AsyncAPI 3.0 event side of the same service (Kafka, WebSocket, MQTT 5, HTTP and AMQP channels, three request/reply styles, traits with a merge trap, bindings for all five protocols, draft-07 schemas), with a mock overlay and a feature catalog. Level 1 compares their output with snapshots and checks their manifests (the twelve non-WebSocket channels don't concern them; the reply of a request/reply operation is not generated yet). Level 2 type-checks and lints the generated packages; Level 3 drives the generated client and server through `apigenie-mock` as a validating WebSocket proxy. The matrix in `docs/codegen_conformance.md` has an AsyncAPI section; the design is ADR-100. - `apigenie generate server faststream` generates a Python [FastStream](https://faststream.ag2.ai) application from the Kafka, AMQP (RabbitMQ) and MQTT channels of an AsyncAPI 3.x document: a broker per server (URL from an environment variable), a subscriber per receive operation (topics and patterns, consumer groups, queues, exchanges and routing keys, QoS from the bindings; several messages dispatched by a constant property) calling a handler you write in `handlers.py`, which regenerating keeps, and a publisher with a typed publish function per send operation. Payloads and headers become Pydantic v2 models, the same as `generate client python`'s, with trait headers merged; headers are typed `Header()` parameters. Requests wait for their reply on the document's reply channel by correlation id; reply addresses in headers become `reply_to` arguments. WebSocket and HTTP channels and Avro payloads are skipped and reported. Configuration is `commands.generate.server_faststream`; it is in the codegen conformance suite at Levels 1 to 3. The design is ADR-101. - The codegen conformance suite runs `generate server faststream` at Level 3: the conformance workflow has RabbitMQ (with the fixture's virtual host) and Mosquitto service containers, pinned by digest, next to its Kafka one, and the generated application runs on the three brokers next to a counterpart. The counterpart publishes the fixture's examples (MQTT courier positions and sorter scans, AMQP customs decisions) to the application's handlers, receives what the application publishes (shipment events and label requests on Kafka, job offers on MQTT, customs filings on the `customs` exchange) and answers the label requests on their reply topic. The MQTT traffic goes through apigenie-mock's MQTT bridge, whose contract report checks it; the Kafka and AMQP messages and the MQTT 5 user properties are checked against the fixture in the harness (`checkMessages()`, ajv). Every item passes. - `apigenie-mock --proxy-to http://host:port/graphql` with a GraphQL schema is a validating proxy for contract testing: GraphQL requests are checked against the schema (graphql-js's rules, variables, deprecated usage) and forwarded to the real server, whose answers are checked field by field against the schema and the request's selection set (missing and unexpected fields, nulls no error explains, scalar, enum and `__typename` values, lists, the shape of `errors`, statuses and media types). The proxy also introspects the server and reports where its schema differs (`schema.drift`, `schema.addition`). Violations carry checks such as `response.data.incompatible`, go to the log and `X-Apigenie-Mock-Violations-Detail`, and `--strict` answers bad requests itself and replaces bad answers (502). Field and root field coverage, `--report`, `--report-junit`, `--fail-on` and `--min-coverage` work as for OpenAPI. `--proxy-mode fallback` lets examples, scenarios and scripts answer first, and `--record-dir` writes the server's answers as examples the mock replays. - `generate server fastapi` generates a Python FastAPI server from an OpenAPI 3.x document, with the project layout and options of openapi-generator's `python-fastapi` generator: pydantic 2 models (enums, unions with discriminators, recursive models, aliases and constraints), a router and a base class to implement per tag, security dependencies for API keys, HTTP, OAuth2 and OpenID Connect schemes with alternatives and scopes, `pyproject.toml`, a Dockerfile and pytest tests. Routes declare their status codes and response classes, parameters and bodies of every kind (forms, uploads, text, binary) are typed, and the implementation package, the tests and `.openapi-generator-ignore` are never overwritten. Configured under `commands.generate.server_fastapi`. - `generate client python` generates a Python client of an OpenAPI document, built on httpx (or httpx2) and Pydantic 2: `Client` and `AsyncClient` classes with one resource per tag (`client.pets.list_pets()`), Pydantic models with Python field names, tagged unions for discriminators and `Input` variants for `readOnly`/`writeOnly` properties, all parameter styles, JSON, form, multipart, text and binary bodies, typed errors parsed with the documented schemas, retries with backoff honoring `Retry-After`, per-request options, raw and streaming responses, server-sent events, server variables, and authentication by security scheme, including the OAuth 2.0 client credentials flow. The code passes `mypy --strict`. Configured under `commands.generate.client_python`. - `generate client java` generates a Java client of an OpenAPI document as a Maven project (Java 17, Spring Framework and Jackson versions from the Spring Boot BOM, without Spring Boot): an `ApiClient` on Spring's `RestClient` (`--library restclient`, the default) or `RestTemplate` (`resttemplate`) with one class per tag, whose operations have `op(...)`, `opWithHttpInfo(...)`, `opStream(...)` (a lazy `Stream` of `text/event-stream` and JSON Lines items) and `opWith<MediaType>(...)` methods for further request media types (`updateShipmentWithJsonPatch`); every parameter style, JSON-encoded `content` parameters, JSON, JSON Lines, form, multipart (`Resource` parts) and binary bodies, QUERY and other methods, operation and path servers, credentials per security scheme (bearer, basic, API keys in headers, queries and cookies) applied to the operations requiring them, and `ApiException`/`ProblemDetailsException` (RFC 9457) for errors; `x-internal` operations are left out. `--library feign` and `--library http-interface` generate Spring Cloud OpenFeign and Spring HTTP interface clients. Configured under `commands.generate.client_java`. - `generate server express` generates an Express 5 server stub in TypeScript from OpenAPI 3.x documents: typed handler interfaces per tag, implemented in files of your own, and `createRouter(handlers, options)`, a router which checks security requirements with security handlers per scheme, decodes parameters in all OpenAPI styles and converts them to the types of their schemas, parses bodies, validates requests (and optionally responses) with Ajv or with generated validators without dependencies (`validation`), answers errors with RFC 9457 problem details and operations without handlers with 501. It can include the document and an example server. Configured under `commands.generate.server_express`. - `generate server orpc` generates a TypeScript server based on oRPC (https://orpc.dev) from an OpenAPI document: Zod schemas, a procedure contract per operation with its route, input, output and type-safe errors (one per 4xx/5xx response, sent with the response body of the document), handler stubs, and a Node.js server serving the procedures with oRPC's `OpenAPIHandler` and their OpenAPI reference. Inputs use oRPC's compact structure unless the request needs the detailed one, parameters are converted from strings, and operations with several success responses or response headers return status, headers and body. Handlers and the server files are written once, so regenerating keeps them. Targets oRPC 1, or oRPC 2 (beta) with `orpc_version: 2`. Configured under `commands.generate.server_orpc`. - `generate server aspnet` generates an ASP.NET Core server in C# built on Minimal APIs, for .NET 8 to 10 and without NuGet packages: records and enums of the schemas, one interface per group of operations whose methods return `Results<...>` unions of typed results (generated result types cover statuses `TypedResults` lacks), endpoints binding path, query, header and cookie parameters (array styles included) and JSON, text, binary, form and multipart bodies, and a project with `Program.cs` and stub implementations written only when missing. `oneOf` with a discriminator becomes `[JsonPolymorphic]` records, enums keep the values of the document, an endpoint filter validates requests against the constraints of their schemas (400 validation problems), and operations with security requirements call `RequireAuthorization()`. `layout: sources` writes only the sources, for existing projects. Configured under `commands.generate.server_aspnet`. - `apigenie-mock --proxy-to http://host:port` with an OpenAPI document is a validating proxy for contract testing: it forwards every request to the real server and checks the request and the server's response against the document (parameters, bodies, security, statuses, media types, headers). Violations carry stable checks such as `response.body.incompatible` and show up in the log, in `X-Apigenie-Mock-Violations-Detail` and at `GET /__apigenie/contract`; `--strict` rejects bad requests (422) and replaces bad responses (502). The mock counts the operations, request bodies and responses the traffic covered, and writes `--report` (JSON) and `--report-junit` when it stops; `--fail-on` and `--min-coverage` make it exit with 5. Configured under `proxy` and `contract`. - `overlay` command applies OpenAPI Overlays (versions 1.0, 1.1 and 1.2 of the specification) to an OpenAPI document, or to any JSON or YAML document: `apigenie overlay INPUT --overlay OVERLAY`, with `--overlay` repeated to apply several overlays in order. Updates, copies and removals follow the merge rules of the specification, reusable actions are supported, YAML comments are kept, and actions that select nothing are reported as warnings. `--validate` only checks the overlays, with the line and column of each issue. Targets are RFC 9535 JSONPath queries, functions (`length()`, `count()`, `match()`, `search()`, `value()`) included. The `openapi_overlay` WebAssembly module exports the same `apply` and `validate`. - `generate server go` generates a Go server for the `net/http.ServeMux` of Go 1.22 from an OpenAPI 3.x document, using the standard library only. Names and layering follow oapi-codegen: `ServerInterface` receives bound parameters, `StrictServerInterface` request and response objects (typed headers, statuses, JSON, form, multipart, text and binary bodies). Types carry `Validate()` methods, and parameters and bodies are validated before the handlers run, with RFC 9457 problem details for failures; `oneOf`/`anyOf` become structs with one field per variant, optional nullable properties `Nullable[T]`. Patterns end with `{$}` where needed, and the patterns `http.ServeMux` can't register together share one that dispatches to the most specific operation. A `SecurityHandler` and middlewares run before parameters are bound. Configured under `commands.generate.server_go`. - `generate schema zod` generates Zod (v4) schemas, with their inferred TypeScript types, from the root schema and the `$defs` of a JSON Schema document (drafts 4 to 2020-12), or from the component schemas of an OpenAPI 3.x, Swagger 2.0 or AsyncAPI document. Objects follow JSON Schema and keep unknown properties unless `additionalProperties` says otherwise; formats, numeric and string constraints, tuples, `patternProperties`, `not`, `if`/`then`/`else` and dependencies are validated, discriminated unions are detected, and recursive schemas become getters. Configured under `commands.generate.schema_zod`. - `generate client ws` and `generate server ws` generate TypeScript code from the WebSocket channels of AsyncAPI 3.x documents: a client with one class per channel (browsers and Node.js, no dependencies) and a Node.js server built on the `ws` package, with session classes and handler interfaces. Payloads, address parameters and the query of the WebSocket binding are typed; received messages get handlers of their own when a property with a constant value tells them apart. The server implements the described application and the client its counterpart, unless the `perspective` option says otherwise. Configured under `commands.generate.client_ws` and `commands.generate.server_ws`. - `format --check` reports the files that formatting would change, one path per line, and exits with 1 when there are any, without writing anything. - GitHub Action (`src/github_action`, not published yet) that installs the CLI on Linux, macOS and Windows runners and runs `lint`, `format --check` or `diff` (against the pull request's base), with annotations on the files and a job summary. With `sarif: true`, lint issues are also uploaded to GitHub code scanning; on pull requests, the `diff` report is posted as a comment that later runs update in place. - `sarif` formatter of `lint`: SARIF 2.1.0 for GitHub code scanning and other dashboards, with paths relative to the current directory and fingerprints based on JSON pointers, so that issues are tracked across runs. - `apigenie-mock`, a mock server for OpenAPI 3.0 and 3.1 documents, installed with `apigenie` by every package and published as the `mykulyak/apigenie-mock` Docker image. It answers with the document's examples or with data generated from its schemas, validates requests (422 with problem details) and its own responses, checks security requirements, follows `Prefer` headers (`code`, `example`, `dynamic`, `delay`, `drop`, `scenario`), simulates latency, jitter, dropped connections and bandwidth limits, and logs every exchange as text or JSON lines. Scenarios force error states from a configuration file (`apigenie-mock.yaml` or `commands.mock`), `x-apigenie-mock` document extensions or an admin API under `/__apigenie`, which also reloads, reseeds and stops the server. `--watch` reloads the document and the configuration when they change. Schemas can pick faker functions with `x-faker`. - `apigenie-mock` serves AsyncAPI 3.x documents: WebSocket clients of a channel get its send operations' messages on a schedule and their messages are checked against its receive operations and answered with their replies; HTTP channels take and answer messages; an in-house MQTT 3.1.1 and 5 broker serves the channels of mqtt servers. - `apigenie-mock` serves the gRPC services of `.proto` files over cleartext HTTP/2, on the same port as HTTP: unary and streaming methods answered from YAML or JSON stub files (`--stubs`, `grpc.stubs`) with request and metadata matchers, templates, delays and error statuses with `google.rpc` details, or with messages generated from the response types. It honours deadlines and message limits, follows `x-apigenie-mock-*` metadata, applies scenarios (`grpc_status`, `grpc_message`) and scripts, serves server reflection (v1 and v1alpha) and health checks, proxies unanswered calls to an upstream server (`--proxy-to`) and records them as stub files (`--record-dir`). The admin API manages stubs and has the call history and a `verify` endpoint under `/__apigenie/grpc`. Imports are looked up in `--proto-path` directories and among the embedded well-known, `google/api` and `google/rpc` files. - `apigenie-mock` also answers OpenAPI documents over cleartext HTTP/2 (prior knowledge). - `apigenie-mock` serves GraphQL schemas (`.graphql`, `.graphqls`, `.gql`) at `/graphql`: GET, POST and batched requests per GraphQL over HTTP, validated against the schema with the rules and messages of graphql-js, executed with generated data (by type, field name and custom scalar name, or as graphql-faker's `@fake`, `@examples` and `@listLength` and the mock's `@mock` directives say), full introspection, GraphiQL and the SDL. Entities (types with an `id`) keep their values across requests, and `user(id:)`, `users`, `usersConnection` (Relay) and `createUser`, `updateUser`, `deleteUser`-like fields read and change them. Examples (`graphql.examples`, example files, `<schema>_examples/`) answer operations or fields, cut to the selection set and completed with generated values; scenario rules match operations and root fields and inject errors at field paths. Subscriptions are served over WebSocket (`graphql-transport-ws` and the legacy `graphql-ws`) and server-sent events. Configured under `graphql`. - `apigenie-mock` runs JavaScript hooks (`--script`, `scripts`): `onRequest` answers requests, `onResponse` changes responses and their simulated delays or drops, `onMessage` changes or drops AsyncAPI messages, `onGraphQL` answers GraphQL operations, with state kept between requests, logging, seeded random numbers, faker functions and scenarios. - Linter validates documents against the OpenAPI schema, and more rules support autofixing, including the new `schema-no-optional-nullable-properties` rule. - `diff` command (openapi-diff) and the HTML documentation generator are available again. - `diff` severities are configurable per context: `request` and `response` rule overlays (callbacks and webhooks swap them), `overrides` for single locations, conditions such as `if: required`, and `add_first_item` / `remove_last_item` rules. Schema properties are compared, respecting `readOnly` and `writeOnly`. - `diff` detailed reports describe each change in all formats. - `diff` command compares AsyncAPI 3.x documents: servers, channels, operations, messages and their payloads and headers, security schemes, bindings (property by property for HTTP, WebSockets, Kafka, AMQP and MQTT) and components, with the same reports, formatters, exit status and `--update-version` as OpenAPI documents. The severity of a message change depends on whether the application sends or receives the message (`send` and `receive` rule overlays). Configured under `commands.diff.asyncapi`. - `diff` command compares Protobuf (proto3 `.proto`) files: package, imports, options, messages, fields (matched by their numbers), oneofs, enums, services, methods, extend blocks, reserved numbers and names, and comments, with the same reports, formatters and exit status as OpenAPI documents. Type names are resolved before they are compared, and removing a field whose number the new file reserves is not breaking. Severities can depend on `reserved`, `deprecated` and `wire_compatible` conditions, and options are configured by their names. Configured under `commands.diff.protobuf`. - `diff` command compares Swagger 2.0 documents: host, base path, schemes, media types, paths, operations, parameters (matched by location and name, the body parameter by location), responses, headers, schemas (following references to definitions), security definitions and requirements, and tags, with the same reports, formatters, exit status and `--update-version` as OpenAPI documents. Body parameters and consumed media types get the `request` rules, responses and produced media types the `response` ones, and definitions the stricter of the two. Configured under `commands.diff.swagger`. - `diff` command compares GraphQL schemas (`.graphql`, `.graphqls` and `.gql` files): root operation types, types of every kind, fields, arguments, input fields, default values, interfaces, union members, enum values, directive definitions, applied directives and descriptions, with the same reports, formatters and exit status as OpenAPI documents. Type extensions are merged into their types, and operations are ignored. Severities follow graphql-js's breaking changes and can depend on `required`, `compatible`, `deprecated` and boolean conditions; directives are configured by their names. Configured under `commands.diff.graphql`. - `changelog` command builds the changelog of an OpenAPI file from its git history: one entry per commit or per release tag, or the history of each operation (`--by operation`, filtered with `--operation`), as stylish text, Markdown, HTML or JSON. Files the specification references are followed in each version. - `changelog` command builds the changelog of AsyncAPI 3.x files too: added, removed and changed operations, channels and servers, with the changes of a channel's messages shown under the operations using it, rated with the `commands.diff.asyncapi` rules. `--operation` selects AsyncAPI operations by id, by `send`/`receive` and channel address, or by channel address. - `changelog` command builds the changelog of Protobuf (`.proto`) files too: added, removed and changed methods (named `Service.Method`), messages, enums, services and extensions, package changes shown like version changes, rated with the `commands.diff.protobuf` rules. The file is compared on its own, without the files it imports. `--by operation` groups the changes by method, and `--operation` selects methods by full name, method name or service name. - Swagger 2.0 input support. - `changelog` command builds the changelog of Swagger 2.0 documents too: added, removed, deprecated and changed operations, with the changes of a path item shown under its operations, and the host, base path, schemes, media types and security of the API as metadata, rated with the `commands.diff.swagger` rules. Files the specification references are followed in each version. - `changelog` command builds the changelog of GraphQL (`.graphql`, `.graphqls`, `.gql`) schema files too: added, removed and changed operations (the fields of the root operation types, named like `Query.books`), scalars, object types, interfaces, unions, enums, input objects and directive definitions, with changes of the root operation types, the schema description and the schema directives as metadata, rated with the `commands.diff.graphql` rules. The file is compared on its own. `--by operation` groups the changes by operation, and `--operation` selects operations by full name, field name, root type name or operation type (`query`, `mutation`, `subscription`). - `bundle` command bundles Swagger 2.0 documents and the local files they reference into a single file: referenced schemas, parameters and responses become entries of `definitions`, `parameters` and `responses`, and referenced path items take the content of their files. - `bundle` command bundles AsyncAPI 3.x documents and the local files they reference into a single file. Root servers, channels and operations kept in other files take the content of those files, so that operations still refer to their channels and channel messages; other referenced objects become components. Schemas in other formats, such as Avro, are copied as they are, and references by URL are kept. - `bundle` command bundles Protobuf (`.proto`) files: the input file and the messages, enums and extensions it uses from the files it imports (searched in the `-I`/`--proto-path` directories) are combined into one proto3 file. Declarations from other packages are renamed with a prefix made from their package, and well-known type imports are kept. - `format` command formats AsyncAPI 3.x documents, configured under `commands.format.asyncapi`. - `i18n` command extracts the texts of AsyncAPI 3.x documents for translation: the titles, summaries and descriptions of servers, channels, operations, messages, schemas and the other objects, keyed by their JSON pointers. - `i18n` command extracts the leading comments of Protobuf (`.proto`) files for translation, keyed by the fully qualified name of the message, field, oneof, enum, enum value, service or method they document; enum values are keyed under their enum, and the comment of the file (that of its `syntax` statement) under the package name. - `i18n` command extracts the descriptions of GraphQL (`.graphql`, `.graphqls`, `.gql`) files for translation, keyed by full name: the schema (`schema`), types, fields, arguments, input fields, enum values and directives by their schema coordinates (e.g. `Query.search(text:)`, `Genre.POETRY`, `@key`), operations and their variables (e.g. `query FindBooks`, `query FindBooks($text:)`) and fragments (e.g. `fragment BookSummary`). - `format` command formats Swagger 2.0 documents, configured under `commands.format.swagger`. - `format` command formats GraphQL schemas and operations (`.graphql`, `.graphqls`, `.gql`) in the layout of Prettier, keeping all comments, and optionally sorts definitions and the members of types. Configured under `commands.format.graphql`. - `lint` command lints AsyncAPI 3.x documents with 31 rules (ported from the OpenAPI ones where they apply, plus `channel-parameters-defined`, `channel-addresses-unique` and `server-hosts`), rulesets, custom rules and autofixes, configured under `commands.lint.asyncapi`. - `lint` command lints Swagger 2.0 documents with 46 rules (ported from the OpenAPI ones where they apply, plus `host-defined`, `schemes-secure`, `media-types-defined` and `swagger-validation`, which reports the specification violations found by the Swagger validator), rulesets, custom rules and autofixes, configured under `commands.lint.swagger`. - `lint` command lints Protobuf (proto3 `.proto`) files with 39 rules modelled on buf's: naming conventions, packages (versions, directories, consistent language options, import cycles between packages), imports (unresolved, unused, public, weak, cycles, order), enums, services and RPCs, comments and spell checking. Imports are looked up in `--proto-path` directories, the `import_paths` of the configuration and the directories above the file, with the well-known `google/protobuf` files built in. `--fix` removes unused imports and sorts imports; an `// apigenie-lint-disable <rules>` comment disables rules for a declaration. Configured under `commands.lint.protobuf` with the `recommended` (default), `strict` and `all` rulesets. - `lint` command lints GraphQL schemas and operations (`.graphql`, `.graphqls`, `.gql`) with 87 rules modelled on graphql-eslint, graphql-schema-linter and Apollo's schema linter: the type system and operation rules of the specification, naming conventions, descriptions, deprecations (reasons, deletion dates), schema design (root types, mutations and payloads, unreachable types, identifiers, `@oneOf`, circular input types), the Relay connection conventions, ordering, spelling, and operations checked against the schema (unknown fields, types and arguments, required arguments, deprecated fields, selection depth, identifier selections). Operations are checked against the files named by `--graphql-schema` or by the `schema` option, or against the type system of their own document. A `# apigenie-lint-disable <rules>` comment disables rules for a definition. Configured under `commands.lint.graphql` with the `recommended` (default), `strict`, `all` and `relay` rulesets; `--fix` doesn't apply to GraphQL files. - Minimal telemetry. - Linter rules reasoning about schemas: `schema-no-contradictions` (constraints rejecting every value, and properties forbidden by an `allOf` member with `additionalProperties: false`), `schema-oneof-no-overlap` (`oneOf` branches a single value matches, shown in the report), `schema-required-properties-defined` and `schema-conditional-effective` (`if`/`then`/`else` without effect), all in the `recommended` ruleset, and `patch-request-body-partial` (required properties in `PATCH` bodies) in the `strict` ruleset. - Official release binaries for macOS (arm64), Linux (x64, static, runs on any distribution) and Windows (x64), plus `.deb` and `.rpm` packages, a Homebrew formula, per-platform npm packages and a versioned Docker image. - `generate server express` and `generate client fetch` follow `discriminator.defaultMapping` (OpenAPI 3.2; `x-defaultMapping` in 3.0 and 3.1). Express validates such a `oneOf` by the discriminating property: with Ajv as an `if`/`then`/`else` chain that ends with the default schema, with `validation: generated` by a dispatch reporting the same issues. A value whose property matches no mapping, or lacks it, is validated against the default schema instead of failing `oneOf`. The types of both targets get a type guard per member (`isParcelShipment(value: Shipment)`), the default member's taking the values no mapping matches. The fetch client's conformance snapshots cover OpenAPI 3.1 and 3.0 too. ### Changed - The documentation smoke run of the codegen conformance suite is `generate docs` (`test_docs_bundle`) instead of `generate doc html`, and the `e2e/generate_doc_html` benchmark cases are `e2e/generate_docs`. - `apigenie test import` writes the credentials it finds (bearer tokens, basic credentials, API keys, OAuth 2 client secrets and passwords) to a generated `http-client.private.env.json` instead of `http-client.env.json`, which keeps the other variables and no secret; `apigenie test` reads both. The `sensitive-environment` warning names the private file. - The web components read AsyncAPI documents with the `asyncapi` WebAssembly module, as they read GraphQL and Protobuf: set `asyncapi-wasm-url` on `<apg-spec>` or `<apg-api-reference>`, or call `configureAsyncApiEngine(url)`. `npm run prerender` takes `--asyncapi-wasm`. There is no JavaScript reader for AsyncAPI any more; without the module, AsyncAPI documents fail to load with a message saying what to set. The views are unchanged. `@mykulyak/apigenie-asyncapi-view` reads the module's documentation model; its `parse` and `traits` modules are gone. Server-rendered pages embed the model, so hydration needs no module. - The JSON contract reports of `apigenie-mock --report`, `GET /__apigenie/contract` and `apigenie test --report` give each OpenAPI operation the JSON `pointer` of the operation in the document (e.g. `/paths/~1pets/get`). - Internal: `swagger_convert` returns a source map with each conversion, from the JSON pointers of the result to those of the Swagger 2.0 document. - `apigenie-mock --proxy-to` with a `.proto` file logs request violations instead of failing the call with INVALID_ARGUMENT, as the OpenAPI, GraphQL and AsyncAPI proxies do; `--strict` or `grpc.validation.request: enforce` restores it, and a request is then checked before it reaches the upstream (an always-mode proxy forwarded it first). A mock without `--proxy-to` keeps enforcing requests, and now also rejects a request that misses a field marked `[(google.api.field_behavior) = REQUIRED]`. A non-200 HTTP answer of the upstream ends the call with the status gRPC clients make of it (UNAVAILABLE for 503) instead of always UNAVAILABLE, and an upstream answer without `grpc-status` ends as UNKNOWN instead of OK. - `--report` and `--report-junit` of `apigenie-mock` are accepted for `.proto` files, and `/__apigenie/contract` answers for them. - The requester of `generate server aspnet`'s Kafka code (AsyncAPI) waits for replies on the runtime's new `KafkaReplies`, which `generate client csharp` shares; its behaviour is unchanged. The OpenAPI configurations of `generate client csharp` and `generate server aspnet` ignore their `asyncapi` section instead of rejecting it as an unknown option. - `generate server aspnet` (OpenAPI) writes the recursive DataAnnotations validation of `ValidationFilter` as `Infrastructure/ModelValidator.cs`, which the AsyncAPI Kafka application uses for its messages too; the behavior is unchanged. - `apigenie` and `apigenie-mock` link Mbed TLS 3.6 (Apache-2.0), the first runtime library from vcpkg; `credits` and `license --library mbedtls` list it. The release binaries grow by about 0.9 MB (macOS arm64: `apigenie` +3.5%, `apigenie-mock` +8.2%). The Docker images now include Alpine's CA certificates. - `apigenie-mock --proxy-to` no longer refuses `https://` and `wss://` targets with exit status 2, and the 426 answer to gRPC over HTTP/1.1 on a TLS port says to ask for `h2` by ALPN instead of offering `Upgrade: h2c`. - `generate server spring` is built on `openapi_generator_java`, the Java layer it shares with `generate client java`, whose Feign and HTTP interface writers now generate its `spring-cloud` and `spring-http-interface` libraries; their output is unchanged. Models get `defaultImpl` from `discriminator.defaultMapping` (`x-defaultMapping` before 3.2), name implicit discriminator mappings after the `const` value of the members (`person` instead of `Person`), no longer require the properties of `anyOf`/`oneOf` alternatives (Person and Company required both `email` and `phone` of ContactChannels), and treat an `allOf` with only a reference to a `oneOf` interface as that interface (3.0 documents produced a class extending an interface). - `generate server go`: an `anyOf` or `oneOf` whose members only list required properties no longer makes a union of untyped values, so `allOf` schemas holding one are merged into structs (instead of `any`) and `Validate()` checks the alternatives; a discriminator's `defaultMapping` (`x-defaultMapping` in 3.0 and 3.1) decodes unknown values as its fallback variant, and an implicit mapping also accepts the `const` the variant gives the property. The runtime's request binders moved from `runtime_params.gen.go` to a new `runtime_bind.gen.go`. - The OpenAPI library reads a media type's `itemSchema` and a discriminator's `defaultMapping` (3.2), and their `x-itemSchema` and `x-defaultMapping` forms in 3.0 and 3.1 documents. - `generate server aspnet` and `generate client csharp` share their C# models (`src/openapi_generator_csharp`). The server's output changes in two ways: the implicit discriminator value of a `oneOf` variant is the `const` of its discriminator property when it has one (e.g. `"person"` instead of the schema name `"Person"`), and a `oneOf` or `anyOf` whose members map to one C# type has that type (e.g. `List<string>` for strings of the `ipv4` and `ipv6` formats, instead of `List<object>`). - The contract report of `apigenie-mock` (gate, JSON and JUnit) moved into the `mock` and `openapi_mock` libraries, shared with `apigenie test`; its output is unchanged. - `format` keeps the YAML comments of OpenAPI, Swagger and AsyncAPI documents (at the top and the end of the file, above keys, at the end of lines, inside sequences and between entries); comments move with their keys when properties are sorted. Before, every comment was dropped, and `format --check` reported commented files that were formatted. - `lint --fix` keeps the YAML comments of the OpenAPI, Swagger and AsyncAPI documents it rewrites, including those of the properties a fix replaces, instead of dropping them all. - `format` writes a Protobuf comment that follows a declaration on the next line (and that protoc attaches to it) on its own line again, instead of moving it to the end of the declaration's line. - `i18n` has two subcommands: `i18n extract` extracts texts, as `i18n` did, and `i18n apply` applies translations. `apigenie i18n FILE --output DEST` becomes `apigenie i18n extract FILE --output DEST`, which also accepts `-o`. - `apigenie-mock --stubs` with a GraphQL schema or an AsyncAPI document exits with status 2 instead of being ignored; stubs answer the calls of a `.proto` file and, now, the operations of an OpenAPI document. - `lint` exits with status 1 when it reports issues of severity `error` (those remaining after `--fix`), so CI jobs fail on them; warnings keep the exit status at 0. - The CLI binary is about 2.8 MB (14%) smaller: the test-data generator's string tables (names, addresses, words and the like) are stored compressed and decoded when first used, instead of as pointer tables. - The built-in English spelling dictionary is stored compressed (about 290 KB less in the binary) and decoded only when the first spell-check rule runs; the decoded bytes are released once the dictionary is parsed. - The third-party license texts shown by `license --library` are stored compressed and decoded only when one is printed. - `format` reports files that are neither OpenAPI nor AsyncAPI documents and leaves them untouched, instead of writing empty output. - Parse errors in JSON and YAML input now report why and where the input cannot be parsed. - `lint` with several input files writes a single report for the `json`, `checkstyle`, `junit`, `html`, `sarif` and `tap` formatters, instead of one document per file. - `diff` exit status and `--update-version` consider all changes, whatever the report shows, and a fixed severity of a node caps the severities of changes inside it (e.g. adding an optional parameter is non-breaking). - `diff --update-version` changes only the version in the file, keeping its formatting. - `diff` configuration is validated: unknown node types, properties and severities are reported. - `generate server spring` builds Java sources with a syntax tree instead of text templates. The generated code is the same, but imports are sorted and blank lines and indentation are consistent. - `unused-shared-component` is enabled again in the `recommended` (warning), `strict` and `all` rulesets, and skips documents without operations, which are libraries of components for other documents. - `schema-no-optional-nullable-properties` recognizes OpenAPI 3.0 `nullable: true`, referenced nullable schemas and `anyOf`/`oneOf` null branches, finds `required` in `allOf` members, and skips `PATCH` and merge-patch bodies, where `null` clears a value (option `ignorePatchBodies`). - `spell-check` (OpenAPI and AsyncAPI) now checks spelling: it reports each misspelled word of titles, summaries and descriptions with suggested corrections, using a built-in English dictionary, and skips code, URLs, identifiers and acronyms. Options `words` (extra words), `suggestions` and `dictionary`/`affix` (any Hunspell dictionary) are optional. The rule moved from the `recommended` ruleset to `strict` and `all`. - Internal: the Swagger 2.0 to OpenAPI 3.2 conversion behind `convert --to openapi32` moved from the CLI into its own library, `swagger_convert`, which also reports what each conversion approximates or drops (not shown by the CLI yet). The output of `convert` is unchanged. - Internal: a release gate (`release_gate.yaml`) runs every test on Linux, Windows and macOS, the tests that build generated code with Java, Go, .NET and Python, the RealWorld demo, codegen conformance Levels 2 and 3 and the WebAssembly build; a `cli-*` tag only gets its draft release once the gate passed on the tagged commit. ### Removed - `generate doc html`, the Astro documentation project it generated and the `@mykulyak/api-genie-doc-html-template` package it depended on, with the `commands.generate.doc_html` configuration section (see Upgrading). Internal: `openapi_generator_doc_html` and `code_morph_astro`. ### Fixed - `apigenie-mock --license` without a library name prints API Genie's license instead of the usage: an option whose value is optional counted as given only with a value. - `generate server spring` reads request bodies typed by a oneOf without discriminator (JSON Patch operations, Carpet Express's recursive `SearchFilter`): such interfaces had no type information, so Jackson couldn't instantiate them and the request answered 500. The interface now names a `Deserializer` built on the generated `OneOfDeserializer`, which reads the one member the value matches: a member that declares all its properties (or takes additional properties), reads it and, with Bean Validation, is valid. A value matching no member, or several, is a 400. `useDeductionForOneOfInterfaces=true` keeps Jackson's deduction. Strings with `format: uri` (`java.net.URI`) no longer get `@Pattern` or `@Size` in `generate server spring` and `generate client java`: Bean Validation can't check them on a URI and threw `UnexpectedTypeException` (the server's `createWebhookSubscription` answered 500); their pattern isn't checked. - The Pydantic models of `generate client python`, `generate server faststream` and the Python Kafka client check `pattern`: `Annotated[str, matching(r"...")]`, a validator of `_models.py` compiling the pattern with Python's `re` when a value is first checked (Pydantic's default engine rejects look-arounds, back-references and large `\w` repetitions, which would break the model). Named string schemas keep their constraints in their aliases, e.g. `ShipmentId: TypeAlias = Annotated[str, matching(r"^shp_[0-9A-Za-z]{24}$")]`; a pattern `re` can't compile, such as one using `\p{L}`, isn't checked. - `generate server faststream`: published messages and replies no longer carry `null` for optional fields that weren't set, which their schemas don't allow. The publish functions and the subscribers' replies send payloads through the runtime's new `encode_message()` (the fields that were set), instead of letting FastStream serialize the models with every field. Subscribers of operations with a static reply channel now return a `KafkaResponse`, `RabbitResponse` or `MQTTResponse`, and their reply publisher states the reply's schema (`schema=`). - The code of `generate client ws` and `generate server ws` passes typescript-eslint's recommended type-checked rules: options and handler interfaces that would be empty are type aliases, the client runtime's `WebSocketLike.addEventListener` has one overload per event instead of an `any` listener, and the shared AsyncAPI type mapper no longer writes `unknown` into unions (`[key: string]: unknown`) or intersections (an `anyOf` of `required` lists). - The validators of `generate server express` (`validation: functions`) import `pointerToken` only when a generated function uses it, so object schemas with `additionalProperties: true` no longer leave an unused import. - Generated values (`apigenie-mock` responses and messages, examples) satisfy an object schema's `oneOf`/`anyOf` next to its `properties`, such as `anyOf: [{required: [phone]}, {required: [email]}]`: one alternative is picked and what it requires is generated. The alternatives used to be ignored, so such objects could lack every property they ask for. - `apigenie-mock`: the problems of an `x-apigenie-mock` extension name it by a well-formed JSON pointer (`/paths/~1pets/get/x-apigenie-mock`, not `/paths//pets/get/...`), and by its line when the value has no position of its own. - `apigenie-mock` generates AsyncAPI messages whose schemas use AsyncAPI's string `discriminator` or an `externalDocs` given by `$ref`: such documents made every message without an example fail with "the payload has no schema values can be generated from". A reply whose message has its `correlationId` in the payload now carries the request's value (Carpet Express's `requestPickup` gets a `pickupConfirmed` with its `requestId`). - `apigenie-mock --proxy-to ws://` checks the server's reply to a client message of a request/reply operation against the reply's messages and its `correlationId` (`message.reply.uncorrelated`), instead of reporting it as `channel.send.undeclared` on a channel without `send` operations (ADR-110). - `generate server faststream` no longer fails with "The message schemas can't be mapped to Python types" when a payload schema's `externalDocs` is a `$ref`, as the AsyncAPI fixture's `CloudEvent` has: the reference is followed. - The AsyncAPI contract report counts the requests of HTTP channels, mocked or proxied, as messages of their operations. - `generate client csharp`: the generated project compiles again: the client of the API is registered with `AddHttpClient<TClient, TClient>(factory)`, as `AddHttpClient<TClient>` has no factory overload and bound the lambda to its configuration callback (CS1503). Unions read by the generated discriminator converters no longer carry `[JsonPolymorphic]`/`[JsonDerivedType]`, which System.Text.Json rejects next to a custom converter ("does not support metadata writes or reads") when sending or reading a `oneOf` with a discriminator. - `generate client csharp` and `generate server aspnet`: properties with a default value are settable instead of init-only, because the System.Text.Json source generator of .NET 8 assigns every init-only property and replaced the default of an absent one with `0`/`false`/`null`; decimals described as strings (`type: string, format: decimal`) are written as JSON strings. - `generate client python`: form body fields whose `encoding` sets `style` or `explode` are written like query parameters of that style (`deepObject`: `hints[building]=rear`) instead of as JSON text. The package passes ruff's default rules: `__all__` lists are sorted as RUF022 expects, and the runtime uses `X | Y` unions and `Self`. - `generate server express` with `validation: generated`: objects without declared properties (maps), or with only `patternProperties`, no longer get validators with constant conditions (`if (!(false))`, `false || ...`), which failed ESLint's `no-constant-condition`. The codegen conformance suite's Level 2 now also type-checks and lints a `validation: generated` build. - `generate client fetch`: properties of `application/x-www-form-urlencoded` bodies whose `encoding` sets `style` or `explode` are written like query parameters of that style (`deepObject`: `hints%5Bbuilding%5D=rear`, also `pipeDelimited`, `spaceDelimited` and unexploded `form`) instead of as JSON text; the other object properties stay JSON. The runtime no longer calls `String()` on values of unknown type, so it passes typescript-eslint's `no-base-to-string`. - `generate server express` routes `QUERY` and `COPY` operations (OpenAPI 3.2): their routes were typed with a method the runtime's `HttpMethod` type lacked, so the generated package didn't compile. An empty form field of a nullable property (`location=` for `oneOf: [GeoPoint, {type: null}]`) is read as null instead of failing validation, and the runtime passes typescript-eslint's recommended type-checked rules. - `generate client fetch`, `generate server express` and `generate server orpc`: `anyOf`/`oneOf` alternatives that only add constraints (`anyOf: [{required: [email]}, {required: [phone]}]`) no longer add `& unknown` to the type. - `generate server aspnet`: an empty form field for an object (`location=`, how form style writes an empty or null value) is read as null instead of failing to parse as JSON with 400. - `generate server spring`: a `@lombok.*` annotation in a model's `x-class-extra-annotation` drops the members Lombok generates for that model and adds Lombok to the pom, as `additionalModelTypeAnnotations` does; before, the model kept its own `equals`/`hashCode` next to `@lombok.EqualsAndHashCode` and the project didn't build without Lombok. Deprecated parameters no longer get `@Deprecated`, which has no effect on parameters (`javac -Xlint` warns since JDK 21); the deprecation stays in `@Parameter(deprecated = true)`. - `generate client python` and `generate server faststream`: `allOf` parts with `oneOf`/`anyOf` alternatives that only add constraints, such as Carpet Express's `ContactChannels` (an email or a phone), are merged like other object parts, so `Person` and `Company` are models instead of `Any`. Discriminated unions dispatch on the mapping, on the schema names of the members it leaves out (the implicit mapping) and on the value each of those members fixes the property to with `const` or a single `enum` value (`partyType: person` of a schema named `Person`). Values whose tag is missing or unknown are read as the `discriminator.defaultMapping` schema (`x-defaultMapping` in OpenAPI 3.0 and 3.1), which joins the union if it isn't a member; before, they matched no model. The unions keep their callable `pydantic.Discriminator`, as `Field(discriminator=...)` can neither fall back nor take several tags per model. The codegen conformance suite checks `generate client python` against the OpenAPI 3.1 and 3.0 fixtures too. - `generate server fastapi` passes the codegen conformance suite's mypy, ruff and runtime checks without known failures, on the OpenAPI 3.2, 3.1 and 3.0 fixtures: - Discriminator tags follow the Python models: a member that fixes the property with `const` or a single `enum` value gets that value (`party_type: Literal["person"]` for a schema named `Person`), where the implicit mapping made it `Literal["Person"]` and rejected valid parties. A union with a `discriminator.defaultMapping` (`x-defaultMapping` in OpenAPI 3.0 and 3.1) dispatches with a callable `Discriminator()` that reads values with a missing or unknown tag as the default schema, which joins the union if it isn't a member. - `RootModel` subclasses have their type argument (`RootModel[int | str]`; a forward reference in a cycle), which `mypy --strict` asked for. - A request body with several JSON media types, such as `application/merge-patch+json` and `application/json-patch+json`, is validated against the schema of the request's `Content-Type` (415 for another one); the route took only the first media type's schema. The body parameter is the union of the schemas and the served OpenAPI document lists every media type. - Integer enums in parameters and form fields convert the request's text (`dpi=300`); `Literal[203, 300, 600]` rejected every value. - Multipart file parts described with `contentMediaType` or `contentEncoding: binary` (OpenAPI 3.1 and 3.2), not only `format: binary`, are `UploadFile`s, and arrays of them `list[UploadFile]`. - Imports are sorted the way Ruff's isort rules expect (case-insensitive, numbers by value, long single-name imports wrapped), and the imports at the end of modules of a cycle no longer carry a `# noqa: E402` that Ruff reports as unused. - `apigenie test --generate` sends multipart file parts (`format: binary`, `contentMediaType` or `contentEncoding: binary`) with a file name and the Content-Type of their encoding, and an array as a part per item; servers that only take parts with a file name as files, such as FastAPI's and ASP.NET Core's, rejected the generated requests. - `generate client python` and `generate server faststream`: an object schema with properties of its own and `oneOf` or `anyOf` alternatives that are objects (each narrowing a property or requiring others) becomes a union of one model per alternative with the object's properties merged in. The properties were lost (a union of classes holding only the alternatives' properties), and `anyOf` of `required` lists, such as "an email or a phone", was `Any`. - The CLI no longer writes `.apigenie.telemetry` in the current directory; set `APIGENIE_TELEMETRY_FILE` to keep a local telemetry log. - `apigenie-mock` and `apigenie test` type the fields of form and multipart bodies (and deepObject and delimited parameters) whose properties come from `allOf` members, references included: `residential=false` of a body `allOf: [$ref Address, {...}]` is the boolean `false`, not the string. They were validated as strings, so valid requests were reported or rejected with 422. - YAML output quotes strings that YAML 1.1 parsers (PyYAML, SnakeYAML, go-yaml v2) read as booleans, numbers or merge keys: `yes`, `No`, `ON`, `off`, `y`, `N`, `0b101`, `1_000`, `1:30`, `<<` and the like. Before, `bundle`, `overlay`, `lint --fix`, `convert` and `format` with the `best-fit` style wrote them plain, so other tools read `enum: [yes, no]` as booleans and `1:30` as 90. - `apigenie-mock` validates requests and responses whose schemas refer to themselves (trees, nested filters, recursive `oneOf`s). They were accepted without any check, in OpenAPI and AsyncAPI documents alike. The lint rules `schema-no-contradictions` and `schema-oneof-no-overlap` now analyze such schemas too. - OpenAPI 3.2 documents: examples written with `dataValue` and media types that refer to `components/mediaTypes` are read. Generators no longer drop them (Spring rendered such examples as `null`, Go typed such problem responses as `any`), and `apigenie-mock` answers with those examples. - `generate server fastapi` routes the OpenAPI 3.2 `query` method and the methods of `additionalOperations` (such as `COPY`) with `@router.api_route(..., methods=[...])`. They were emitted as `@router.query`/`@router.copy`, which `APIRouter` doesn't have, so a server generated from a document with such an operation failed to import. - `convert --to openapi32` converts the structure of Swagger 2.0 documents, not only their references: body and `formData` parameters become request bodies with the media types of `consumes` (files as `multipart/form-data`), `collectionFormat` becomes `style` and `explode`, response schemas, headers and examples move into `content` per media type of `produces`, global body parameters become `components.requestBodies`, and references to parameters and responses point into `components`. Schemas get `type: file` as binary strings, object discriminators, numeric exclusive bounds and `x-nullable` as a `null` type. Before, most converted documents could not be read (2163 of the 2168 Swagger documents of the openapi-directory corpus convert into readable documents now, the others are invalid). - Many memory-safety and robustness issues in the parsers, bundler, reader and linter. - `diff` changelog reports rate added, removed and modified operations by their own changes rather than their path's, report request body changes as such instead of as response codes, and no longer list a removed deprecated operation as deprecated. - `generate server spring` numbers enum constants whose names collide (e.g. the values `+1` and `-1`, both named `_1`), like openapi-generator, so the generated models compile. - `test` reports a rejected certificate as such for `wss://`, `mqtts://` and `grpcs://` URLs whose host name has several addresses: it stops at the first address that answers instead of trying the others and reporting the last one's "Connection refused" (on macOS, `localhost` is 127.0.0.1 and ::1, and a server often listens on one). - The YAML and JSON writers report an alias of a collection that contains it as soon as they meet it again, instead of after expanding it to the depth limit, which overflowed the JavaScript stack of the WebAssembly build. - `generate server spring` with `useSpringBoot4` no longer declares `spring-boot-starter-restclient` (or `-webclient`) twice, which Maven rejects as a duplicate dependency. ## 0.8.2 (2025-11-13) Pre-release, published on [GitHub](https://github.com/mykulyak/api-genie/releases/tag/cli-0.8.2). ## 0.8.0 (2025-07-12) Pre-release, published on [GitHub](https://github.com/mykulyak/api-genie/releases/tag/cli-0.8.0).