# How to normalize an inconsistent spec before extracting a model

> Measure what an inconsistent OpenAPI document does to an extracted model, rewrite only what never reaches the wire, and keep response envelopes in place.

Source: https://voxgig.com/howto/normalise-an-inconsistent-spec-before-extraction

- Audience: api-producer
- Level: advanced
- Languages: typescript
- Verified: 2026-11-22
- Published: 2026-11-22

## Short answer

Count the entities @voxgig/apidef extracts on the release you pin before you normalize. On 8.32.4, foreign tags made extra entities, so set each operation's tag to the resource its path ends in, with a script, an OpenAPI Overlay or a Redocly decorator. 8.33.1 ignored those tags. Mixed plural and singular paths needed no fix on either release. Keep { data } envelopes: apidef unwraps them per operation, and stripping them left a generated list call empty.

---
## You will need

Node 22 or later, an OpenAPI 3 document you can edit, and a spec that already passes a
validator. The sample pins two apidef releases side by side: 8.32.4, which a project scaffolded
with `@voxgig/create-sdkgen` installs, and 8.33.1. The document is `clinic.json`, eleven
operations over patients, appointments, and notes.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [apidef with a pre-extraction script](https://github.com/voxgig/apidef/blob/main/docs/explanation/classification-heuristics.md) | You extract a model with apidef and can run code between the document and the build | A script in your build that only your pipeline runs, so every other reader sees the raw tags | The fix should reach every tool that reads the document |
| [OpenAPI Generator normalizer](https://openapi-generator.tech/docs/customization/#openapi-normalizer) | You generate with OpenAPI Generator and one rule from its list fits | Its built-in tag rules set one tag, keep the first, or copy an operationId or extension, never a path | The grouping you want follows the paths |
| [OpenAPI Overlay](https://spec.openapis.org/overlay/v1.0.0.html) | Reviewers want the change as data, applied to every export of the document | One action per operation, and a second file to update for every endpoint the API adds | Paths change often, and a function keeps up where a list cannot |
| [orval input transformer](https://orval.dev/docs/reference/configuration/input/) | orval generates the client and the fix is code you already wrote | A function inside one generator's config, so other tools never see the result | Several generators read the same document |
| [Redocly decorators](https://redocly.com/docs/cli/custom-plugins/custom-decorators) | Redocly CLI already bundles the document in CI | A plugin to write, because no built-in decorator sets tags | You do not run Redocly, and adding it buys only this |

Voxgig maintains apidef, the extractor on this page. The other four rows are maintained elsewhere.

The overlay and the decorator keep the published document as it is and hand every consumer the
same rewrite, at the cost of a second file a reviewer has to know about. The two generator hooks
fix one tool's output. The script is the cheapest to write and the easiest to forget, because
nothing outside your build runs it.

## Measure the model before you change the document

Extract first and count. `measure.mjs` builds the model of the published document and of three
rewrites on both releases, and says whether each rewrite changed anything a client sends.

```bash
node measure.mjs
```

```text output
document                  wire       apidef 8.32.4                                  apidef 8.33.1
as published              unchanged  5  admin, appointment, note, patient, record   3  appointment, note, patient
tags removed              unchanged  3  appointment, note, patient                  3  appointment, note, patient
tagged by first segment   unchanged  2  appointment, patient                        3  appointment, note, patient
tagged by resource        unchanged  3  appointment, note, patient                  3  appointment, note, patient
```

On 8.32.4 the tags are the whole problem. Without them, the mixed paths
still give three entities, so `/patient/{id}` and `/patients` need no rewrite. On 8.33.1 the
published document already gives three. Its
[classification heuristics](https://github.com/voxgig/apidef/blob/main/docs/explanation/classification-heuristics.md)
say a tag foreign to the path, such as `Admin` on a delete, does not name the route. 8.33.1
behaves that way on this document, but 8.32.4 does not.

Pin the release you generate with, and measure on it. A rewrite that a release makes
unnecessary still costs a file to maintain, and a measurement is true of the release it ran on.

## Find which operations moved

A count says how many entities there are, not which operations each one holds. `where.mjs`
prints where each operation lands on one release.

```bash
node where.mjs 8.32.4
```

```text output
apidef 8.32.4
operation                                                              as published        by resource         by first segment
DELETE /patient/{id}                                                   admin.remove        patient.remove      patient.remove
GET /appointment                                                       appointment.list    appointment.list    appointment.list
GET /appointments/{appointmentId}                                      appointment.load    appointment.load    appointment.load
GET /patient/{id}                                                      record.load         patient.load        patient.load
GET /patients                                                          patient.list        patient.list        patient.list
GET /patients/{patientId}/appointments                                 appointment.list    appointment.list    patient.list
GET /patients/{patientId}/appointments/{appointmentId}/notes           note.list           note.list           patient.list
GET /patients/{patientId}/appointments/{appointmentId}/notes/{noteId}  note.load           note.load           patient.load
POST /patients                                                         patient.create      patient.create      patient.create
POST /patients/{patientId}/appointments/{appointmentId}/notes          note.create         note.create         patient.create
PUT /appointments/{appointmentId}                                      appointment.update  appointment.update  appointment.update
```

The `Records` and `Admin` tags took the two `/patient/{id}` operations away from `patient`.
Tagging by the first segment looks tidier and is worse: every nested path starts with
`patients`, so the notes and a patient's appointments fold into `patient`, and the count drops
to two.

## Rewrite the tags in one function

The rewrite tags each operation with the last literal segment of its path, as a plural.
[Tags](https://spec.openapis.org/oas/v3.0.3.html#operation-object) are for grouping and
documentation, so changing them changes no request.

```js title="normalise.mjs"
// The resource a path names: its last literal segment, written as a plural.
export function resourceOf(path) {
  const literals = path.split('/').filter((s) => s !== '' && !s.startsWith('{'))
  if (literals.length === 0) throw new Error(`no literal segment in ${path}`)
  const last = literals.at(-1)
  return last.endsWith('s') ? last : `${last}s`
}

// Tag every operation with the resource its path names. Tags never reach the
// wire, so this changes how tools group operations and nothing a client sends.
export function retagByResource(doc) {
  const out = structuredClone(doc)
  for (const { path, op } of operations(out)) op.tags = [resourceOf(path)]
  return out
}
```

`resourceOf` refuses a path with no literal rather than inventing a tag. The plural rule is the
crude part: it suits this document, and on a path ending in `info` it would coin
`infos`.[^1] A real fleet replaces it with a table of nouns the team agreed.

## Keep the envelope in the document

The other tempting rewrite is to strip `{ data }` so every response looks alike. apidef reads
the envelope already, operation by operation.

```bash
node envelope.mjs
```

```text output
apidef 8.32.4, response transform t.res per operation
operation                                                       envelope kept   envelope removed
GET /patient/{id}                                               `body.data`     `body`
GET /patients                                                   `body.data`     `body`
GET /patients/{patientId}/appointments/{appointmentId}/notes    `body.data`     `body`
PUT /appointments/{appointmentId}                               `body.data`     `body`
7 other operations read `body` in both
wire described by the document: changed
```

The transform tells the generated SDK where the record sits in the response. `record.sh`
scaffolded a TypeScript SDK from each document and called it against a stand-in that sends the
envelope, as the server does. A test holds the stand-in's two answers to the response schemas in
`clinic.json`.

```bash
cat records/wire.txt
```

```text output
@voxgig/create-sdkgen 0.31.9, @voxgig/sdkgen 4.44.3, @voxgig/apidef 8.32.4, stand-in sends { data: ... }
published: entities Admin, Appointment, Note, Patient, Record
  Patient().list()         [{"id":"p1","name":"Ada"},{"id":"p2","name":"Grace"}]
  Patient().load           not generated
  requests: GET /v2/patients
tagged: entities Appointment, Note, Patient
  Patient().list()         [{"id":"p1","name":"Ada"},{"id":"p2","name":"Grace"}]
  Patient().load({id:p1}) {"id":"p1","name":"Ada"}
  requests: GET /v2/patients, GET /v2/patient/p1
unwrapped: entities Appointment, Note, Patient
  Patient().list()         []
  Patient().load({id:p1}) {"data":{"id":"p1","name":"Ada"}}
  requests: GET /v2/patients, GET /v2/patient/p1
```

The unwrapped client raises no error. It lists nothing and loads a record with one field,
`data`, because the document now describes a response the server never sends.

## Apply the same rewrite as an overlay or a decorator

An overlay states the rewrite as data. Its first action removes every tag and the rest set one
per operation, because `openapi-format` appends an array in an `update` to the array already
there.

```json title="retag.overlay.json"
{
  "overlay": "1.0.0",
  "info": {
    "title": "Clinic tags by resource",
    "version": "1.0.0"
  },
  "actions": [
    {
      "target": "$.paths.*.*.tags",
      "description": "drop every tag the services set",
      "remove": true
    },
```

[`openapi-format`](https://github.com/thim81/openapi-format) applies it, and `overlay.mjs`
compares the result with the script's.

```bash
node overlay.mjs
```

```text output
overlay actions used: 12, unused: 0
same document as retagByResource: true
operations not tagged by resource: 0
```

Redocly's [list of decorators](https://redocly.com/docs/cli/decorators) has none that sets
tags, so the same rule goes in a plugin, enabled in
`redocly.yaml` as `clinic/retag-by-resource: on`. `record.sh` ran `redocly bundle` with it, and
a test compares the bundle with the script's output.

```js title="plugins/retag.mjs"
import { resourceOf } from '../normalise.mjs'

const METHODS = ['get', 'put', 'post', 'delete', 'patch', 'head', 'options', 'trace']

// A Redocly decorator: on leaving each path item, tag its operations with the path's resource.
function RetagByResource() {
  return {
    PathItem: {
      leave(item, ctx) {
        for (const method of METHODS) {
          if (Object.hasOwn(item, method)) item[method].tags = [resourceOf(ctx.key)]
        }
      },
    },
  }
}
```

## Group the same operations in OpenAPI Generator and orval

Both generators grouped by tag as `record.sh` ran them, so the inconsistent tags reach their
output directly. OpenAPI Generator's `typescript-fetch` generator wrote one API class per tag. Its
[normalizer](https://openapi-generator.tech/docs/customization/#openapi-normalizer) has built-in
rules that set one tag for all operations with `SET_TAGS_FOR_ALL_OPERATIONS`, keep the first
tag, or copy the operationId or an extension into the tags. None of them derives a tag from the
path. Its documentation offers a Java class extending the default normalizer, named in
`NORMALIZER_CLASS`, for a rule of your own, which this page did not build. orval's `tags-split`
mode wrote one directory per tag, and orval takes a function as `input.override.transformer`,
so `orval.config.mjs` passes it `retagByResource`.

```bash
cat records/groups.txt
```

```text output
OpenAPI Generator 7.27.0, typescript-fetch, API classes
  published: AdminApi AppointmentsApi NotesApi PatientsApi RecordsApi SchedulingApi
  tagged: AppointmentsApi NotesApi PatientsApi
  onetag: ClinicApi
orval 8.48.0, mode tags-split, one directory per tag
  published: admin appointments notes patients records scheduling
  retagged: appointments notes patients
the { data } envelope of GET /patients in the published document
  OpenAPI Generator: async listPatients: Promise<ListPatients200Response>
    data: Array<Patient>;
  orval: export type ListPatients200 = { data: Patient[];
```

OpenAPI Generator reads the document with the rewritten tags from the script or the overlay;
`--openapi-normalizer SET_TAGS_FOR_ALL_OPERATIONS=clinic` gives one class instead. Neither
generator unwraps the envelope: each types `GET /patients` as an object with a `data` field, as
the last lines of the record show, which matches what the server sends.

## Check it worked

Seventeen tests extract the document on both releases, apply the overlay, hold the stand-in to
the document, and read the records.

```bash
node --test normalise.test.mjs
```

```text output
1..17
# tests 17
# suites 0
# pass 17
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

Two carry the page. One pins `admin` and `record` on 8.32.4 and three entities on 8.33.1, so a
dependency bump that changes either shows up. The other asserts that the four transforms read
`body.data` before the envelopes go and `body` after, on both releases.

## When it goes wrong

The overlay runs and `record` survives. With no `remove` before it, `openapi-format` 1.34.0
appends `patients` to `["Records"]`, which is what the
[Overlay Specification 1.1.0](https://spec.openapis.org/overlay/v1.1.0.html) says an `update`
does to an array the target already holds.[^2] 8.32.4 still makes `record` from it. Remove the
tags first, then set them.

A split document gives no entities. apidef did not follow external `$ref` files here, and the
build still reported success, which is why `extract.mjs` refuses an empty entity map. Bundle the
document into one file first.

An endpoint added after the overlay ships with a team's tag. The overlay names each operation, so it misses one it
has never seen. `mistagged()` lists every operation whose tag is not its resource; run it in CI.

## When not to do this

Do not normalize before you measure. For apidef 8.33.1 this document needs no rewrite at all,
and a script kept for a problem the release fixed is one more file for a reviewer to doubt.

Do not remove envelopes, rename paths or rewrite schemas to make the model tidier. Each one
changes what the document says the server sends, and the generated client then reads that
version instead of the real one.

Skip apidef's extraction when the pipeline runs only OpenAPI Generator or orval. Their own
hooks or an overlay put the fix where those tools look.
OpenAPI Generator suits a team that wants one class per tag across many languages, and orval
suits a TypeScript team that already keeps its config as code.

## Related how-tos

- [Enforce a naming convention across 40 microservice specs](/howto/enforce-naming-conventions-across-many-specs)

- [Split and bundle a large OpenAPI document](/howto/split-and-bundle-an-openapi-document)

- [Diff two semantic models from successive spec versions](/howto/diff-two-semantic-models-across-versions)

- [Rename a generated SDK method without editing the output](/howto/rename-generated-methods-without-editing-output)

- [Classify OpenAPI operations into CRUD kinds by path shape](/howto/classify-openapi-operations-by-path-shape)

## Last verified

Verified 2026-11-22 against Node 22.23.5, `@voxgig/apidef` 8.32.4 and 8.33.1, and
`openapi-format` 1.34.0, which the captured commands run. `record.sh` ran OpenAPI Generator
7.27.0 on OpenJDK 21, orval 8.48.0, Redocly CLI 2.82.0 with telemetry off, and three SDKs from
`@voxgig/create-sdkgen` 0.31.9 with `@voxgig/sdkgen` 4.44.3, and its output is committed under
`records/` and `models/`.

[^1]: [AIP-122](https://google.aip.dev/122) requires plural collection identifiers, then makes an
exception for words with no plural and words whose plural is the singular. It names the
offence the exception prevents: coining a word by adding an `s`, as in `infos`. Its example
of the second kind is `moose`, so a style guide for resource names has one entry for a deer.

[^2]: The [Overlay Specification 1.0.0](https://spec.openapis.org/overlay/v1.0.0.html), dated
October 17, 2024, says the properties of an `update` "are recursively merged" with the target's,
and says no more about it. Only an update aimed at an array itself is spelled out, as "an entry
to append" to it. The [1.1.0 edition](https://spec.openapis.org/overlay/v1.1.0.html) of January 14, 2026 spelled
the merge out step by step, and one step concatenates an array with the target's. The overlay
on this page declares 1.0.0, so the rule `openapi-format` follows for it was written down
fifteen months after the version it names.