How to Convert OpenAPI to Go - Step by Step Guide

From an OpenAPI 3 or Swagger 2 file to Go structs you can decode responses into

Step 1

Paste or upload the spec

Paste an OpenAPI 3 or Swagger 2.0 file in YAML or JSON. The converter looks at components/schemas (OpenAPI 3) or definitions (Swagger 2) and writes one Go type per schema:

•
Paste it: copy the spec from Swagger Editor, your repository or an API's docs page
•
Upload a file: click "Upload" to open an openapi.yaml, swagger.json or .yml file
•
Try the sample: click "Sample" to load a small User API with two schemas

Example: a spec with two schemas

Pet and NewPet, with a description and an int32 field:

openapi: 3.0.3
info:
  title: Pets
  version: 1.0.0
paths: {}
components:
  schemas:
    Pet:
      type: object
      description: A pet in the store
      required: [id, name]
      properties:
        id: { type: integer, format: int64 }
        name: { type: string }
        species: { type: string }
        age: { type: integer, format: int32 }
    NewPet:
      type: object
      required: [name]
      properties:
        name: { type: string }
        species: { type: string }
Step 2

Read the generated types

Each schema becomes an exported Go type with encoding/json tags that keep the original key:

•
Numbers: integer follows its format (int32, int64) and is int64 without one; number is float64
•
Optional fields: anything not in required, or marked nullable, is a pointer with omitempty
•
References: $ref: '#/components/schemas/Pet' uses the Pet type, and a schema that points back at itself gets a pointer

Example: the Go code for the spec above

This is exactly what the converter writes for the Step 1 example:

package apiclient

// Types for the components/schemas of "Pets" 1.0.0. Decode a response with json.Unmarshal(body, &v).

// A pet in the store
type Pet struct {
	ID      int64   `json:"id"`
	Name    string  `json:"name"`
	Species *string `json:"species,omitempty"`
	Age     *int32  `json:"age,omitempty"`
}

type NewPet struct {
	Name    string  `json:"name"`
	Species *string `json:"species,omitempty"`
}
Step 3

Copy the file into your Go project

Set the package name in the field above the editors (lowercase, like api or models; anything Go won't accept is cleaned up and mentioned in a Note), then copy or download the file. Decoding a response looks like this:

resp, err := http.Get("https://api.example.com/pets/1")
if err != nil {
	return err
}
defer resp.Body.Close()

var pet apiclient.Pet
if err := json.NewDecoder(resp.Body).Decode(&pet); err != nil {
	return err
}
if pet.Species != nil {
	fmt.Println(pet.Name, *pet.Species)
}

Want to check the spec first? The OpenAPI Validator points out structural problems before you generate code.

What is OpenAPI to Go Conversion?

An OpenAPI (or older Swagger) file describes the shapes of the JSON an API sends and receives. Writing the matching Go structs by hand is slow and easy to get subtly wrong: a field that should be a pointer, a tag with a typo, an int that overflows on a real ID. Generating them from the spec keeps your code and the API contract in step.

The output is plain Go that you can read and edit. Field names follow Effective Go naming, the json tag keeps the key exactly as the API spells it, and comments carry descriptions, defaults and allowed enum values from the spec.

This page only writes the data types. If you want a whole client with a method for every endpoint, oapi-codegen and go-swagger are the usual choices. Got a JSON Schema instead of a full spec? Try JSON Schema to Go, or JSON to Go if all you have is a sample response.

Frequently Asked Questions

Which OpenAPI versions and formats can I paste?

OpenAPI 3.0 and 3.1 and Swagger 2.0, as YAML or JSON. The schemas are read from components/schemas in OpenAPI 3 and from definitions in Swagger 2. Paths, parameters and inline request or response schemas are not turned into types; if you need one of those, move it into components/schemas and point at it with $ref.

How are OpenAPI types mapped to Go?

string becomes string, number becomes float64 and boolean becomes bool. An integer follows its format: int32 gives int32, int64 gives int64, and an integer with no format is int64, so a long ID like 8901240544102066246 always fits. If a limit or enum value is bigger than int64 the field becomes uint64 (when it can never be negative) or json.Number. Arrays become slices, an object with additionalProperties becomes a map, and an object with properties becomes its own struct named after the parent and the field, such as OrderShippingAddress.

What happens to required, nullable and optional fields?

A field listed in required is a plain value with a plain json tag. A field that is not required, or is marked nullable (or x-nullable in Swagger 2, or has "null" in its type list in OpenAPI 3.1), becomes a pointer such as *string, so you can tell a missing value from an empty one. Optional fields also get omitempty. Slices, maps and interface{} stay as they are, because they can already be nil.

How are $ref, allOf, oneOf and enums handled?

A $ref to another schema in the same file uses that schema's Go type. A schema that refers back to itself, directly or through another one, gets a pointer so the type is valid Go. allOf is merged into one struct with every property and required field from its parts. oneOf and anyOf with more than one shape become interface{}, with a Note explaining it, because Go has no union type. String enums become a named type with one constant per value (StatusInTransit for "in-transit"), and integer enums get a comment listing the allowed values.

Are default and enum values copied exactly?

Yes. Defaults and enum values are written into comments exactly as they appear in the spec, so 8901240544102066246 keeps every digit, "00501" keeps its leading zeros and 14.50 keeps its trailing zero. Field names follow Go conventions with the usual initialisms (user_id becomes UserID), while the json tag keeps the original key. Two keys that would get the same Go name, like first-name and firstName, get FirstName and FirstName2.

Is this a full API client generator?

No, it writes the data model structs only. For a client with one method per endpoint, look at oapi-codegen (OpenAPI 3) or go-swagger (Swagger 2). The structs here are a good fit when you want to write your own HTTP calls with net/http or another client and just need types that match the spec.

Is my spec uploaded anywhere?

No. The spec is read and converted in your browser and is not sent to our server. Nothing is kept either: a reload starts with an empty editor.