How-to › Describe your API

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.

Audience
Library maintainer
Level
intermediate
Topic
Extract a semantic model from a spec
Languages
TypeScript
Verified

Read first: Classify OpenAPI operations into CRUD kinds by path shape

The API’s owners publish Swagger 2.0 and will not move to OpenAPI 3. Your extractor was written for 3.0 and reads request bodies from requestBody, which Swagger 2.0 does not have. Every entity whose fields live in an in: body or in: formData parameter comes out with no attributes, so the SDK built from that model has nothing to send.

What you get

You will end up with two entity models, one from the Swagger 2.0 file and one from its OpenAPI 3.0 copy, and a check that fails if any entity’s attributes differ. This is for you if you extract models from a document you cannot change.

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.

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

ApproachWhen it fitsWhat it costs youWhen to pick something else
apidef reading Swagger 2 directlysdkgen is the only consumer of the modelOne step, but x-nullable is ignored, so a nullable field reads as a plain stringOther tools in the pipeline need an OpenAPI 3 file
Hey APIYour SDK is TypeScript generated by Hey APIKeeps a body type per operation and no entities, so there is no attribute list to compareYou need one record type per resource
Swagger CodegenYour clients come from Swagger Codegen and must read the 2.0 fileTwo lines to choose between, and 3.0.85 checks optional form fields as requiredYou need entities rather than a model class per schema
swagger2openapi then apidefOther tools in your pipeline read only OpenAPI 3A second artifact to regenerate on every change, and one more place to looksdkgen 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 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 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:

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:

node extract.mjs
@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.

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 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:

node probe.mjs
@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:

node generators.mjs
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 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:

node --test entity-model.test.mjs
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:

node naive.mjs
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.

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.

Footnotes

  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 notes. The metadata of the 2.X group 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. ↩︎ Back to text

  2. The Swagger 2.0 specification 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 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. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.