Generate Go client and server boilerplate from OpenAPI 3 specifications
Repo oapi-codegen/oapi-codegen, read from GitHub 2 d ago. oapi-codegen has not joined Take My Repo.
oapi-codegen/oapi-codegen is a public repo on GitHub by oapi-codegen. Generate Go client and server boilerplate from OpenAPI 3 specifications. It declares the Apache-2.0 license on GitHub. It is written mainly in Go, has 8,669 stars and last changed on 2026-11-19. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-21.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
oapi-codegenoapi-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:
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.
additionalProperties)
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/oapi-codegen/oapi-codegen/v2.
[!IMPORTANT]
oapi-codegenmoved to its new home with the version tagv2.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/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@latest
oapi-codegen requires Go 1.26+ to build and install. The generated code requires Go 1.26+ as well — see Supported Servers.
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/oapi-codegen/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/oapi-codegen/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
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/oapi-codegen/oapi-codegen/v2@main
# alternatively, to a commit hash i.e. https://github.com/oapi-codegen/oapi-codegen/commit/71e916c59688a6379b5774dfe5904ec222b9a537
$ go get github.com/oapi-codegen/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/oapi-codegen/oapi-codegen/v2 v2.1.0
+require github.com/oapi-codegen/oapi-codegen/v2 v2.1.1-0.20240331212514-80f0b978ef16
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.
While some command line options are supported, they should be considered deprecated,
we just maintain them for backward compatibility, but we're not extending
them.
For full details of what is supported, check out the oapi-codegen configuration documentation.
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.9.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.
Although we strive to retain backwards compatibility - as a project that's using a stable API per SemVer - there are sometimes opportunities we must take to fix a bug that could cause a breaking change for people relying upon the behaviour.
In this case, we will expose a compatibility option to restore old behaviour.
That all being said, we operate in a little bit of a grey area, since we are a code generator, we support template overrides, and our code can be imported. So this is how we will try to maintain compatibility:
pkg/ directory is importable. In retrospect, this was a mistake in our original design. Importing anything other than the Generate function and its related Configuration is considered unstable (and at this point, hasn't (yet) been documented). In the future, we will clean up our import surface.Also note that - if a security vulnerability is found - we will opt for breaking all users if need be, if it is the most secure response.
Unless explicitly called out above, your usage of oapi-codegen may be using unstable features, which may make it harder to upgrade over time.
At a high level, oapi-codegen supports:
Below we can see a trimmed down example taken from the OpenAPI Petstore example:
// generated code
type ServerInterface interface {
// ...
// Returns all pets
// (GET /pets)
FindPets(w http.ResponseWriter, r *http.Request, params FindPetsParams)
// ...
}
// FindPets operation middleware
func (siw *ServerInterfaceWrapper) FindPets(w http.ResponseWriter, r *http.Request) {
var err error
// Parameter object where we will unmarshal all parameters from the context
var params FindPetsParams
// ------------- Optional query parameter "tags" -------------
err = runtime.BindQueryParameter("form", true, false, "tags", r.URL.Query(), ¶ms.Tags)
if err != nil {
siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "tags", Err: err})
return
}
// ------------- Optional query parameter "limit" -------------
err = runtime.BindQueryParameter("form", true, false, "limit", r.URL.Query(), ¶ms.Limit)
if err != nil {
siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err})
return
}
handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
siw.Handler.FindPets(w, r, params)
}))
for _, middleware := range siw.HandlerMiddlewares {
handler = middleware(handler)
}
handler.ServeHTTP(w, r)
}
// HandlerWithOptions creates http.Handler with additional options
func HandlerWithOptions(si ServerInterface, options StdHTTPServerOptions) http.Handler {
m := options.BaseRouter
if m == nil {
m = http.NewServeMux()
}
if options.ErrorHandlerFunc == nil {
options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, err.Error(), http.StatusBadRequest)
}
}
wrapper := ServerInterfaceWrapper{
Handler: si,
HandlerMiddlewares: options.Middlewares,
ErrorHandlerFunc: options.ErrorHandlerFunc,
}
m.HandleFunc("GET "+options.BaseURL+"/pets", wrapper.FindPets)
return m
}
Then, in your own code, you implement the underlying logic for the FindPets implementation:
type PetStore struct {
Pets map[int64]Pet
NextId int64
Lock sync.Mutex
}
// Make sure we conform to ServerInterface
var _ ServerInterface = (*PetStore)(nil)
func NewPetStore() *PetStore {
return &PetStore{
Pets: make(map[int64]Pet),
NextId: 1000,
}
}
// FindPets implements all the handlers in the ServerInterface
func (p *PetStore) FindPets(w http.ResponseWriter, r *http.Request, params FindPetsParams) {
p.Lock.Lock()
defer p.Lock.Unlock()
var result []Pet
for _, pet := range p.Pets {
if params.Tags != nil {
// If we have tags, filter pets by tag
for _, t := range *params.Tags {
if pet.Tag != nil && (*pet.Tag == t) {
result = append(result, pet)
}
}
} else {
// Add all pets if we're not filtering
result = append(result, pet)
}
if params.Limit != nil {
l := int(*params.Limit)
if len(result) >= l {
// We're at the limit
break
}
}
}
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(result)
}
As we can see, oapi-codegen simplifies some of the boilerplate by taking parameters out of the request and instead allows us to focus on the implementation.
You'll note that there's still a bit more marshaling of request/response data, which is further reduced by using the Strict server functionality.
When using the strict server, you'll have the following generated code:
// StrictServerInterface represents all server handlers.
type StrictServerInterface interface {
// ...
// Returns all pets
// (GET /pets)
FindPets(ctx context.Context, request FindPetsRequestObject) (FindPetsResponseObject, error)
// ...
}
func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface {
return &strictHandler{ssi: ssi, middlewares: middlewares, options: options}
}
// FindPets operation middleware
func (sh *strictHandler) FindPets(w http.ResponseWriter, r *http.Request, params FindPetsParams) {
var request FindPetsRequestObject
request.Params = params
handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) {
return sh.ssi.FindPets(ctx, request.(FindPetsRequestObject))
}
for _, middleware := range sh.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))
}
}
Then, in your own code, you implement the underlying logic for the FindPets implementation:
// Make sure we conform to StrictServerInterface
var _ StrictServerInterface = (*PetStore)(nil)
func NewPetStore() *PetStore {
return &PetStore{
Pets: make(map[int64]Pet),
NextId: 1000,
}
}
// FindPets implements all the handlers in the ServerInterface
func (p *PetStore) FindPets(ctx context.Context, request FindPetsRequestObject) (FindPetsResponseObject, error) {
p.Lock.Lock()
defer p.Lock.Unlock()
var result []Pet
for _, pet := range p.Pets {
if request.Params.Tags != nil {
// If we have tags, filter pets by tag
for _, t := range *request.Params.Tags {
if pet.Tag != nil && (*pet.Tag == t) {
result = append(result, pet)
}
}
} else {
// Add all pets if we're not filtering
result = append(result, pet)
}
if request.Params.Limit != nil {
l := int(*request.Params.Limit)
if len(result) >= l {
// We're at the limit
break
}
}
}
return FindPets200JSONResponse(result), nil
}
We can see that this provides the best means to focus on the implementation of the business logic within the endpoint, rather than (un)marshalling types to and from JSON, or wrangling cookies or headers. In order to actually use your strict server implementation use NewStrictHandler or NewStrictHandlerWithOptions to generate a (non-strict) server interface to use with the examples below.
text/templates, which are user-overridabletype: [T, "null"] nullability and enums declared via oneOf + constquery operation (HTTP QUERY) and additionalOperations (arbitrary HTTP methods) are generated for clients and every server framework; see OpenAPI 3.2 HTTP methodsadditionalProperties are ignored by default (more details)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.
You can find the supported HTTP server backends below, and more information about how to implement a server on top of each router.
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.
Right now, we support the following servers, and are supportive of adding new servers, too! Each
server lists the minimum Go version required to compile the generated code. That is
currently Go 1.26 for all of them, because the generated code imports
github.com/oapi-codegen/runtime, which requires Go 1.26.
| Server | generate flag |
Go Version | Documentation |
|---|---|---|---|
| Chi | chi-server |
1.26+ | Chi documentation |
| Echo | echo-server |
1.26+ | Echo documentation |
| Echo v5 | echo5-server |
1.26+ | Echo v5 documentation |
| Fiber | fiber-server |
1.26+ | Fiber documentation |
| Fiber v3 | fiber-v3-server |
1.26+ | Fiber v3 documentation |
| Gin | gin-server |
1.26+ | Gin documentation |
| gorilla/mux | gorilla-server |
1.26+ | gorilla/mux documentation |
| Iris | iris-server |
1.26+ | Iris documentation |
net/http |
std-http-server |
1.26+ | net/http documentation |
query and additionalOperations)OpenAPI 3.2 adds the query operation (the HTTP QUERY method) to the Path Item, and an additionalOperations map for any other HTTP method:
paths:
/items:
query:
operationId: queryItems
# ...
additionalOperations:
PURGE:
operationId: purgeItem
# ...
These are generated like any other operation, for clients, servers and strict servers. Route registration uses each router's string-method API. Some routers only accept methods they have been told about, and because that is application-wide state (one process often hosts several generated packages), the generated code never registers methods itself. Your application does it once, at startup, before any routes are registered:
Chi: call chi.RegisterMethod for each custom method before Handler/HandlerFromMux, otherwise route registration panics with chi: 'QUERY' http method is not supported:
chi.RegisterMethod("QUERY")
chi.RegisterMethod("PURGE")
r := chi.NewRouter()
api.HandlerFromMux(server, r)
Fiber (v2 and v3): list the custom methods in the application config (keep the defaults, the list replaces them), otherwise RegisterHandlers panics with add: invalid http method:
app := fiber.New(fiber.Config{
RequestMethods: append(slices.Clone(fiber.DefaultMethods), "QUERY", "PURGE"),
})
api.RegisterHandlers(app, server)
Iris: routes for custom methods work as-is. iris.RegisterMethods("QUERY") is only needed if you also want iris's Any() helpers and route debug listing to include them.
Echo (v4 and v5): nothing to register. The generated EchoRouter interface gains an Add method, which *echo.Echo and *echo.Group both satisfy; a custom EchoRouter implementation needs Add too.
Gin, gorilla/mux, net/http: nothing to do.
oapi-codegen also supports generating a server that is much more strict with the contract that the implementer requires, and takes inspiration from server-side code generation for RPC servers.
This takes the boilerplate reduction from the non-strict servers and adds additional boilerplate reduction, allowing you to make the following changes to your function signatures:
-FindPets(w http.ResponseWriter, r *http.Request, params FindPetsParams)
+FindPets(ctx context.Context, request FindPetsRequestObject) (FindPetsResponseObject, error)
This is the highest level of strictness that oapi-codegen supports right now, and it's a good idea to start with this if you want the most guardrails to simplify developing your APIs.
The strict server has support for:
multipart/form-data and application/x-www-form-urlencoded requestserror is returned from a functioncontent-type and HTTP status codes on responsesmultipart.Reader or providing a io.ReaderYou can see a little more detail of the generated code in the "What does it look like" section.
[!NOTE] To configure the strict server generation, you must specify another server to be generated. For instance:
# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.9.0/configuration-schema.json
package: api
generate:
# NOTE another server must be added!
chi-server: true
strict-server: true
output: server.gen.go
[!NOTE] This doesn't include validation of incoming requests.
[!IMPORTANT] When a strict-server spec uses
$refto point at acomponents/responses/...(orcomponents/requestBodies/...) defined in another spec viaimport-mapping, the destination spec must also be generated withstrict-server: true. The strict envelope embeds the<Name>JSONResponsetype from the destination package; that type only exists when the destination generates a strict server. Without it the generated code will fail to compile with an "undefined" error. See issue #2010.
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.9.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/oapi-codegen/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/oapi-codegen/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)
}
}
An OpenAPI specification makes it possible to denote Servers that a client can interact with, such as:
servers:
- url: https://development.gigantic-server.com/v1
description: Development server
- url: https://{username}.gigantic-server.com:{port}/{basePath}
description: The production API server
variables:
username:
# note! no enum here means it is an open value
default: demo
description: this value is assigned by the service provider, in this example `gigantic-server.com`
port:
enum:
- '8443'
- '443'
default: '8443'
basePath:
# open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2`
default: v2
It is possible to opt-in to the generation of these Server URLs with the following configuration:
# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.9.0/configuration-schema.json
package: serverurls
output: gen.go
generate:
# NOTE that this uses default settings - if you want to use initialisms to generate i.e. `ServerURLDevelopmentServer`, you should look up the `output-options.name-normalizer` configuration
server-urls: true
This will then generate the following boilerplate:
// (the below does not include comments that are generated)
const ServerUrlDevelopmentServer = "https://development.gigantic-server.com/v1"
type ServerUrlTheProductionAPIServerBasePathVariable string
const ServerUrlTheProductionAPIServerBasePathVariableDefault = "v2"
type ServerUrlTheProductionAPIServerPortVariable string
const ServerUrlTheProductionAPIServerPortVariable8443 ServerUrlTheProductionAPIServerPortVariable = "8443"
const ServerUrlTheProductionAPIServerPortVariable443 ServerUrlTheProductionAPIServerPortVariable = "443"
const ServerUrlTheProductionAPIServerPortVariableDefault ServerUrlTheProductionAPIServerPortVariable = ServerUrlTheProductionAPIServerPortVariable8443
type ServerUrlTheProductionAPIServerUsernameVariable string
const ServerUrlTheProductionAPIServerUsernameVariableDefault = "demo"
func ServerUrlTheProductionAPIServer(basePath ServerUrlTheProductionAPIServerBasePathVariable, port ServerUrlTheProductionAPIServerPortVariable, username ServerUrlTheProductionAPIServerUsernameVariable) (string, error) {
// ...
}
Notice that for URLs that are not templated, a simple const definition is created.
However, for more complex URLs that defined variables in them, we generate the types (and any enum values or default values), and instead use a function to create the URL.
For a complete example see examples/generate/serverurls.
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.9.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/oapi-codegen/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.9.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.
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.
[!TIP] Try to define as much as possible within the
#/components/schemasobject, asoapi-codegenwill 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.9.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/oapi-codegen/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.9.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.
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-mappingare 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.
[!IMPORTANT] External references to local files are always followed. External references to URLs are not followed unless the URL is listed in
allow-remote-refs-from, because an untrusted spec could otherwise makeoapi-codegenissue requests to any host reachable from the machine running it. List each referenced document's URL exactly as it appears in the$ref, without the#...fragment, or"*"to allow any URL:allow-remote-refs-from: - https://raw.githubusercontent.com/example/specs/main/common.yamlThere is no host or prefix matching: a reference to a different path, port or scheme on the same host is refused until it is listed too. A relative
$refinside a remote document resolves to an absolute URL, and that absolute URL is what has to be listed. A spec passed tooapi-codegenas a URL is fetched without listing it, but the documents it references still have to be.
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?
[!TIP] Since
oapi-codegenv2.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/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen -config cfg-api.yaml ../admin/api.yaml
$ go run github.com/oapi-codegen/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.9.0/configuration-schema.json
package: samepackage
output: server.gen.go
generate:
models: true
chi-server: true
strict-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.9.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.
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.9.0/configuration-schema.json
# admin/cfg.yaml
package: admin
output: server.gen.go
generate:
models: true
chi-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.9.0/configuration-schema.json
package: admin
output: server.gen.go
generate:
models: true
chi-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/oapi-codegen/oapi-codegen/v2/examples/import-mapping/common
This will then generate the following code:
package admin
import (
// ...
externalRef0 "github.com/oapi-codegen/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.
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.
[!NOTE] The Overlay implementation changed in v2.9.0: action targets are now RFC 9535 JSONPath, where earlier versions read them in a different dialect. The main differences are:
- a filter selects the children of the node it follows that match it, so drop one
.*before it:$.paths.*.*[?(@.x-internal)]becomes$.paths.*[?@['x-internal']]- names that contain
-or/, or start with a digit, must be bracketed:.x-internalbecomes['x-internal']X =~ /re/becomessearch(X, 're')X[*] == vbecomesX[?@ == v]The setting is all-or-nothing: by default every target in the overlay is read as RFC 9535, including targets that are valid in both dialects but mean something different in each. For instance
$.paths.*.*[?(!@.servers)]used to select operations withoutservers, and now selects the children of operations withoutservers; oapi-codegen does not try to detect which dialect a target was written in. Check your targets, or keep the previous behaviour for the whole overlay by settingcompatibility.overlays-use-yaml-jsonpath: true.
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.9.0/configuration-schema.json
package: api
output: ping.gen.go
generate:
models: true
gorilla-server: true
embedded-spec: 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.
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:
S.Field == nil)null? (Can be checked with S.Field == nil)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"`
}
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, with schema-merging-behavior: v3 |
(docs) |
The generated code that oapi-codegen produces has some validation for some incoming data, such as checking for required headers, and when using the strict server you get some more validation around the correct usage of the 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, we use a middleware, which provides the request validation. The middleware you want to use depends on the server you're using:
| Server | Middleware library |
|---|---|
|
Any other server (which conforms to |
[!NOTE] It is not currently possible to validate the HTTP response with a middleware.
[!TIP] A validation middleware decodes the JSON request body to validate it, and the generated handler then decodes it again. Because
encoding/jsonmatches member names case-insensitively, a body such as{"role":"user","ROLE":"admin"}validates asrole: userbut is bound asRole: "admin", bypassing the schema's constraints.Strict net/http, Chi, gorilla/mux, Echo, Gin, Iris and Fiber servers avoid the second decode when the middleware keeps the value it validated.
nethttp-middlewarev1.3.1,echo-middlewarev1.2.1,echo-v5-middlewarev0.2.1,gin-middlewarev1.2.1,iris-middlewarev1.2.1,fiber-middlewarev1.3.0 andfiber-v3-middlewarev0.3.0 and later do this by default (opt out withOptions.DiscardValidatedValue). With an older version, or with your ownopenapi3filtersetup, set kin-openapi'sKeepValidatedValueoption, shown here fornethttp-middleware:r.Use(middleware.OapiRequestValidatorWithOptions(spec, &middleware.Options{ Options: openapi3filter.Options{KeepValidatedValue: true}, }))The generated handler then binds the validated value (via
runtime.BindJSONBodyorruntime.BindJSONValue, runtime v1.8.0 or later) with exact member-name matching, and only falls back to the framework's decoder when no validated value is present. This requires kin-openapi v0.151.0 or later. Fiber does not run onnet/http, so the validated value cannot travel on the request body;fiber-middlewareandfiber-v3-middlewarestore it in the Fiber context underValidatedBodyLocalsKey(x-oapi-codegen-validated-body) and the generated strict Fiber handler reads it from there, which means the Fiber middleware versions above are required rather than theKeepValidatedValueoption alone. See #2605.
If you're using a specification with Security Schemes and Security Requirements, you'll want to authenticate and authorize requests.
[!NOTE] Out-of-the-box, the server-side code generated by
oapi-codegendoes not provide security validation.To perform authentication, you will need to use the validation middleware, which validates each request against the spec's security requirements and calls your
AuthenticationFuncwith the scheme name and required scopes.
To see how this can work, check out the authenticated API example.
Historically, generated server code embedded each operation's security scopes into the request context:
a context key type per security scheme (e.g. bearerAuthContextKey), a scope constant (e.g. BearerAuthScopes),
and a per-operation call storing the operation's scopes into the request context.
This mechanism is deprecated and no longer generated by default. It flattens the
spec's security requirements into a per-scheme list of scopes, and cannot represent
alternative schemes (OR), combined schemes (AND), or anonymous ({}) alternatives, so middleware built on it can't correctly enforce the spec. Use the validation middleware instead. Please see #1524 for more background.
If you have existing middleware that relies on these constants, you can re-enable them with:
compatibility:
enable-auth-scopes-on-context: true
Note that even when re-enabled, an operation that includes an empty {} security alternative allows anonymous requests, and no scopes are embedded into the request context for that operation.
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/oapi-codegen/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.
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-templatesconfiguration must exactly match the filename thatoapi-codegenis looking for
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.9.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
It is also possible to use HTTPS URLs.
[!WARNING] Although possible, this does lead to
oapi-codegenexecutions not necessarily being reproducible. It's recommended to vendor (copy) the OpenAPI spec into your codebase and reference it locallySee 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.9.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 likemain. Tracking a branch can lead to unexpected API drift, and loss of the ability to reproduce a build.
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.9.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
}
...
Alternatively, you are able to use the underlying code generation as a package, which will be documented in the future.
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.
additionalProperties: true / no additionalProperties setcomponents:
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
additionalProperties: truecomponents:
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
// 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 := runtime.JSONUnmarshal(b, &object)
if err != nil {
return err
}
if raw, found := object["id"]; found {
err = runtime.JSONUnmarshal(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 := runtime.JSONUnmarshal(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 = runtime.JSONMarshal(a.Id)
if err != nil {
return nil, fmt.Errorf("error marshaling 'id': %w", err)
}
for fieldName, field := range a.AdditionalProperties {
object[fieldName], err = runtime.JSONMarshal(field)
if err != nil {
return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err)
}
}
return runtime.JSONMarshal(object)
}
additionalProperties as integerscomponents:
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
// 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 := runtime.JSONUnmarshal(b, &object)
if err != nil {
return err
}
if raw, found := object["id"]; found {
err = runtime.JSONUnmarshal(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 := runtime.JSONUnmarshal(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 = runtime.JSONMarshal(a.Id)
if err != nil {
return nil, fmt.Errorf("error marshaling 'id': %w", err)
}
for fieldName, field := range a.AdditionalProperties {
object[fieldName], err = runtime.JSONMarshal(field)
if err != nil {
return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err)
}
}
return runtime.JSONMarshal(object)
}
additionalProperties with an objectcomponents:
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
// 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 := runtime.JSONUnmarshal(b, &object)
if err != nil {
return err
}
if raw, found := object["id"]; found {
err = runtime.JSONUnmarshal(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 := runtime.JSONUnmarshal(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 = runtime.JSONMarshal(a.Id)
if err != nil {
return nil, fmt.Errorf("error marshaling 'id': %w", err)
}
for fieldName, field := range a.AdditionalProperties {
object[fieldName], err = runtime.JSONMarshal(field)
if err != nil {
return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err)
}
}
return runtime.JSONMarshal(object)
}
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 tagprefer-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.9.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` o
oapi-codegen/oapi-codegen is a public repo on GitHub by oapi-codegen. Generate Go client and server boilerplate from OpenAPI 3 specifications.
It declares the Apache-2.0 license on GitHub.
Its maker has not tagged a system, so it is unknown here. Its README says what it needs.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-11-19. GitHub counts 288 open issues and pull requests. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
User-friendly AI Interface (Supports Ollama, OpenAI API, ...)

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)

Opensource IDE For Exploring and Testing API's (lightweight alternative to Postman/Insomnia)
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Generate Pydantic v2 models, dataclasses, TypedDict, and msgspec.Struct from OpenAPI, JSON Schema, GraphQL, Avro, Protobuf, and raw JSON/YAML/CSV, plus FastAPI servers and Python clients from OpenAPI.

Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.
This page is also available as structured data, with the same sources and dates.
Take My Repo has not tested this on your machine. Requirements come from the project's own documentation.