# How to migrate a Swagger 2 document to OpenAPI 3.1

> Convert a Swagger 2.0 file to 3.0 and then 3.1 with two pinned tools, prove nothing was lost, and re-check form bodies, servers, and the keywords 3.1 rewrote.

Source: https://voxgig.com/howto/migrate-swagger-2-to-openapi-3-1

- Audience: api-producer
- Level: intermediate
- Verified: 2026-11-22
- Published: 2026-11-22

## Short answer

Convert the Swagger 2.0 file with swagger2openapi to 3.0, then with openapi-format --convertTo 3.1, applying an overlay that names every server. Compare the operations, schemas and form fields of all three documents, and review each schema 3.1 rewrote. Keep the 3.0 copy for generators that mishandle 3.1, because Swagger Codegen 3.0.85 drops the path parameters of the 3.1 file.

---
## You will need

Node 22 or later and the Swagger 2.0 document. Every command here is JavaScript on Node, run in
the sample directory after `npm ci`. The sample document is a pet store with eight operations, a
JSON body, a multipart upload, and a URL-encoded form. Moving `definitions` to components is the
subject of the prerequisite on
[reusing schemas and responses with components and `$ref`](/howto/reuse-schemas-with-components-and-ref).

## 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/main/docs/reference/model.md) | You generate SDKs with sdkgen and nothing else needs 3.x | No migration, but `x-nullable` is ignored, so a nullable field reads as a plain string | Docs tools or other generators need a 3.x file |
| [Fern overlays](https://buildwithfern.com/learn/api-definitions/openapi/overlays) | Fern generates your SDKs from the converted 3.1 file | Fixes live in an overlay file, and generation needs a login, a guest session, or Docker | You want every fix inside the document itself |
| [Hand migration](https://openapis.org/blog/2021/02/16/migrating-from-openapi-3-0-to-3-1-0/) | A small document with design debt you want to pay off in the move | Hours of review per document, and every hand edit is a chance to drift | The document is large or still changing weekly |
| [Swagger Codegen](https://swagger.io/docs/open-source-tools/swagger-codegen/codegen-v3/versioning/) | Your clients come from Swagger Codegen 3.x | Reads 2.0 and 3.0 alike, and writes a broken client from this 3.1 file | Your generator reads 3.1 correctly |
| [swagger2openapi plus openapi-format](https://github.com/Mermade/oas-kit/tree/main/packages/swagger2openapi) | Most documents: two pinned steps, rerun on every change to the source | Carries every ambiguity across, and 3.1 keywords still need a review | The source is being retired, so a one-off hand edit is cheaper |

Voxgig maintains apidef. The converters, Fern and Swagger Codegen are other projects, and the
pipeline on this page runs without apidef.

The pipeline is the default because it reruns. A hand migration fixes design debt that a
converter carries over, and costs hours. Staying on 2.0 costs nothing until a tool needs 3.x, and a
2.0 reader such as apidef ignores `x-nullable`, an extension rather than a 2.0 keyword.

## Convert in two hops

`convert.mjs` runs `swagger2openapi` and then
[`openapi-format`](https://github.com/thim81/openapi-format) on a scratch folder, and compares the
result with the committed `converted/` files. swagger2openapi 7.0.8, published on 2021-07-07, is
the last release on npm and is not deprecated. The last commit on the `main` branch of its
oas-kit repository is from the same day, as `generate.sh` recorded on 2026-11-22. `--no-sort` keeps the second hop's changes to the
3.1 rewrite, because openapi-format otherwise sorts the keys.

The first hop moves `definitions` to `components.schemas`, `securityDefinitions` to
`securitySchemes`, body and `formData` parameters to `requestBody`, and `x-nullable` to
`nullable`. Swagger 2.0 has one `host`, one `basePath`, and a list of schemes, and here the
converter writes one server from them. Neither hop adds an environment, so the overlay names that
server and adds staging, through the
[Overlay specification](https://spec.openapis.org/overlay/v1.1.0.html) that openapi-format applies.

```yaml title="spec/servers.overlay.yaml"
overlay: 1.1.0
info:
  title: Name every environment the converted document must reach
  version: 1.0.0
actions:
  - target: $.servers[?(@.url == 'https://api.example.com/v1')]
    update:
      description: Production
      x-fern-server-name: Production
  # One object, appended to the array. Overlay 1.0.0 and 1.1.0 both read it that way.
  - target: $.servers
    update:
      url: https://staging.example.com/v1
      description: Staging
      x-fern-server-name: Staging
```

```bash
node convert.mjs
```

```text output
swagger2openapi 7.0.8   spec/petstore-swagger2.json -> 3.0.0
openapi-format 1.34.0   --convertTo 3.1 --no-sort --overlayFile spec/servers.overlay.yaml -> 3.1.0
converted/petstore-oas30.json: same as this run
converted/petstore-oas31.json: same as this run
```

## Compare the documents before and after

`inventory.mjs` reads each document into the same shape: operations with their ids and
parameters, schemas with every property, security schemes, form bodies with their fields, and
servers. It exits 1 if
any of them differ between the three, or if a file field sits outside a multipart body.

```bash
node inventory.mjs
```

```text output
versions: 2.0 -> 3.0.0 -> 3.1.0
ops       8 / 8 / 8  same in all three
params    6 / 6 / 6  same in all three
schemas   4 / 4 / 4  same in all three
fields    9 / 9 / 9  same in all three
security  2 / 2 / 2  same in all three
form      POST /owners: application/x-www-form-urlencoded; email, name*  same in all three
form      POST /pets/{petId}/photo: multipart/form-data; caption, file* (file)  same in all three
servers   2.0: https://api.example.com/v1
servers   3.0.0: https://api.example.com/v1
servers   3.1.0: https://api.example.com/v1 (Production), https://staging.example.com/v1 (Staging)
for a second review, 3.0 -> 3.1:
  #/paths/~1pets/get/parameters/0/schema
    {"type":"integer","minimum":0,"maximum":100,"exclusiveMinimum":true} -> {"type":"integer","maximum":100,"exclusiveMinimum":0}
  #/paths/~1pets~1{petId}~1photo/post/requestBody/content/multipart~1form-data/schema/properties/file
    {"type":"string","format":"binary"} -> {"type":"string","contentMediaType":"application/octet-stream"}
  #/components/schemas/NewPet/properties/name
    {"type":"string","example":"Rex"} -> {"type":"string","examples":["Rex"]}
  #/components/schemas/NewPet/properties/tag
    {"type":"string","nullable":true} -> {"type":["string","null"]}
  #/components/schemas/NewPet/properties/weight
    {"type":"number","minimum":0,"exclusiveMinimum":true} -> {"type":"number","exclusiveMinimum":0}
```

Both hops kept all eight operations, six parameters, nine schema properties, two security
schemes, and both form bodies, with their `required` flags. The asterisk marks a required field. The five schemas at the end are
the 3.1 rewrites: `nullable` became a type array, a boolean `exclusiveMinimum` became a number,
`example` became `examples`, and `format: binary` became `contentMediaType`. Each is correct and
each changes what a tool reads, so review them one by one.

## Check both hops against one model

apidef reads Swagger 2.0 and OpenAPI 3.x alike, so its model of each document is a comparison
that spans both hops. `models.mjs` builds it with `@voxgig/apidef` 8.32.4, the release
[`@voxgig/create-sdkgen`](https://github.com/voxgig/create-sdkgen) 0.31.9 installs, and diffs the
three.

```bash
node models.mjs
```

```text output
apidef 8.32.4
  spec/petstore-swagger2.json     owner(create list), pet(create list load remove update)
  converted/petstore-oas30.json   owner(create list), pet(create list load remove update)
  converted/petstore-oas31.json   owner(create list), pet(create list load remove update)
2.0 against 3.0: 9 values differ
  8 of them co.source, "swagger2" -> "openapi3"
  entity.pet.fields.tag.t: "`$STRING`" -> ["`$ONE`",["`$STRING`","`$NULL`"]]
3.0 against 3.1: 4 values differ
  entity.pet.op.create.points.0.rb.fields.1.media: undefined -> "application/octet-stream"
  info.servers.0.description: undefined -> "Production"
  info.servers.0.x-fern-server-name: undefined -> "Production"
  info.servers.1: undefined -> {"description":"Staging","url":"https://staging.example.com/v1","x-fern-server-name":"Staging"}
```

apidef builds the same two entities from all three files. Between 2.0 and 3.0 the only
change apart from `co.source` is `tag`: apidef reads `x-nullable: true` as a plain string, and
reads the `nullable: true` the converter wrote as string or null. Between 3.0 and 3.1, the file field of
the upload gains a media type and the servers carry the overlay. `generate.sh` ran the same script on
apidef 8.33.1, the newest release, into `generated/apidef-8.33.1.txt`, with the same result.

## Run oasdiff on the second hop

[oasdiff](https://github.com/oasdiff/oasdiff/blob/main/docs/BREAKING-CHANGES.md) v1.39.0 declares
Go 1.26, a toolchain the gate lacks, so `generate.sh` ran it once and recorded each run with its
exit status. `oasdiff-report.mjs` reads the records.

```bash
node oasdiff-report.mjs
```

```text output
oasdiff version 1.39.0
its go.mod: go 1.26.0
breaking 3.0 -> 3.1: 3 errors, 5 warnings, exit 0; with --fail-on ERR, exit 1
  request-property-became-not-nullable  in API POST /pets
    the request property `tag` became not nullable
  request-property-became-not-nullable  in API PUT /pets/{petId}
    the request property `tag` became not nullable
  request-property-content-media-type-changed  in API POST /pets/{petId}/photo
    the `file` request property contentMediaType changed from `` to `application/octet-stream`
summary 3.0 -> 3.1: endpoints modified: 6; paths modified: 4; requestBodies modified: 1; schemas modified: 2; servers added: 1 modified: 1
summary 2.0 -> 3.0: endpoints modified: 7; paths modified: 5; requestBodies added: 1; schemas added: 4; securitySchemes added: 2; servers added: 1
```

Between 3.0 and 3.1 the summary shows nothing deleted, and the one addition is the overlay's server. `breaking` calls
three changes errors and still exits 0, so a CI step needs `--fail-on ERR`. Two of those errors
say `tag` became not nullable, although its 3.1 type still includes `null`. Given the Swagger 2.0
file, oasdiff reports every converted definition as added, so it cannot check the first hop.

## Give each generator the document it reads

`generate.sh` ran Swagger Codegen 3.0.85 on all three documents and summarized each client.

```bash
node generators.mjs
```

```text output
Swagger Codegen 3.0.85, typescript-fetch, one run per document
  swagger2  6 interfaces  uploadPhoto(file: Blob, caption: string, petId: number)
  oas30     6 interfaces  uploadPhoto(file: Blob, caption: string, petId: number)
  oas31     5 interfaces  uploadPhoto(file: any, caption: any)
  swagger2 and oas30 runs identical: true
  oas31: no Pet; {petId} never filled in deletePet, getPet, updatePet, uploadPhoto
  swagger2 optional form fields checked as required: caption, email
  oas30    optional form fields checked as required: caption, email
  oas31    optional form fields checked as required: caption, email
fern-api 5.227.0, cli.cjs, read and not run
  bundles: name:"swagger2openapi",version:"7.0.8"
  detects: e.swagger&&e.swagger==="2.0")return yC.OAS2
```

Swagger Codegen reads Swagger 2.0 directly and writes the same client as from the 3.0 copy. On
the 3.1 copy it exits 0 and writes a client with no `Pet` type, `any` for every parameter outside a
JSON body, and four methods whose `{petId}` is never filled in. It also checks `caption` and `email` as required on
every input, although the documents require neither. Keep feeding it the 2.0 or 3.0 file.

Fern was not run here: [remote generation needs a login, a token, or a guest session, and
`--local` runs on Docker or Podman](https://buildwithfern.com/learn/cli-api-reference/cli-reference/sdk-commands). Its
[OpenAPI overview](https://buildwithfern.com/learn/api-definitions/openapi/overview) says it is
compatible with OpenAPI 3.1.1, and does not mention Swagger 2.0. Its [`sdk-config.yml` reference](https://buildwithfern.com/learn/sdks/current/reference/sdk-config)
accepts `swagger` as a spec `type`, and the `cli.cjs` file of the `fern-api` 5.227.0 package
holds swagger2openapi 7.0.8's metadata and a check for `swagger: "2.0"`. Point Fern at the 3.1
copy, and list the overlay under `source.specs[].overlays` there, or in `generators.yml`, the
legacy format its overlays page shows. Its [servers page](https://buildwithfern.com/learn/api-definitions/openapi/servers) recommends
`x-fern-server-name` to name each server, which is why the overlay sets it. Fern's overlays page links the 1.0.0 specification, and this page did
not check what Fern makes of a 1.1.0 overlay.

Fern is the better fit when overlays are your only way to change a document you do not own.
Swagger Codegen fits when its client must come from the 2.0 file directly.

## Check it worked

The suite reruns the pipeline, compares the inventories, and fails on a removed operation and on
a changed `required` flag:

```ts title="migrate.test.mjs"
test('the comparison fails on a lost operation and on a changed required flag', () => {
  const lost = docs()
  delete lost[2].paths['/owners']
  assert.equal(report(lost).failed, true)
  const changed = docs()
  changed[1].paths['/owners'].post.requestBody.content['application/x-www-form-urlencoded'].schema.required = []
  assert.equal(report(changed).failed, true)
  assert.throws(() => inventory({ openapi: '3.2.0', paths: {} }), /not Swagger 2.0 or OpenAPI 3.0\/3.1/)
  assert.throws(() => inventory({ swagger: '2.0', paths: {} }), /no operations/)
})
```

```bash
node --test migrate.test.mjs
```

```text output
1..15
# tests 15
# suites 0
# pass 15
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 2528.323988
```

## When it goes wrong

An upload arrives with no file. The operation had no `consumes` of its own, so it inherited the
document's JSON one, and the converter fell back to `application/x-www-form-urlencoded`.
`pitfall.mjs` removes that `consumes` and converts again.

```bash
node pitfall.mjs
```

```text output
POST /pets/{petId}/photo with no consumes of its own (the document says application/json)
  2.0    application/json
         PROBLEM POST /pets/{petId}/photo: file field file in application/json
  3.0.0  application/x-www-form-urlencoded
         PROBLEM POST /pets/{petId}/photo: file field file in application/x-www-form-urlencoded
  3.1.0  application/x-www-form-urlencoded
         PROBLEM POST /pets/{petId}/photo: file field file in application/x-www-form-urlencoded
```

Swagger 2.0 allows a file in that media type,[^1] so neither converter complains. Give every
`formData` operation its own `consumes` before converting, and keep the inventory's check in CI.

The overlay adds no staging server. [Overlay 1.0.0](https://spec.openapis.org/overlay/v1.0.0.html)
already says an update aimed at an array is "an entry to append" to it, and 1.1.0 says the same
of an object. `overlay-arrays.mjs` runs openapi-format 1.34.0 on each case.

```bash
node overlay-arrays.mjs
```

```text output
openapi-format 1.34.0, update on $.servers
  overlay 1.0.0, object -> https://api.example.com/v1
  overlay 1.0.0, array  -> https://api.example.com/v1, https://staging.example.com/v1
  overlay 1.1.0, object -> https://api.example.com/v1, https://staging.example.com/v1
  overlay 1.1.0, array  -> https://api.example.com/v1, https://staging.example.com/v1
```

Under `overlay: 1.0.0` the tool drops a lone object and exits 0, against the 1.0.0 text. Declare
`1.1.0`, or wrap the object in an array.

## When not to do this

Do not migrate a document only because a converter exists. If your one consumer is sdkgen,
apidef builds the same entities from the 2.0 file, and the migration adds two artifacts to keep in
step.

Do not give the 3.1 copy to Swagger Codegen 3.0.85. Its client from that file is worse than the
one from the 2.0 original. If Fern generates your SDKs, migrate, because its documentation
describes 3.1 and its fixes live in overlays.

Skip the pipeline if the source is frozen. A one-off migration by hand, reviewed once, ends the
two-file problem for good.

## Related how-tos

- [Reuse schemas and responses with components and $ref](/howto/reuse-schemas-with-components-and-ref)

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

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

- [Normalize an inconsistent spec before extracting a model](/howto/normalise-an-inconsistent-spec-before-extraction)

## Last verified

Verified 2026-11-22 against Node 22.23.5, swagger2openapi 7.0.8, openapi-format 1.34.0 and
@voxgig/apidef 8.32.4. Swagger Codegen 3.0.85 and oasdiff v1.39.0 ran once, in `generate.sh`, and
the page reads what it recorded. Fern was not run: its part comes from its documentation and from
reading the `fern-api` 5.227.0 package.

[^1]: The [Swagger 2.0 specification](https://swagger.io/specification/v2/) says that for a
parameter of type `file`, consumes must be `multipart/form-data`, `application/x-www-form-urlencoded`
or both. The HTML standard's [serializer for URL-encoded forms](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#convert-to-a-list-of-name-value-pairs)
replaces a file entry with the file's name, so a browser form sent that way delivers the name of
the photo and not the photo.