oapi-codegen

module
v2.0.0-...-2ada9f5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: Apache-2.0

README

oapi-codegen

OpenSSF Best Practices

oapi-codegen is a command-line tool and library to convert OpenAPI specifications to Go code, be it server-side implementations, API clients, or simply HTTP models.

Using oapi-codegen allows you to reduce the boilerplate required to create or integrate with services based on OpenAPI 3.0 and OpenAPI 3.1, and instead focus on writing your business logic, and working on the real value-add for your organisation.

With oapi-codegen, there are a few Key Design Decisions we've made, including:

  • idiomatic Go, where possible
  • fairly simple generated code, erring on the side of verbose code over complex modular code
  • supporting as much of OpenAPI 3.0 and 3.1 as is possible, alongside Go's type system

oapi-codegen is one part of a wider ecosystem, which can be found described in further detail in the oapi-codegen organisation on GitHub.

⚠️ This README may be for the latest development version, which may contain unreleased changes. Please ensure you're looking at the README for the latest release version.

Table of Contents

Installation

Action Required: The repository for this project has changed

As announced in May 2024, we have moved the project from the Deepmap organization to our own organization, and you will need to update your import paths to pull updates past this point. You need to do a recursive search/replace from github.com/deepmap/oapi-codegen/v2 to github.com/ifc7/oapi-codegen/v2.

[!IMPORTANT] oapi-codegen moved to its new home with the version tag v2.3.0.

If you are using v2.2.0 or below, please install like so:

# for the binary install
go install github.com/deepmap/oapi-codegen/v2/cmd/oapi-codegen@v2.2.0

If you are using v2.3.0 or above, please install like so, using the new module import path:

# for the binary install
go install github.com/ifc7/oapi-codegen/v2/cmd/oapi-codegen@latest
Installing

oapi-codegen requires Go 1.26+ to build and install. Note that the generated code has its own, lower requirements — see Generating server-side boilerplate.

It is recommended to use go tool support for managing the dependency of oapi-codegen alongside your core application.

To do this, you run go get -tool:

$ go get -tool github.com/ifc7/oapi-codegen/v2/cmd/oapi-codegen@latest
# this will then modify your `go.mod`

From there, each invocation of oapi-codegen would be used like so:

//go:generate go tool oapi-codegen -config cfg.yaml ../../api.yaml

Alternatively, you can install it as a binary with:

$ go install github.com/ifc7/oapi-codegen/v2/cmd/oapi-codegen@latest
$ oapi-codegen -version

Which then means you can invoke it like so:

//go:generate oapi-codegen --config=config.yaml ../../api.yaml
Pinning to commits

While the project does not (yet) have a defined release cadence, there may be cases where you want to pull in yet-unreleased changes to your codebase.

Therefore, you may want to pin your dependency on oapi-codegen to a given commit hash, rather than a tag.

This is officially recommended for consumers of oapi-codegen, who want features/bug fixes that haven't yet been released.

We aim to keep the default branch ready-to-release so you should be able to safely pin.

To do so, you can run:

# pin to the latest version on the default branch
$ go get github.com/ifc7/oapi-codegen/v2@main
# alternatively, to a commit hash i.e. https://github.com/oapi-codegen/oapi-codegen/commit/71e916c59688a6379b5774dfe5904ec222b9a537
$ go get github.com/ifc7/oapi-codegen/v2@71e916c59688a6379b5774dfe5904ec222b9a537

This will then make a change such as:

diff --git go.mod go.mod
index 44f29a4..436a780 100644
--- go.mod
+++ go.mod
@@ -2,21 +2,20 @@
-require github.com/ifc7/oapi-codegen/v2 v2.1.0
+require github.com/ifc7/oapi-codegen/v2 v2.1.1-0.20240331212514-80f0b978ef16

Usage

oapi-codegen is configured using a YAML configuration file, to simplify the number of flags that users need to remember, and to make reading the go:generate command less daunting. Prefer the configuration file to command line options, which only cover a subset of it.

For full details of what is supported, check out the oapi-codegen configuration documentation.

The spec is loaded with libopenapi.

We also have a JSON Schema that can be used by IDEs/editors with the Language Server Protocol (LSP) to perform intelligent suggestions, i.e.:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
package: api
# ...

Note that it's recommended to pin to a specific version of the configuration schema, so it matches the version of oapi-codegen you're using. For instance, if you're using Renovate, you can have Renovate automagically update this version for you.

Features

At a high level, oapi-codegen supports:

  • Generating net/http server-side boilerplate (docs)
  • Generating client API boilerplate (docs)
  • Generating the types (docs)
  • Splitting large OpenAPI specs across multiple packages(docs)
    • This is also known as "Import Mapping" or "external references" across our documentation / discussion in GitHub issues

What does it look like?

Below we can see a trimmed down example taken from the OpenAPI Petstore example. For each operation, oapi-codegen generates a request object holding its parameters and body, a response type for each response the spec declares, and a method on the ServerInterface:

// generated code

type FindPetsRequestObject struct {
	Params FindPetsParams
}

type FindPetsResponseObject interface {
	VisitFindPetsResponse(w http.ResponseWriter) error
}

// FindPets200JSONResponse is the 200 response, a JSON array of pets.
type FindPets200JSONResponse []Pet

// FindPetsdefaultJSONResponse is the default response, with any status code.
type FindPetsdefaultJSONResponse struct {
	Body       Error
	StatusCode int
}

type ServerInterface interface {
	// FindPets Returns all pets
	// (GET /pets)
	FindPets(ctx context.Context, request FindPetsRequestObject) (FindPetsResponseObject, error)
	// ...
}

It also generates the net/http handler that serves each operation: it binds the request's parameters and body into the request object, calls your ServerInterface, and writes the response object you return:

// generated code

// FindPets serves the FindPets operation.
func (sh *serverHandler) FindPets(w http.ResponseWriter, r *http.Request) {
	var err error

	// Parameter object where we will unmarshal all parameters from the request
	var params FindPetsParams

	// ------------- Optional query parameter "limit" -------------

	if values_, found_ := r.URL.Query()["limit"]; found_ {
		var value_ int32
		// ... parse the value, or call sh.options.RequestErrorHandlerFunc and return
		params.Limit = &value_
	}

	var request FindPetsRequestObject

	request.Params = params

	handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request any) (any, error) {
		return sh.si.FindPets(ctx, request.(FindPetsRequestObject))
	}
	for _, middleware := range sh.options.Middlewares {
		handler = middleware(handler, "FindPets")
	}

	response, err := handler(r.Context(), w, r, request)

	if err != nil {
		sh.options.ResponseErrorHandlerFunc(w, r, err)
	} else if validResponse, ok := response.(FindPetsResponseObject); ok {
		if err := validResponse.VisitFindPetsResponse(w); err != nil {
			sh.options.ResponseErrorHandlerFunc(w, r, err)
		}
	} else if response != nil {
		sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response))
	}
}

// HandlerWithOptions creates an http.Handler with routing matching the
// OpenAPI spec, configured by options.
func HandlerWithOptions(si ServerInterface, options ServerOptions) http.Handler {
	// ...
	sh := &serverHandler{si: si, options: options}

	m.HandleFunc(http.MethodGet+" "+options.BaseURL+"/pets", sh.FindPets)
	// ...
	return m
}

Then, in your own code, you implement the underlying logic for the FindPets implementation:

type PetStore struct {
	Store *Store
}

// Make sure we conform to ServerInterface
var _ api.ServerInterface = (*PetStore)(nil)

func (p *PetStore) FindPets(ctx context.Context, request api.FindPetsRequestObject) (api.FindPetsResponseObject, error) {
	result := p.Store.FindPets(request.Params.Tags, request.Params.Limit)
	return api.FindPets200JSONResponse(result), nil
}

And serve it with the generated Handler, an ordinary http.Handler:

h := api.Handler(NewPetStore())
log.Fatal(http.ListenAndServe(":8080", h))

This lets you focus on the business logic of each endpoint, rather than (un)marshalling types to and from JSON, or wrangling cookies or headers.

Key design decisions

  • Produce an interface that can be satisfied by your implementation, with reduced boilerplate
  • Bulk processing and parsing of OpenAPI document in Go
  • Resulting output is using Go's text/templates, which are user-overridable
  • Attempts to produce idiomatic Go
  • Support multiple OpenAPI files by having a package per OpenAPI file
  • Support of OpenAPI 3.0 and 3.1
    • OpenAPI 3.1 support includes webhooks and version-aware handling of 3.1 idioms such as type: [T, "null"] nullability and enums declared via oneOf + const
    • Note that this does not include OpenAPI 2.0 (aka Swagger), which oapi-codegen rejects. If you have an old Swagger specification, you can use a converter before using oapi-codegen.
  • Extract parameters from requests, to reduce work required by your implementation
  • Implicit additionalProperties are ignored by default (more details)
  • Prune unused types by default

Generating server-side boilerplate

oapi-codegen shines by making it fairly straightforward (note that this is a purposeful choice of wording here - we want to avoid words like "easy") to generate the server-side boilerplate for a backend API.

The generated server is built on the standard library's net/http, and takes inspiration from server-side code generation for RPC servers: each operation is a method that takes a request object and returns a response object,

FindPets(ctx context.Context, request FindPetsRequestObject) (FindPetsResponseObject, error)

so the contract the spec describes is the contract the compiler checks. The server supports:

  • multiple request/response media types and status codes on a given operation
  • first-class support for multipart/form-data and application/x-www-form-urlencoded requests
  • returning an HTTP 500 Internal Server Error, when an error is returned from a function
  • automagic (un)marshalling of request/responses, and setting content-type and HTTP status codes on responses
  • binding request values to a struct, a multipart.Reader or providing a io.Reader

To generate it, enable the server:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
package: api
generate:
  server: true
output: server.gen.go

See the server documentation for how to implement and run it. The generated Handler is an ordinary http.Handler, so it works with any router or middleware that accepts one. The generated server needs Go 1.22+, for the net/http routing patterns.

To provide you a fully Test Driven Development style test harness to confirm you are following the specification, you could use a tool such as openapi.tanna.dev/go/validator, or craft your own.

[!NOTE] This doesn't include validation of incoming requests.

[!IMPORTANT] When a spec uses $ref to point at a components/responses/... (or components/requestBodies/...) defined in another spec via import-mapping, the destination spec must also be generated with server: true. The server's response type embeds the <Name>JSONResponse type from the destination package; that type only exists when the destination generates a server. Without it the generated code will fail to compile with an "undefined" error. See issue #2010.

Generating API clients

As well as generating the server-side boilerplate, oapi-codegen can also generate API clients.

This aims to be an API client that can be used to interact with the methods of the API, and is perfectly suited for production usage.

However, if you were looking for a slightly more SDK-style approach, or a mix of generated tests and/or documentation, this API client may not be for you, and you may want to look at alternate tooling.

For instance, given an api.yaml:

openapi: "3.0.0"
info:
  version: 1.0.0
  title: Generate models
paths:
  /client:
    get:
      operationId: getClient
      responses:
        200:
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ClientType"
    put:
      operationId: updateClient
      responses:
        400:
          content:
            application/json:
              schema:
                type: object
                properties:
                  code:
                    type: string
                required:
                - code
components:
  schemas:
    ClientType:
      type: object
      required:
        - name
      properties:
        name:
          type: string
    # NOTE that this is not generated by default because it's not referenced. If you want it, you need to use the following YAML configuration:
    #
    # output-options:
    #   skip-prune: true
    Unreferenced:
      type: object
      required:
        - id
      properties:
        id:
          type: integer

And a cfg.yaml:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
package: client
output: client.gen.go
generate:
  models: true
  client: true

And a generate.go:

package client

//go:generate go run github.com/ifc7/oapi-codegen/v2/cmd/oapi-codegen -config cfg.yaml api.yaml

This would then generate:

package client

// ...

// ClientType defines model for ClientType.
type ClientType struct {
	Name string `json:"name"`
}

// ...

// Client which conforms to the OpenAPI3 specification for this service.
type Client struct {
	// The endpoint of the server conforming to this interface, with scheme,
	// https://api.deepmap.com for example. This can contain a path relative
	// to the server, such as https://api.deepmap.com/dev-test, and all the
	// paths in the swagger spec will be appended to the server.
	Server string

	// Doer for performing requests, typically a *http.Client with any
	// customized settings, such as certificate chains.
	Client HttpRequestDoer

	// A list of callbacks for modifying requests which are generated before sending over
	// the network.
	RequestEditors []RequestEditorFn
}

// ...

// The interface specification for the client above.
type ClientInterface interface {
	// GetClient request
	GetClient(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)

	// UpdateClient request
	UpdateClient(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error)
}

// ...

// ClientWithResponsesInterface is the interface specification for the client with responses above.
type ClientWithResponsesInterface interface {
	// GetClientWithResponse request
	GetClientWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetClientResponse, error)

	// UpdateClientWithResponse request
	UpdateClientWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*UpdateClientResponse, error)
}

type GetClientResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON200      *ClientType
}

// ...

With this generated client, it is then possible to construct and utilise the client, for instance:

package client_test

import (
	"context"
	"fmt"
	"log"
	"net/http"

	"github.com/ifc7/oapi-codegen/v2/examples/client"
)

func TestClient_canCall() {
	// custom HTTP client
	hc := http.Client{}

	// with a raw http.Response
	{
		c, err := client.NewClient("http://localhost:1234", client.WithHTTPClient(&hc))
		if err != nil {
			log.Fatal(err)
		}

		resp, err := c.GetClient(context.TODO())
		if err != nil {
			log.Fatal(err)
		}
		if resp.StatusCode != http.StatusOK {
			log.Fatalf("Expected HTTP 200 but received %d", resp.StatusCode)
		}
	}

	// or to get a struct with the parsed response body
	{
		c, err := client.NewClientWithResponses("http://localhost:1234", client.WithHTTPClient(&hc))
		if err != nil {
			log.Fatal(err)
		}

		resp, err := c.GetClientWithResponse(context.TODO())
		if err != nil {
			log.Fatal(err)
		}
		if resp.StatusCode() != http.StatusOK {
			log.Fatalf("Expected HTTP 200 but received %d", resp.StatusCode())
		}

		fmt.Printf("resp.JSON200: %v\n", resp.JSON200)
	}

}
Duplicate types generated for clients's response object types

When generating the types for interacting with the generated client, oapi-codegen will use the operationId and add on a Request or Response suffix.

However, this can clash if you have named your component schemas in a similar way.

For instance:

openapi: "3.0.0"
info:
  version: 1.0.0
  title: "Show that generated client boilerplate can clash if schemas are well named i.e. `*Request` and `*Response`"
paths:
  /client:
    put:
      operationId: updateClient
      requestBodies:
        application/json:
          schema:
            $ref: '#/components/schemas/UpdateClientRequest'
      responses:
        400:
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UpdateClientResponse'
components:
  schemas:
    UpdateClientRequest:
      type: object
      properties:
        code:
          type: string
      required:
      - code
    UpdateClientResponse:
      type: object
      required:
        - name
      properties:
        name:
          type: string

If you were to generate with this configuration:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
package: client
output: client.gen.go
generate:
  models: true
  client: true

This would then result in go build failures:

# github.com/ifc7/oapi-codegen/v2/examples/clienttypenameclash
./client.gen.go:184:6: UpdateClientResponse redeclared in this block
        ./client.gen.go:17:6: other declaration of UpdateClientResponse
./client.gen.go:192:7: r.HTTPResponse undefined (type UpdateClientResponse has no field or method HTTPResponse)
./client.gen.go:193:12: r.HTTPResponse undefined (type UpdateClientResponse has no field or method HTTPResponse)
./client.gen.go:200:7: r.HTTPResponse undefined (type UpdateClientResponse has no field or method HTTPResponse)
./client.gen.go:201:12: r.HTTPResponse undefined (type UpdateClientResponse has no field or method HTTPResponse)
./client.gen.go:224:3: unknown field Body in struct literal of type UpdateClientResponse
./client.gen.go:225:3: unknown field HTTPResponse in struct literal of type UpdateClientResponse
./client.gen.go:234:12: response.JSON400 undefined (type *UpdateClientResponse has no field or method JSON400)

To fix this, use the response-type-suffix Output Option:

 # yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
 package: client
 output: client.gen.go
 generate:
   models: true
   client: true
+output-options:
+  response-type-suffix: Resp

This will then rename the generated types from the default to use the new suffix:

-type UpdateClientResponse struct {
+type UpdateClientResp struct {
        Body         []byte
        HTTPResponse *http.Response
        JSON400      *UpdateClientResponse
 }

There is no currently planned work to change this behaviour.

Generating API models

If you're looking to only generate the models for interacting with a remote service, for instance if you need to hand-roll the API client for whatever reason, you can do this as-is.

[!NOTE] Generated models and clients need Go 1.20+, and the generated server Go 1.22+, for the net/http routing patterns. Generated code depends only on the standard library, plus github.com/google/uuid when the spec uses the uuid format, github.com/oapi-codegen/nullable with nullable-type.

[!TIP] Try to define as much as possible within the #/components/schemas object, as oapi-codegen will generate all the types here.

Although we can generate some types based on inline definitions in i.e. a path's response type, it isn't always possible to do this, or if it is generated, can be a little awkward to work with as it may be defined as an anonymous struct.

For instance, given an api.yaml:

openapi: "3.0.0"
info:
  version: 1.0.0
  title: Generate models
paths:
  /client:
    get:
      operationId: getClient
      responses:
        200:
          content:
            application/json:
              schema:
                # NOTE that Client is generated here, because it's within #/components/schemas
                $ref: "#/components/schemas/Client"
    put:
      operationId: updateClient
      responses:
        400:
          content:
            application/json:
              # NOTE that this anonymous object is /not/ generated because it's an anonymous, but would be generated if using `generate: client`
              # See https://github.com/oapi-codegen/oapi-codegen/issues/1512
              schema:
                type: object
                properties:
                  code:
                    type: string
                required:
                - code
components:
  schemas:
    Client:
      type: object
      required:
        - name
      properties:
        name:
          type: string
    # NOTE that this is not generated by default because it's not referenced. If you want it, you need to use the following YAML configuration:
    #
    # output-options:
    #   skip-prune: true
    Unreferenced:
      type: object
      required:
        - id
      properties:
        id:
          type: integer

And a cfg.yaml:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
package: onlymodels
output: only-models.gen.go
generate:
  models: true

And a generate.go:

package onlymodels

//go:generate go run github.com/ifc7/oapi-codegen/v2/cmd/oapi-codegen -config cfg.yaml api.yaml

This would then generate:

package onlymodels

// Client defines model for Client.
type Client struct {
	Name string `json:"name"`
}

If you wish to also generate the Unreferenced type, you would need the following cfg.yaml:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
package: onlymodels
output: only-models.gen.go
generate:
  models: true
output-options:
  # NOTE that this is only required for the `Unreferenced` type
  skip-prune: true

For a complete example see examples/only-models.

Format types

Most string formats map to standard library or well-known types (date-time to time.Time, uuid to uuid.UUID from github.com/google/uuid). The rest map to types declared in the generated package itself, alongside the models:

Format Go type Notes
date OpenAPIDate Embeds time.Time; marshals as 2006-01-02 (time.DateOnly)
duration OpenAPIDuration RFC 3339 duration with its components kept as parsed; ParseOpenAPIDuration, TimeDuration and OpenAPIDurationFromTimeDuration convert it
email OpenAPIEmail A string, validated and normalized when marshaled or unmarshaled as JSON; invalid addresses return ErrOpenAPIEmailValidation
binary OpenAPIFile Content from a multipart upload (InitFromMultipart) or memory (InitFromBytes), read with Bytes or Reader

Only the types the spec uses are declared. Each generated package declares its own, so admin.OpenAPIDate and common.OpenAPIDate are distinct types; all but OpenAPIFile convert into each other with a plain conversion, e.g. common.OpenAPIDate(d).

If you generate models for several specs into one package, set output-options.skip-format-types: true on all but one of them, so each type is declared once; the one without it must use every format the others do.

To use your own types instead, map the formats to them with type-mapping. A mapping's import is added to the generated code, and a parameter named after a package the mapping uses, such as uuid, is given a p prefix (pUuid) so it doesn't shadow that package.

Splitting large OpenAPI specs across multiple packages (aka "Import Mapping" or "external references")

When you've got a large OpenAPI specification, you may find it useful to split the contents of the spec across multiple files, using external references, such as:

      responses:
        200:
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'

This is supported by oapi-codegen, through the ability to perform "Import Mapping".

[!NOTE] The keys of import-mapping are the paths of the $ref'd documents — a relative file path or a URL, exactly as it is written in the $ref — and the values are the Go packages their types are generated into.

A key cannot be a JSON pointer such as #/components/schemas. References within a single document always resolve to the package being generated, so there's nothing to map — if you want your models in a different Go package to your server, split them into their own spec file and map that file, as shown below.

For instance, let's say that we have a large API, which has a user-facing API and an admin API, both of which use a common set of API models.

In this case, we may have an Admin API that looks like:

# admin/api.yaml
openapi: "3.0.0"
info:
  version: 1.0.0
  title: Admin API
  description: The admin-only portion of the API, which has its own separate OpenAPI spec
tags:
  - name: admin
    description: Admin API endpoints
  - name: user
    description: API endpoint that pertains to user data
paths:
  /admin/user/{id}:
    get:
      tags:
        - admin
        - user
      summary: Get a user's details
      operationId: getUserById
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        200:
          description: Success
          content:
            application/json:
              schema:
                $ref: '../common/api.yaml#/components/schemas/User'

This references the common spec:

# common/api.yaml
components:
  schemas:
    User:
      type: object
      additionalProperties: false
      properties:
        name:
          type: string
      required:
        - name

So how do we get oapi-codegen to generate our code?

Using a single package with multiple OpenAPI specs

[!TIP] Since oapi-codegen v2.4.0, it is now possible to split large OpenAPI specifications into the same Go package, using the "self" mapping (denoted by a -) when using Import Mapping.

This is an improvement on the previous model, which would require splitting files across multiple packages.

[!NOTE] You still need to have multiple go generates, and any other configuration files.

To get oapi-codegen's single-package support working, we need multiple calls to oapi-codegen, one call per OpenAPI spec file:

$ go run github.com/ifc7/oapi-codegen/v2/cmd/oapi-codegen -config cfg-api.yaml ../admin/api.yaml
$ go run github.com/ifc7/oapi-codegen/v2/cmd/oapi-codegen -config cfg-user.yaml ../common/api.yaml

This therefore means that we need multiple configuration files, such as cfg-api.yaml:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
package: samepackage
output: server.gen.go
generate:
  models: true
  server: true
output-options:
  # to make sure that all types are generated
  skip-prune: true
import-mapping:
  user.yaml: "-"

And then our cfg-user.yaml:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
package: samepackage
output: user.gen.go
generate:
  models: true
output-options:
  # to make sure that all types are generated
  skip-prune: true

From here, oapi-codegen will generate multiple Go files, all within the same package, which can be used to break down your large OpenAPI specifications, and generate only the subsets of code needed for each part of the spec.

Check out the import-mapping/samepackage example for the full code.

Using multiple packages, with one OpenAPI spec per package

To get oapi-codegen's multi-package support working, we need to set up our directory structure:

├── admin
│   ├── cfg.yaml
│   └── generate.go
└── common
    ├── cfg.yaml
    └── generate.go

We could start with our configuration file for our admin API spec:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
# admin/cfg.yaml
package: admin
output: server.gen.go
generate:
  models: true
  server: true
output-options:
  # to make sure that all types are generated
  skip-prune: true
# NOTE that this won't work, as it's missing `import-mapping`

If we were to run oapi-codegen, this will fail with the following error

error generating code: error creating operation definitions: error generating response definitions: error generating request body definition: error turning reference (../common/api.yaml#/components/schemas/User) into a Go type: unrecognized external reference '../common/api.yaml'; please provide the known import for this reference using option --import-mapping

This is because oapi-codegen requires the import-mapping:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
package: admin
output: server.gen.go
generate:
  models: true
  server: true
output-options:
  # to make sure that all types are generated
  skip-prune: true
import-mapping:
  # for a given file/URL that is $ref'd, point `oapi-codegen` to the Go package that this spec is generated into, to perform Go package imports
  ../common/api.yaml: github.com/ifc7/oapi-codegen/v2/examples/import-mapping/common

This will then generate the following code:

package admin

import (
	// ...
	externalRef0 "github.com/ifc7/oapi-codegen/v2/examples/import-mapping/common"
)

// User defines model for User.
type User = externalRef0.User

If you don't want to do this, an alternate option is to use a single package, with multiple OpenAPI spec files for that given package or to bundle your multiple OpenAPI files into a single spec.

Check out the import-mapping/multiplepackages example for the full code.

Modifying the input OpenAPI Specification (with OpenAPI Overlay)

Prior to oapi-codegen v2.4.0, users wishing to override specific configuration, for instance taking advantage of extensions such as x-go-type would need to modify the OpenAPI specification they are using.

In a lot of cases, this OpenAPI specification would be produced by a different team to the consumers (or even a different company) and so asking them to make changes like this were unreasonable.

This would lead to the API consumers needing to vendor the specification from the producer (which is our recommendation anyway) and then make any number of local changes to the specification to make it generate code that looks reasonable.

However, in the case that a consumer would update their specification, they would likely end up with a number of merge conflicts.

Now, as of oapi-codegen v2.4.0, it is now possible to make changes to the input OpenAPI specification without needing to modify it directly.

This takes advantage of the OpenAPI Overlay specification, which is a stable specification.

[!CAUTION] Beware! Here (may) be dragons.

The Overlay specification requires the use of JSON Path, which some users may find difficult to write and/or maintain.

We still heavily recommend using Overlay functionality, but would like users to be aware of this.

There is a proposed modification to the specification which would relax the need for JSON Path as the targeting mechanism.

For instance, let's say that we have the following OpenAPI specification, which provides insight into an internal endpoint that we should not be generating any code for (denoted by x-internal):

openapi: "3.0.0"
info:
  version: 1.0.0
  title: "Example to indicate how to use the OpenAPI Overlay specification (https://github.com/OAI/Overlay-Specification)"
paths:
  /ping:
    get:
      responses:
        '200':
          description: pet response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Pong'
    delete:
      x-internal: true
      responses:
        '202':
          content: {}

If we were to run oapi-codegen with out-of-the-box functionality, this would then lead to the DELETE endpoint being generated, which we don't want.

Instead, we can define the following overlay.yaml:

overlay: 1.0.0
info:
  title: Overlay
  version: 0.0.0
actions:
- target: "$"
  description: Perform a structural overlay, which can be more readable, as it's clear what the shape of the document is
  update:
    info:
      x-overlay-applied: structured-overlay
    paths:
      /ping:
        get:
          responses:
            '200':
              description: Perform a ping request
- target: $.paths.*[?(@.x-internal)]
  description: Remove internal endpoints (noted by x-internal)
  remove: true
- target: $.paths.*.*[?(@.x-internal)]
  description: Remove internal endpoints (noted by x-internal)
  remove: true

And our configuration file for oapi-codegen:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
package: api
output: ping.gen.go
generate:
  models: true
  server: true
output-options:
  overlay:
    path: overlay.yaml

This then completely removes the DELETE endpoint before we even start to parse the specification in oapi-codegen, so it's as if your specification was provided without that endpoint.

Additionally, we can override other pieces of metadata, such as the description for operations.

Check out the overlay example for the full code, and some more complex examples.

Generating Nullable types

It's possible that you want to be able to determine whether a field isn't sent, is sent as null or has a value.

For instance, if you had the following OpenAPI property:

S:
  type: object
  properties:
    Field:
      type: string
      nullable: true
    required: []

The default behaviour in oapi-codegen is to generate:

type S struct {
	Field *string `json:"field"`
}

Note that there is no omitempty here: since the field is nullable, a nil pointer marshals as an explicit null, and omitempty would make that null impossible to produce.

However, you lose the ability to understand the three cases, as there's no way to distinguish two of the types from each other:

  • is this field not sent? (Can be checked with S.Field == nil)
  • is this field null? (Can be checked with S.Field == nil)
  • does this field have a value? (S.Field != nil && *S.Field == "123")

As of oapi-codegen v2.1.0 it is now possible to represent this with the nullable.Nullable type from our new library, oapi-codegen/nullable.

If you configure your generator's Output Options to opt-in to this behaviour, as so:

output-options:
  nullable-type: true

You will now receive the following output:

type S struct {
    // note that there's no pointer here, just `omitempty`
    Field nullable.Nullable[string] `json:"field,omitempty"`
}

OpenAPI extensions

As well as the core OpenAPI support, we also support the following OpenAPI extensions, as denoted by the OpenAPI Specification Extensions.

The following extensions are supported:

Extension Description Docs
x-go-type / x-go-type-import Override the generated type definition (and optionally, add an import from another package) (docs)
x-go-type-skip-optional-pointer Do not add a pointer type for optional fields in structs (docs)
x-go-name Override the generated name of a field or a type (docs)
x-go-type-name Override the generated name of a type (docs)
x-omitempty Force the presence of the JSON tag omitempty on a field (docs)
x-omitzero Force the presence of the JSON tag omitzero on a field (docs)
x-go-json-ignore When (un)marshaling JSON, ignore field(s) (docs)
x-oapi-codegen-extra-tags Generate arbitrary struct tags to fields (docs)
x-enum-varnames / x-enumNames Override generated variable names for enum constants (docs)
x-deprecated-reason Add a GoDoc deprecation warning to a type (docs)
x-order Explicitly order struct fields (docs)
x-oapi-codegen-only-honour-go-name Only honour the x-go-name when generating field names (docs)
x-oapi-codegen-enum-merge Keep all the values of an allOf's enums (docs)

Request/response validation middleware

The generated code that oapi-codegen produces has some validation for some incoming data, such as checking for required headers, and the generated server checks that a handler returns one of the operation's response types.

However, this leaves a lot of validation that needs to be done, which can be tedious to hand-write this logic, especially for large or complex OpenAPI specifications.

To simplify this, use nethttp-middleware, which validates requests against the spec and wraps any http.Handler.

[!NOTE] It is not currently possible to validate the HTTP response with a middleware.

Implementing security

If you're using a specification with Security Schemes and Security Requirements, you'll want to authenticate and authorize requests.

On the server

The generated server doesn't authenticate requests itself, but it tells you what each one needs: SecurityRequirements(ctx) returns the security requirements of the operation a request is for, with the spec's alternatives (OR), combined schemes (AND) and anonymous ({}) alternatives intact. A MiddlewareFunc, a ServerInterface method or the RequestErrorHandlerFunc can use them to authorize the request; see the server documentation.

Alternatively, the validation middleware validates each request against the spec's security requirements, and calls your AuthenticationFunc with the scheme name and required scopes.

To see how this can work, check out the authenticated API example.

On the client

With a generated client, you'll want to use the client's generated WithRequestEditorFn function to pass in a given request editor RequestEditorFn.

For instance:

import (
	"context"
	"fmt"
	"log"

	"github.com/ifc7/oapi-codegen/v2/pkg/securityprovider"
)

func main() {
	basicAuth, err := securityprovider.NewSecurityProviderBasicAuth("my_user", "my_pass")
	if err != nil {
		log.Fatal(err)
	}

	client, err := NewClient("https://....", WithRequestEditorFn(basicAuth.Intercept))
	if err != nil {
		log.Fatal(err)
	}

	resp, err := client.GetClient(context.TODO())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("resp.StatusCode: %v\n", resp.StatusCode)
}

Notice that we're using a pre-built provider from the pkg/securityprovider package, which has some inbuilt support for other types of authentication, too.

Custom code generation

It is possible to extend the inbuilt code generation from oapi-codegen using Go's text/templates.

You can specify, through your configuration file, the output-options.user-templates setting to override the inbuilt templates and use a user-defined template.

[!NOTE] Filenames given to the user-templates configuration must exactly match the filename that oapi-codegen is looking for

Local paths

Within your configuration file, you can specify relative or absolute paths to a file to reference for the template, such as:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
# ...
output-options:
  user-templates:
    client-with-responses.tmpl: ./custom-template.tmpl
    additional-properties.tmpl: /tmp/foo.bar
    typedef.tmpl: no-prefix.tmpl

[!WARNING] We do not interpolate ~ or $HOME (or other environment variables) in paths given

HTTPS paths

It is also possible to use HTTPS URLs.

[!WARNING] Although possible, this does lead to oapi-codegen executions not necessarily being reproducible. It's recommended to vendor (copy) the OpenAPI spec into your codebase and reference it locally

See this blog post for an example of how to use GitHub Actions to manage the updates of files across repos

See this blog post for an example of how to use Renovate to manage the updates of files across repos

This will be disabled by default (but possible to turn back on via configuration) in the future

To use it, you can use the following configuration:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
# ...
output-options:
  user-templates:
    # The following are referencing a version of the default client-with-responses.tmpl file, but loaded in through GitHub's raw.githubusercontent.com. The general form to use raw.githubusercontent.com is as follows https://raw.githubusercontent.com/<username>/<project>/<commitish>/path/to/template/template.tmpl

    # Alternatively using raw.githubusercontent.com with a hash
    client-with-responses.tmpl: https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/ad5eada4f3ccc28a88477cef62ea21c17fc8aa01/pkg/codegen/templates/client-with-responses.tmpl
    # Alternatively using raw.githubusercontent.com with a tag
    client-with-responses.tmpl: https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.1.0/pkg/codegen/templates/client-with-responses.tmpl
    # Alternatively using raw.githubusercontent.com with a branch
    client-with-responses.tmpl: https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/master/pkg/codegen/templates/client-with-responses.tmpl

[!WARNING] If using URLs that pull locations from a Git repo, such as raw.githubusercontent.com, it is strongly encouraged to use a tag or a raw commit hash instead of a branch like main. Tracking a branch can lead to unexpected API drift, and loss of the ability to reproduce a build.

Inline template

It's also possible to set the templates inline in the configuration file:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
# ...
output-options:
  user-templates:
    # NOTE the use of the `|` (pipe symbol) here to denote that this is a
    # multi-line statement that should preserve newlines. More reading:
    # https://stackoverflow.com/a/18708156/2257038 and
    # https://stackoverflow.com/a/15365296/2257038
    client-with-responses.tmpl: |
        // ClientWithResponses builds on ClientInterface to offer response payloads
        type ClientWithResponses struct {
            ClientInterface
        }
        ...
Using the Go package

codegen.Generate takes a *model.Document (pkg/model). Load one with the libopenapi engine and pass it in:

import (
    "github.com/ifc7/oapi-codegen/v2/pkg/codegen"
    "github.com/ifc7/oapi-codegen/v2/pkg/engine"
    "github.com/ifc7/oapi-codegen/v2/pkg/engine/libopenapi"
)

doc, err := libopenapi.Engine{}.Load(path, engine.LoadOptions{})
code, err := codegen.Generate(doc, cfg)

User templates receive that same model. Schema.OAPISchema, ParameterDefinition.Spec and OperationDefinition.Spec are model types.

Further use of the package as a library will be documented in the future.

Additional Properties (additionalProperties)

OpenAPI Schemas implicitly accept additionalProperties, meaning that any fields provided, but not explicitly defined via properties on the schema are accepted as input, and propagated. When unspecified, OpenAPI defines that the additionalProperties field is assumed to be true.

For simplicity, and to remove a fair bit of duplication and boilerplate, oapi-codegen decides to ignore the implicit additionalProperties: true, and instead requires you to specify the additionalProperties key to generate the boilerplate.

[!NOTE] In the future this will be possible to disable this functionality, and honour the implicit additionalProperties: true

Below you can see some examples of how additionalProperties affects the generated code.

Implicit additionalProperties: true / no additionalProperties set
components:
  schemas:
    Thing:
      type: object
      required:
        - id
      properties:
        id:
          type: integer
      # implicit additionalProperties: true

Will generate:

// Thing defines model for Thing.
type Thing struct {
	Id int `json:"id"`
}

// with no generated boilerplate nor the `AdditionalProperties` field
Explicit additionalProperties: true
components:
  schemas:
    Thing:
      type: object
      required:
        - id
      properties:
        id:
          type: integer
      # explicit true
      additionalProperties: true

Will generate:

// Thing defines model for Thing.
type Thing struct {
	Id                   int                    `json:"id"`
	AdditionalProperties map[string]interface{} `json:"-"`
}

// with generated boilerplate below
Boilerplate

// Getter for additional properties for Thing. Returns the specified
// element and whether it was found
func (a Thing) Get(fieldName string) (value interface{}, found bool) {
	if a.AdditionalProperties != nil {
		value, found = a.AdditionalProperties[fieldName]
	}
	return
}

// Setter for additional properties for Thing
func (a *Thing) Set(fieldName string, value interface{}) {
	if a.AdditionalProperties == nil {
		a.AdditionalProperties = make(map[string]interface{})
	}
	a.AdditionalProperties[fieldName] = value
}

// Override default JSON handling for Thing to handle AdditionalProperties
func (a *Thing) UnmarshalJSON(b []byte) error {
	object := make(map[string]json.RawMessage)
	err := json.Unmarshal(b, &object)
	if err != nil {
		return err
	}

	if raw, found := object["id"]; found {
		err = json.Unmarshal(raw, &a.Id)
		if err != nil {
			return fmt.Errorf("error reading 'id': %w", err)
		}
		delete(object, "id")
	}

	if len(object) != 0 {
		a.AdditionalProperties = make(map[string]interface{})
		for fieldName, fieldBuf := range object {
			var fieldVal interface{}
			err := json.Unmarshal(fieldBuf, &fieldVal)
			if err != nil {
				return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err)
			}
			a.AdditionalProperties[fieldName] = fieldVal
		}
	}
	return nil
}

// Override default JSON handling for Thing to handle AdditionalProperties
func (a Thing) MarshalJSON() ([]byte, error) {
	var err error
	object := make(map[string]json.RawMessage)

	object["id"], err = json.Marshal(a.Id)
	if err != nil {
		return nil, fmt.Errorf("error marshaling 'id': %w", err)
	}

	for fieldName, field := range a.AdditionalProperties {
		object[fieldName], err = json.Marshal(field)
		if err != nil {
			return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err)
		}
	}
	return json.Marshal(object)
}
additionalProperties as integers
components:
  schemas:
    Thing:
      type: object
      required:
        - id
      properties:
        id:
          type: integer
      # simple type
      additionalProperties:
        type: integer

Will generate:

// Thing defines model for Thing.
type Thing struct {
	Id                   int            `json:"id"`
	AdditionalProperties map[string]int `json:"-"`
}

// with generated boilerplate below
Boilerplate
// Getter for additional properties for Thing. Returns the specified
// element and whether it was found
func (a Thing) Get(fieldName string) (value int, found bool) {
	if a.AdditionalProperties != nil {
		value, found = a.AdditionalProperties[fieldName]
	}
	return
}

// Setter for additional properties for Thing
func (a *Thing) Set(fieldName string, value int) {
	if a.AdditionalProperties == nil {
		a.AdditionalProperties = make(map[string]int)
	}
	a.AdditionalProperties[fieldName] = value
}

// Override default JSON handling for Thing to handle AdditionalProperties
func (a *Thing) UnmarshalJSON(b []byte) error {
	object := make(map[string]json.RawMessage)
	err := json.Unmarshal(b, &object)
	if err != nil {
		return err
	}

	if raw, found := object["id"]; found {
		err = json.Unmarshal(raw, &a.Id)
		if err != nil {
			return fmt.Errorf("error reading 'id': %w", err)
		}
		delete(object, "id")
	}

	if len(object) != 0 {
		a.AdditionalProperties = make(map[string]int)
		for fieldName, fieldBuf := range object {
			var fieldVal int
			err := json.Unmarshal(fieldBuf, &fieldVal)
			if err != nil {
				return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err)
			}
			a.AdditionalProperties[fieldName] = fieldVal
		}
	}
	return nil
}

// Override default JSON handling for Thing to handle AdditionalProperties
func (a Thing) MarshalJSON() ([]byte, error) {
	var err error
	object := make(map[string]json.RawMessage)

	object["id"], err = json.Marshal(a.Id)
	if err != nil {
		return nil, fmt.Errorf("error marshaling 'id': %w", err)
	}

	for fieldName, field := range a.AdditionalProperties {
		object[fieldName], err = json.Marshal(field)
		if err != nil {
			return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err)
		}
	}
	return json.Marshal(object)
}
additionalProperties with an object
components:
  schemas:
    Thing:
      type: object
      required:
        - id
      properties:
        id:
          type: integer
      # object
      additionalProperties:
        type: object
        properties:
          foo:
            type: string

Will generate:

// Thing defines model for Thing.
type Thing struct {
	Id                   int `json:"id"`
	AdditionalProperties map[string]struct {
		Foo *string `json:"foo,omitempty"`
	} `json:"-"`
}

// with generated boilerplate below
Boilerplate
// Getter for additional properties for Thing. Returns the specified
// element and whether it was found
func (a Thing) Get(fieldName string) (value struct {
	Foo *string `json:"foo,omitempty"`
}, found bool) {
	if a.AdditionalProperties != nil {
		value, found = a.AdditionalProperties[fieldName]
	}
	return
}

// Setter for additional properties for Thing
func (a *Thing) Set(fieldName string, value struct {
	Foo *string `json:"foo,omitempty"`
}) {
	if a.AdditionalProperties == nil {
		a.AdditionalProperties = make(map[string]struct {
			Foo *string `json:"foo,omitempty"`
		})
	}
	a.AdditionalProperties[fieldName] = value
}

// Override default JSON handling for Thing to handle AdditionalProperties
func (a *Thing) UnmarshalJSON(b []byte) error {
	object := make(map[string]json.RawMessage)
	err := json.Unmarshal(b, &object)
	if err != nil {
		return err
	}

	if raw, found := object["id"]; found {
		err = json.Unmarshal(raw, &a.Id)
		if err != nil {
			return fmt.Errorf("error reading 'id': %w", err)
		}
		delete(object, "id")
	}

	if len(object) != 0 {
		a.AdditionalProperties = make(map[string]struct {
			Foo *string `json:"foo,omitempty"`
		})
		for fieldName, fieldBuf := range object {
			var fieldVal struct {
				Foo *string `json:"foo,omitempty"`
			}
			err := json.Unmarshal(fieldBuf, &fieldVal)
			if err != nil {
				return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err)
			}
			a.AdditionalProperties[fieldName] = fieldVal
		}
	}
	return nil
}

// Override default JSON handling for Thing to handle AdditionalProperties
func (a Thing) MarshalJSON() ([]byte, error) {
	var err error
	object := make(map[string]json.RawMessage)

	object["id"], err = json.Marshal(a.Id)
	if err != nil {
		return nil, fmt.Errorf("error marshaling 'id': %w", err)
	}

	for fieldName, field := range a.AdditionalProperties {
		object[fieldName], err = json.Marshal(field)
		if err != nil {
			return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err)
		}
	}
	return json.Marshal(object)
}

Globally skipping the "optional pointer"

One of the key things oapi-codegen does is to use an "optional pointer", following idiomatic Go practices, to indicate that a field/type is optional.

This can be tuned on a per-field basis, using the x-go-type-skip-optional-pointer extension, but it can be a bit repetitive, or can be more complex when using an OpenAPI Overlay.

As of oapi-codegen v2.5.0, this can be tuned in two specific ways, via the following output-options::

  • prefer-skip-optional-pointer: a global default that you do not want the "optional pointer" generated. Optional fields will not have an "optional pointer", and will have an omitempty JSON tag
  • prefer-skip-optional-pointer-with-omitzero: when used in conjunction with prefer-skip-optional-pointer, any optional fields are generated with an omitzero JSON tag. Requires Go 1.24+

In both cases, there is control on a per-field level to set x-go-type-skip-optional-pointer: false or x-omitzero: false to undo these to field(s).

For example, when combining both options:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
package: preferskipoptionalpointerwithomitzero
output: gen.go
generate:
  # ...
output-options:
  # ...
  prefer-skip-optional-pointer: true
  prefer-skip-optional-pointer-with-omitzero: true

When we have the following spec:

openapi: "3.0.0"
info:
  version: 1.0.0
  title: prefer-skip-optional-pointer-with-omitzero
components:
  schemas:
    ClientWithExtension:
      type: object
      required:
        - name
      properties:
        name:
          description: This field is required, so will never have an optional pointer, nor `omitzero`.
          type: string
        id:
          description: This field is optional, but the `prefer-skip-optional-pointer` Output Option ensures that this should not have an optional pointer. However, it will receive `omitzero`.
          type: number
        pointer_id:
          type: number
          description: This field should have an optional pointer, as the field-level definition of `x-go-type-skip-optional-pointer` overrides the `prefer-skip-optional-pointer` Output Option. This will also not receive an `omitzero`.
          # NOTE that this overrides the global preference
          x-go-type-skip-optional-pointer: false
        no_omit:
          type: number
          description: This field is optional, but the `prefer-skip-optional-pointer` Output Option ensures that this should not have an optional pointer. This will not receive `omitzero`, as the field-level definition of `x-omitzero` overrides the `prefer-skip-optional-pointer-with-omitzero` Output Option.
          # NOTE that this overrides the global preference
          x-omitzero: false

We then generate the following Go code:

// ...

// ClientWithExtension defines model for ClientWithExtension.
type ClientWithExtension struct {
	// Id This field is optional, but the `prefer-skip-optional-pointer` Output Option ensures that this should not have an optional pointer. However, it will receive `omitzero`.
	Id float32 `json:"id,omitempty,omitzero"`

	// Name This field is required, so will never have an optional pointer, nor `omitzero`.
	Name string `json:"name"`

	// NoOmit This field is optional, but the `prefer-skip-optional-pointer` Output Option ensures that this should not have an optional pointer. This will not receive `omitzero`, as the field-level definition of `x-omitzero` overrides the `prefer-skip-optional-pointer-with-omitzero` Output Option.
	NoOmit float32 `json:"no_omit,omitempty"`

	// PointerId This field should have an optional pointer, as the field-level definition of `x-go-type-skip-optional-pointer` overrides the `prefer-skip-optional-pointer` Output Option. This will also not receive an `omitzero`.
	PointerId *float32 `json:"pointer_id,omitempty"`
}

You can see this in more detail in the example code for prefer-skip-optional-pointer and example code for prefer-skip-optional-pointer-with-omitzero

Changing the names of generated types

As of oapi-codegen v2.2.0, it is now possible to use the output-options configuration's name-normalizer to define the logic for how to convert an OpenAPI name (i.e. an Operation ID or a Schema name) and construct a Go type name.

Example, using default configuration

By default, oapi-codegen will perform camel-case conversion, so for a spec such as:

openapi: "3.0.0"
info:
  version: 1.0.0
  title: Example code for the `name-normalizer` output option
paths:
  /api/pets/{petId}:
    get:
      summary: Get pet given identifier.
      operationId: getHttpPet
      parameters:
      - name: petId
        in: path
        required: true
        schema:
          type: string
      responses:
        '200':
          description: valid pet
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Pet'
components:
  schemas:
    Pet:
      type: object
      required:
        - uuid
        - name
      properties:
        uuid:
          type: string
          description: The pet uuid.
        name:
          type: string
          description: The name of the pet.
    Error:
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
          description: Error code
        message:
          type: string
          description: Error message
    OneOf2things:
      description: "Notice that the `things` is not capitalised"
      oneOf:
        - type: object
          required:
            - id
          properties:
            id:
              type: integer
        - type: object
          required:
            - id
          properties:
            id:
              type: string
              format: uuid

This will produce:

// OneOf2things Notice that the `things` is not capitalised
type OneOf2things struct {
	union json.RawMessage
}

// Pet defines model for Pet.
type Pet struct {
	// Name The name of the pet.
	Name string `json:"name"`

	// Uuid The pet uuid.
	Uuid string `json:"uuid"`
}

// The interface specification for the client above.
type ClientInterface interface {
	// GetHttpPet request
	GetHttpPet(ctx context.Context, petId string, reqEditors ...RequestEditorFn) (*http.Response, error)
}
Example, using ToCamelCaseWithInitialisms

By default, oapi-codegen will perform camel-case conversion, so for a spec such as:

openapi: "3.0.0"
info:
  version: 1.0.0
  title: Example code for the `name-normalizer` output option
paths:
  /api/pets/{petId}:
    get:
      summary: Get pet given identifier.
      operationId: getHttpPet
      parameters:
      - name: petId
        in: path
        required: true
        schema:
          type: string
      responses:
        '200':
          description: valid pet
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Pet'
components:
  schemas:
    Pet:
      type: object
      required:
        - uuid
        - name
      properties:
        uuid:
          type: string
          description: The pet uuid.
        name:
          type: string
          description: The name of the pet.
    Error:
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
          description: Error code
        message:
          type: string
          description: Error message
    OneOf2things:
      description: "Notice that the `things` is not capitalised"
      oneOf:
        - type: object
          required:
            - id
          properties:
            id:
              type: integer
        - type: object
          required:
            - id
          properties:
            id:
              type: string
              format: uuid

This will produce:

// OneOf2things Notice that the `things` is not capitalised
type OneOf2things struct {
	union json.RawMessage
}

// Pet defines model for Pet.
type Pet struct {
	// Name The name of the pet.
	Name string `json:"name"`

	// UUID The pet uuid.
	UUID string `json:"uuid"`
}

// The interface specification for the client above.
type ClientInterface interface {
	// GetHTTPPet request
	GetHTTPPet(ctx context.Context, petID string, reqEditors ...RequestEditorFn) (*http.Response, error)
}

For more details of what the resulting code looks like, check out the test cases.

Examples

The examples directory contains some additional cases which are useful examples for how to use oapi-codegen, including how you'd take the Petstore API and implement it with oapi-codegen.

You could also find some cases of how the project can be used by checking out our internal test cases which are real-world usages that make up our regression tests.

Blog posts

We love reading posts by the community about how to use the project.

Here are a few we've found around the Web:

Got one to add? Please raise a PR!

Frequently Asked Questions (FAQs)

Does oapi-codegen support OpenAPI 3.1?

Yes. Initial OpenAPI 3.1 support landed with #2336, including webhooks and version-aware handling of 3.1 idioms such as type: [T, "null"] nullability and enums declared via oneOf + const.

A 3.1 schema may also declare a multi-type union, such as type: [string, number, boolean]. Go has no type expressing that constraint, so these generate any.

If you're on an older release that predates this, you can use OpenAPI Overlay to "downgrade" an OpenAPI 3.1 spec to OpenAPI 3.0, following steps from this blog post.

How does oapi-codegen handle anyOf, allOf and oneOf?

oapi-codegen supports anyOf, allOf and oneOf for generated code.

An allOf's members are merged into one type by what allOf means, conflicting members are reported as errors, and anyOf and oneOf become union types. How allOf, anyOf and oneOf become Go types describes the rules in detail.

For instance, through the following OpenAPI spec:

openapi: "3.0.0"
info:
  version: 1.0.0
  title: Using complex schemas
  description: An example of `anyOf`, `allOf` and `oneOf`
components:
  schemas:
    # base types
    Client:
      type: object
      required:
        - name
      properties:
        name:
          type: string
    Identity:
      type: object
      required:
        - issuer
      properties:
        issuer:
          type: string

    # allOf merges the schemas it lists into one type
    ClientWithId:
      allOf:
        - $ref: '#/components/schemas/Client'
        - properties:
            id:
              type: integer
          required:
            - id

    # a property several schemas declare is merged: here, the second schema
    # adds a description and a length limit to Identity's `issuer`. Their
    # types have to agree; generation fails when they can't
    IdentityWithDuplicateField:
      allOf:
        - $ref: '#/components/schemas/Identity'
        - properties:
            issuer:
              type: string
              description: The URL of the issuer.
              maxLength: 255

    # anyOf results in a type that has an `AsClient`/`MergeClient`/`FromClient` and an `AsIdentity`/`MergeIdentity`/`FromIdentity` method so you can choose which of them you want to retrieve
    ClientAndMaybeIdentity:
      anyOf:
        - $ref: '#/components/schemas/Client'
        - $ref: '#/components/schemas/Identity'

    # oneOf results in a type that has an `AsClient`/`MergeClient`/`FromClient` and an `AsIdentity`/`MergeIdentity`/`FromIdentity` method so you can choose which of them you want to retrieve
    ClientOrIdentity:
      oneOf:
        - $ref: '#/components/schemas/Client'
        - $ref: '#/components/schemas/Identity'

This results in the following types:

Base types
// Client defines model for Client.
type Client struct {
	Name string `json:"name"`
}

// Identity defines model for Identity.
type Identity struct {
	Issuer string `json:"issuer"`
}
allOf
// ClientWithId defines model for ClientWithId.
type ClientWithId struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
}

// IdentityWithDuplicateField defines model for IdentityWithDuplicateField.
type IdentityWithDuplicateField struct {
	// Issuer The URL of the issuer.
	Issuer string `json:"issuer"`
}
anyOf
import (
	"encoding/json"
)

// ClientAndMaybeIdentity defines model for ClientAndMaybeIdentity.
type ClientAndMaybeIdentity struct {
	union json.RawMessage
}

// AsClient returns the union data inside the ClientAndMaybeIdentity as a Client
func (t ClientAndMaybeIdentity) AsClient() (Client, error) {
	var body Client
	err := json.Unmarshal(t.union, &body)
	return body, err
}

// FromClient overwrites any union data inside the ClientAndMaybeIdentity as the provided Client
func (t *ClientAndMaybeIdentity) FromClient(v Client) error {
	b, err := json.Marshal(v)
	t.union = b
	return err
}

// MergeClient performs a merge with any union data inside the ClientAndMaybeIdentity, using the provided Client
func (t *ClientAndMaybeIdentity) MergeClient(v Client) error {
	b, err := json.Marshal(v)
	if err != nil {
		return err
	}

	merged, err := oapiJSONMergeForClientAndMaybeIdentity(t.union, b)
	t.union = merged
	return err
}

// AsIdentity returns the union data inside the ClientAndMaybeIdentity as a Identity
func (t ClientAndMaybeIdentity) AsIdentity() (Identity, error) {
	var body Identity
	err := json.Unmarshal(t.union, &body)
	return body, err
}

// FromIdentity overwrites any union data inside the ClientAndMaybeIdentity as the provided Identity
func (t *ClientAndMaybeIdentity) FromIdentity(v Identity) error {
	b, err := json.Marshal(v)
	t.union = b
	return err
}

// MergeIdentity performs a merge with any union data inside the ClientAndMaybeIdentity, using the provided Identity
func (t *ClientAndMaybeIdentity) MergeIdentity(v Identity) error {
	b, err := json.Marshal(v)
	if err != nil {
		return err
	}

	merged, err := oapiJSONMergeForClientAndMaybeIdentity(t.union, b)
	t.union = merged
	return err
}

func (t ClientAndMaybeIdentity) MarshalJSON() ([]byte, error) {
	b, err := t.union.MarshalJSON()
	return b, err
}

func (t *ClientAndMaybeIdentity) UnmarshalJSON(b []byte) error {
	err := t.union.UnmarshalJSON(b)
	return err
}


oneOf
// AsClient returns the union data inside the ClientOrIdentity as a Client
func (t ClientOrIdentity) AsClient() (Client, error) {
	var body Client
	err := json.Unmarshal(t.union, &body)
	return body, err
}

// FromClient overwrites any union data inside the ClientOrIdentity as the provided Client
func (t *ClientOrIdentity) FromClient(v Client) error {
	b, err := json.Marshal(v)
	t.union = b
	return err
}

// MergeClient performs a merge with any union data inside the ClientOrIdentity, using the provided Client
func (t *ClientOrIdentity) MergeClient(v Client) error {
	b, err := json.Marshal(v)
	if err != nil {
		return err
	}

	merged, err := oapiJSONMergeForClientAndMaybeIdentity(t.union, b)
	t.union = merged
	return err
}

// AsIdentity returns the union data inside the ClientOrIdentity as a Identity
func (t ClientOrIdentity) AsIdentity() (Identity, error) {
	var body Identity
	err := json.Unmarshal(t.union, &body)
	return body, err
}

// FromIdentity overwrites any union data inside the ClientOrIdentity as the provided Identity
func (t *ClientOrIdentity) FromIdentity(v Identity) error {
	b, err := json.Marshal(v)
	t.union = b
	return err
}

// MergeIdentity performs a merge with any union data inside the ClientOrIdentity, using the provided Identity
func (t *ClientOrIdentity) MergeIdentity(v Identity) error {
	b, err := json.Marshal(v)
	if err != nil {
		return err
	}

	merged, err := oapiJSONMergeForClientAndMaybeIdentity(t.union, b)
	t.union = merged
	return err
}

func (t ClientOrIdentity) MarshalJSON() ([]byte, error) {
	b, err := t.union.MarshalJSON()
	return b, err
}

func (t *ClientOrIdentity) UnmarshalJSON(b []byte) error {
	err := t.union.UnmarshalJSON(b)
	return err
}

For more info, check out the example code.

How can I ignore parts of the spec I don't care about?

By default, oapi-codegen will generate everything from the specification.

If you'd like to reduce what's generated, you can use one of a few options in the configuration file to tune the generation of the resulting output:

# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
output-options:
  include-tags: []
  exclude-tags: []
  include-operation-ids: []
  exclude-operation-ids: []
  exclude-schemas: []

Check the docs for more details of usage.

Should I commit the generated code?

We recommend doing so, yes, for the following reasons:

  • It means it's easier to view the impact of a change - be it due to an upgrade of oapi-codegen, or a change to your spec
  • It then allows your codebase to be consumed as a library, as all the files are committed

This means you'll need to have your CI/CD pipeline validate that generated files are all up-to-date, but that's a fairly straightforward piece of work.

Should I lint the generated code?

We really ask that you don't. Although it intends to be idiomatic Go code, it's not expected to pass all the various linting rules that your project may apply.

[!NOTE] We will, on occasion, improve the generated code to fix some linting warnings, such as those from go vet, but this should not be an expected change.

Contributors

We're very appreciative of the many contributors over the years and the ongoing use of the project 💜

Sponsors

For the most part, oapi-codegen is maintained in two busy peoples' free time. As noted in Creating a more sustainable model for oapi-codegen in the future, we're looking to make this a more sustainable project in the future.

Please consider sponsoring us through GitHub Sponsors either on the organisation or directly for Jamie, which helps work towards us being able to maintain the project long term.

See this blog post from Tidelift for more details on how to talk to your company about sponsoring maintainers of (Open Source) projects you depend on.

We are also generously sponsored by the following folks, each of whom provide sponsorship for 1 hour of work a month:

DevZero logo

Cybozu logo

Elastic logo

(Note that the order of appearance the order in which sponsorship was received)

Directories

Path Synopsis
cmd
genbench command
Command genbench times code generation on one OpenAPI document: loading it with libopenapi, then generating server, client and models from it.
Command genbench times code generation on one OpenAPI document: loading it with libopenapi, then generating server, client and models from it.
oapi-codegen command
pkg
engine
Package engine defines how an OpenAPI library loads a document into the generator's model.
Package engine defines how an OpenAPI library loads a document into the generator's model.
engine/enginetest
Package enginetest finds the documents the repository generates from, so every engine can be checked against the same set.
Package enginetest finds the documents the repository generates from, so every engine can be checked against the same set.
engine/libopenapi
Package libopenapi loads OpenAPI documents with pb33f/libopenapi and converts them into the generator's model.
Package libopenapi loads OpenAPI documents with pb33f/libopenapi and converts them into the generator's model.
securityprovider
Package securityprovider contains some default securityprovider implementations, which can be used as a RequestEditorFn of a client.
Package securityprovider contains some default securityprovider implementations, which can be used as a RequestEditorFn of a client.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL