# How to extract an entity model from a Swagger 2 document

> Build the same apidef entity model from a Swagger 2.0 file as from its OpenAPI 3 copy, and prove it by comparing the attributes of every entity.

Source: https://voxgig.com/howto/entity-model-from-swagger-2

- Audience: library-maintainer
- Level: intermediate
- Languages: typescript
- Verified: 2026-11-22
- Published: 2026-11-22

## Short answer

Pass the Swagger 2.0 file straight to @voxgig/apidef, which reads in: body and in: formData parameters as the request body, or convert it with swagger2openapi and extract from the 3.0 copy. On this page's document both runs give three entities with three, five, and three attributes. Compare the attribute list of every entity between the two runs, and diff the whole models, to prove the route you chose lost nothing.

---
## You will need

Node 22 or later and the Swagger 2.0 document. In the sample directory, `npm ci` installs
`@voxgig/apidef` 8.32.4, the release `@voxgig/create-sdkgen` 0.31.9 installs, and
`swagger2openapi` 7.0.8, and both run offline. How apidef picks an entity and an operation slot is
the subject of the prerequisite on
[classifying OpenAPI operations into CRUD kinds by path shape](/howto/classify-openapi-operations-by-path-shape).

The sample document is a print shop. Orders take a JSON body shared by POST and PUT, customers
are created from a URL-encoded form, artwork arrives in a multipart upload, and a quote request
has an inline JSON body.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [apidef reading Swagger 2 directly](https://github.com/voxgig/apidef/blob/v8.32.4/docs/reference/model.md) | sdkgen is the only consumer of the model | One step, but `x-nullable` is ignored, so a nullable field reads as a plain string | Other tools in the pipeline need an OpenAPI 3 file |
| [Hey API](https://heyapi.dev/docs/openapi/typescript/configuration/input) | Your SDK is TypeScript generated by Hey API | Keeps a body type per operation and no entities, so there is no attribute list to compare | You need one record type per resource |
| [Swagger Codegen](https://swagger.io/docs/open-source-tools/swagger-codegen/codegen-v3/versioning/) | Your clients come from Swagger Codegen and must read the 2.0 file | Two lines to choose between, and 3.0.85 checks optional form fields as required | You need entities rather than a model class per schema |
| [swagger2openapi then apidef](https://github.com/Mermade/oas-kit/tree/main/packages/swagger2openapi) | Other tools in your pipeline read only OpenAPI 3 | A second artifact to regenerate on every change, and one more place to look | sdkgen is the only consumer |

Voxgig maintains apidef. swagger2openapi, Hey API and Swagger Codegen are other projects, and
the conversion route uses apidef only for its last step.

Direct extraction has one step, so a wrong attribute has one cause to look for. Converting first
adds a file and a tool, and gives every other tool in the pipeline a 3.0 document it can read. The
page on [migrating a Swagger 2 document to OpenAPI 3.1](/howto/migrate-swagger-2-to-openapi-3-1)
takes that route on to 3.1, and apidef builds the same entities there from all three files.
AutoRest also reads Swagger 2.0, but [its readme](https://github.com/Azure/autorest) opens with the
notice that it "is deprecated and will be retired on July 1, 2026" and names TypeSpec in its place.
It gets no row.

## Extract from the Swagger 2.0 file and from its 3.0 copy

`extract.mjs` converts the Swagger 2.0 file with swagger2openapi's own API, checks the result
against the committed `converted/` copy, builds the apidef model of both, and compares them. Its
comparison lists each entity's attributes, refuses a run with no entities, and exits 1 when an
entity has no attributes in either run:

```ts title="extract.mjs"
export function attributes(kit) {
  const out = new Map()
  for (const name of Object.keys(kit.entity).sort()) {
    out.set(name, Object.values(kit.entity[name].fields ?? {}).map((f) => f.n).sort())
  }
  return out
}
```

Run it in the sample directory:

```bash
node extract.mjs
```

```text output
@voxgig/apidef 8.32.4, swagger2openapi 7.0.8
converted/printshop-oas30.json: same as this conversion
entity     direct  converted
customer        3          3  email, name, phone
order           5          5  copies, id, note, status, title
quote           3          3  copies, duplex, paper
entities with no attributes: none
request bodies in the direct model:
  POST /customers  customer.create  rb: form application/x-www-form-urlencoded; email, name, phone
  POST /orders  order.create  bf: copies, note, title
  POST /orders/{orderId}/artwork  order.create, action artwork  rb: multipart multipart/form-data; caption, file
  POST /quotes  quote.create  bf: copies, duplex, paper
  PUT /orders/{orderId}  order.update  bf: copies, note, title
direct against converted: 9 values differ
  8 of them co.source, "swagger2" -> "openapi3"
  entity.order.fields.note.t: "`$STRING`" -> ["`$ONE`",["`$STRING`","`$NULL`"]]
```

Every entity has the same attributes in both runs. A JSON `body` parameter is kept as `bf`, the
fields it sends, and a `formData` set as `rb`, which records its kind and its media type. The
customer's form fields became the customer's attributes, and `name` is required because its
parameter is.

The upload is the exception. apidef read `POST /orders/{orderId}/artwork` as an `artwork` action on
`order.create`, so its form is in `rb` and its fields are not order attributes. An action whose
response does not describe the entity declares no fields, at
[line 925 of `ts/src/transform/field.ts`](https://github.com/voxgig/apidef/blob/v8.32.4/ts/src/transform/field.ts#L925).

The whole models differ in nine values. Eight are `co.source`, which records the version the
operation was read from. The ninth is `note`: apidef ignores Swagger's `x-nullable: true`, and
reads the `nullable: true` the converter wrote as string or null.

## Find the input that decides the attributes

The deciding code is
[`swaggerOffers` in `ts/src/transform/body.ts`](https://github.com/voxgig/apidef/blob/v8.32.4/ts/src/transform/body.ts#L218)
at v8.32.4. It takes the one parameter whose `in` is `body`, or every parameter whose `in` is
`formData`, as the request body. `probe.mjs` changes one input at a time:

```bash
node probe.mjs
```

```text output
@voxgig/apidef 8.32.4, attributes per entity, customer body
  as written                                   customer 3, order 5, quote 3             rb form
  POST /quotes body parameter: in "header"     customer 3, order 5, quote 0             rb form
  POST /quotes: no parameters                  customer 3, order 5, quote 0             rb form
  POST /customers form parameters: in "query"  customer 0, order 5, quote 3             none
  POST /customers: no consumes                 customer 3, order 5, quote 3             bf
  the upload moved to POST /artworks           artwork 2, customer 3, order 5, quote 3  rb form
```

The value of `in` decides. Changed to `header` with the schema left in place, the quote has no
attributes, but the build reports success. The `consumes` list decides how the body is kept, not
whether the fields count: without its own list, the customer form takes the document's
`application/json` and is kept as a JSON body in `bf`. Moved off the item path, the upload names
an `artwork` entity with two attributes. `generate.sh` ran both scripts and diffed the whole
models on apidef 8.33.1, the newest release, and recorded the same output and no differing value.

## Read the same document with Hey API and Swagger Codegen

`generate.sh` ran both generators on each document and recorded what they wrote.
`generators.mjs` reads the records:

```bash
node generators.mjs
```

```text output
Hey API 0.99.0, request body type of each write
  createCustomer   3 from 2.0   3 from 3.0  name, email?, phone?
  createOrder      3 from 2.0   3 from 3.0  title, copies, note?
  requestQuote     3 from 2.0   3 from 3.0  paper, copies, duplex?
  updateOrder      3 from 2.0   3 from 3.0  title, copies, note?
  uploadArtwork    2 from 2.0   2 from 3.0  file, caption?
  only from 2.0: 204: unknown;
  only from 2.0: body: NewOrder;
  only from 3.0: 204: void;
  only from 3.0: body: NewOrder2;
  only from 3.0: export type DeleteOrderResponse = DeleteOrderResponses[keyof DeleteOrderResponses];
  only from 3.0: export type NewOrder2 = NewOrder;
Swagger Codegen 3.0.85, from the 2.0 file
  models: CustomersBody 3, NewOrder 3, Order 5, OrderIdArtworkBody 2, QuotesBody 3
  createCustomer(name, email, phone) checks email, name, phone
  requestQuote(body) checks body
  uploadArtwork(file, caption, orderId) checks caption, file, orderId
  api.ts from the 3.0 copy: identical
Swagger Codegen 2.4.53, from the 2.0 file
  models: NewOrder 3, Order 5, Quote 3
  createCustomer(name, email?, phone?) checks name
  requestQuote(quote) checks quote
  uploadArtwork(orderId, file, caption?) checks file, orderId
```

Hey API's [input page](https://heyapi.dev/docs/openapi/typescript/configuration/input) says it
supports all valid OpenAPI versions. Its parser in `@hey-api/shared` 0.5.0 sends a Swagger 2.0
document down a path of its own, which moves `body` and `formData` parameters into the request
body, as `generated/heyapi-parser.txt` records. Its model is a body type per
operation, with the same members from either file. It also reads `x-nullable`: `note` is
`string | null` in both outputs. The 3.0 copy adds a `NewOrder2` alias for the shared body.

Swagger Codegen's versioning page lists Swagger 2.0 for both lines,[^1] and its 3.X support line reads
"2.0 (by using engine + generators of 2.X), 3.0.X" in full. The run disagrees with that line. With
`typescript-fetch`, 3.0.85 wrote the same `api.ts` from the 2.0 file as from the 3.0 copy, and not
what 2.4.53 wrote. It has a model class for each inline body, and checks the optional `email`,
`phone` and `caption` as required. 2.4.53 names the inline body after its parameter and leaves form
fields optional.

## Check it worked

The suite compares both runs, fails on a removed entity, a changed one and one with no attributes,
and checks every record `generate.sh` wrote:

```bash
node --test entity-model.test.mjs
```

```text output
1..12
# tests 12
# suites 0
# pass 12
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 3938.538167
```

## When it goes wrong

An entity comes out with no attributes. The extractor read `requestBody` alone, which only the 3.0
copy has. `naive.mjs` reads response schemas in both versions and request bodies from
`requestBody` only:

```bash
node naive.mjs
```

```text output
naive extractor: request bodies from requestBody only
entity     swagger 2.0  openapi 3.0
artwork              0            2
customer             0            3
order                5            5
quote                0            3
no attributes from the 2.0 file: artwork, customer, quote
```

The order survives because its response schema names its fields. The other three have only a
request body, so they arrive empty from the 2.0 file.[^2] Read `in: body` and `in: formData` as the
body, or convert first. In CI, compare the attribute counts of both runs and refuse an entity with
none, since a fault both runs share passes the comparison.

A nullable field loses its null. A Swagger 2.0 reader that ignores `x-nullable`, as apidef does,
types the field as plain string. Convert first if the model must carry it, or check the diff for
`fields.<name>.t` lines.

## When not to do this

Do not convert a document only to feed apidef. On this document the direct run gave the same
attributes. The conversion adds a file to regenerate, a tool to pin, and a second place to look
when a field is wrong.

Do not build an apidef model for an SDK that Hey API or Swagger Codegen generates, since neither
reads it. Hey API fits a TypeScript SDK whose nullable fields must stay nullable from the 2.0 file.
Swagger Codegen 2.4.53 fits a client in a language Hey API does not write, read from the 2.0 file
with its optional form fields intact.

Skip direct extraction when another tool in the pipeline reads only OpenAPI 3, or when a nullable
field must stay nullable. The converted copy then serves every tool, and apidef reads it as well.

## Related how-tos

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

- [Migrate a Swagger 2 document to OpenAPI 3.1](/howto/migrate-swagger-2-to-openapi-3-1)

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

- [Publish an OpenAPI 3.0 copy beside your 3.1 document](/howto/publish-openapi-3-0-alongside-3-1)

## Last verified

Verified 2026-11-22 against Node 22.23.5, @voxgig/apidef 8.32.4 and swagger2openapi 7.0.8, with
apidef 8.33.1 recorded by `generate.sh`. Hey API 0.99.0 and Swagger Codegen 3.0.85 and 2.4.53 ran
once in `generate.sh`, and the page reads what they wrote. AutoRest was not run.

[^1]: The two lines have different Maven group ids, `io.swagger` for 2.X and
`io.swagger.codegen.v3` for 3.X, as the [versioning page](https://swagger.io/docs/open-source-tools/swagger-codegen/codegen-v3/versioning/)
notes. The [metadata of the 2.X group](https://repo.maven.apache.org/maven2/io/swagger/swagger-codegen-cli/maven-metadata.xml)
names 3.0.0-rc1 as both its `latest` and its `release`, a candidate of the other line, although
the highest 2.X version it lists is 2.4.53.

[^2]: The [Swagger 2.0 specification](https://swagger.io/specification/v2/#parameter-object)
allows one `body` parameter at most, because in its words "there can only be one payload" in a
request. It rules out form parameters beside it, since they travel in the payload too. In
[OpenAPI 3.0](https://spec.openapis.org/oas/v3.0.3.html#parameter-object) a parameter is in the
query, a header, the path or a cookie. The payload has a request body object of its own, and that
object is where an extractor written for 3.0 looks.