Repository navigation
Releases
v2.9.0: OpenAPI 3.2 methods, smarter schema merging, more naming control
This is another large release. Most of the work went into three areas: a rewrite of how allOf, anyOf and oneOf become Go types (available as an option for now), more configuration for things we used to hard-code (names, struct tags, content types, JSON encoding), and a long list of bug fixes, many of them from first-time contributors. Thank you all.
The security fixes from v2.8.1 and v2.8.2 are included here as well. Those two releases were made from a separate branch, so if you're coming from v2.8.0, you get them now.
As always, the full automatically-generated changelog is at the bottom. The sections below cover what you should read before upgrading.
Before you upgrade
- Go 1.26 is now required, both to build
oapi-codegenand to build the code it generates. Go 1.27 is out, so 1.26 is the oldest supported Go release. - Use generated code with
runtimev1.9.1 or newer. Generated code now calls JSON functions that were added ingithub.com/oapi-codegen/runtimev1.9.0, so it won't compile against an older runtime. v1.9.1 is needed for the form body fix described below. - Regenerate before you upgrade the runtime, not after. Runtime v1.9.0 removed the
strictmiddlewarepackages. Code generated byoapi-codegenv2.6.0 or earlier still imports them, so regenerate with this release first, then update the runtime. - Read the breaking changes section. A few defaults changed on purpose, and the runtime changes how it encodes spaces in query parameters.
🎉 Major features
A new way of merging allOf, anyOf and oneOf, as an option (#2563, #2581, and many in between)
Turning schema composition into Go types has been our largest source of bugs for years. Fixing those bugs properly often changes the generated code, which we can't do to people whose specs already work. So we now have versions of the merging behavior, and you choose one:
compatibility:
schema-merging-behavior: v3v1is the original behavior, which embeds the types ofallOfmembers in a struct. It's whatold-merge-schemas: truedid; that option still works, and prints a deprecation warning.v2is what you have today, and it's still the default in this release.v3is new. It mergesallOfmembers according to whatallOfactually means, reports conflicting members as errors instead of quietly picking one, and generates union types that follow the spec more closely. For example, aoneOfthat only adds constraints no longer produces a union, and anallOfthat only adds a description to a$refis simply that$ref's type.
v1 and v2 keep receiving bug fixes, but nothing that would break code that already works with them. The differences between the versions, with the code each one generates, are described in docs/schema-merging.md, including what to check when moving from v2 to v3.
Please try v3 and tell us what breaks. It becomes the default in the next release (see the end of these notes).
Dozens of allOf/anyOf/oneOf fixes, backed by a test matrix (#2562)
Alongside the versioning work, we built a test matrix that puts every schema shape we know of in every position where we generate code (a component, a property, array items, request and response bodies, and so on), sends it through a generated client and strict server, and checks that it comes back unchanged. This found a lot of bugs, all fixed in this release:
- Specs that failed to generate: an
allOfwhere any member had adefault, or added onlyreadOnly/writeOnly; OpenAPI 3.1type: [object, "null"]members; a schema with bothanyOfandoneOf. - Generated code that didn't compile: reusable responses with inline schemas, and unions with a non-string discriminator.
- Data that was lost or changed on the wire: non-string discriminator values, union properties that overwrote a variant's values, reusable responses whose body is an array or map, and inline request bodies with
additionalProperties. oneOf/anyOfparameters can now be built by callers and bound by servers.
This closes some of our oldest open issues, including #839, #1147, #1379 and #1619.
More control over generated names (#2683)
Three new opt-in settings under output-options.naming answer several long-standing requests. Each one changes a single, narrow behavior, and nothing changes unless you set it:
output-options:
naming:
enum-values:
keep-underscores: true
properties:
leading-underscore: drop
explicit-names: verbatim| Setting | Input | Default | With the setting |
|---|---|---|---|
enum-values.keep-underscores |
enum value SOME_ENUM_NAME |
SOMEENUMNAME |
SOME_ENUM_NAME |
properties.leading-underscore: drop |
property _id |
UnderscoreId |
Id |
explicit-names: verbatim |
x-go-name: HARD_CODED_ID |
HARDCODEDID |
HARD_CODED_ID |
With explicit-names: verbatim, a name you wrote by hand in x-go-name or x-enum-varnames is used exactly as written.
Configurable struct tags (#2448)
Struct tags used to be hard-coded. The new output-options.struct-tags setting lets you change the built-in json and form tags, or add your own (yaml, db, validate, and so on). Each tag is a small Go template:
output-options:
struct-tags:
tags:
- name: db
template: '{{.FieldName}}'Without the setting, the generated tags are exactly what they were. The older yaml-tags flag still works; a yaml entry here takes precedence over it.
Configurable content type names (#2449)
The new output-options.content-types setting maps media types to the short name used in generated type names (the JSON in FindPetsJSONRequestBody). This is most useful for vendor media types: application/vnd.mycompany.v1+json can now produce FindPetsV1RequestBody, and gets models generated for it, instead of a name derived from the media type.
OpenAPI 3.2 QUERY and custom HTTP methods (#2645)
OpenAPI 3.2 adds a query operation (the HTTP QUERY method) and an additionalOperations map for any other HTTP method. Both are now supported on every server and in the client.
Important
chi and Fiber only accept HTTP methods they have been told about. The generated code does not do that setup for you, because it's process-wide and one process often hosts several generated packages. If your spec uses QUERY or a custom method with chi or Fiber, add the one-time registration to your main() as described in the README and in docs/chi-server.md, docs/fiber-server.md and docs/fiber-v3-server.md.
One JSON codec for your whole program (#2665)
Generated models, clients and servers now encode and decode JSON through the runtime instead of calling encoding/json directly. The default is still encoding/json, so nothing changes unless you ask. To use a different JSON library, call this once in your main package:
runtime.SetJSONCodec(myCodec)This is also our intended path to encoding/json/v2. Thanks to @CRaLFa for the implementation. A few places are not covered yet: request body binding and ctx.JSON in the Echo, Gin, Fiber and Iris strict servers still use the framework's own JSON handling.
Overlays no longer depend on the Speakeasy library (#2643)
Our overlay support came from a library whose dependencies broke under go get -u (#2502). We've replaced it with a small implementation of our own, which removes that whole dependency chain from the module. Overlay targets are now written in standard JSONPath (RFC 9535); see the breaking changes below if you use overlays.
More OpenAPI 3.1 support
- Enums written as a
oneOfofconstvalues now become Go enums even when the outer schema has notype, which is the common way to write them (#2520, thanks @sorochinssky). - Multi-type schemas such as
type: [string, integer]used to fail generation. They now map toany(#2522, thanks @bendrucker). - The singular
examplekeyword is read under 3.1 (#2523, thanks @bendrucker).
The rest of the notables
- Strict middleware can be shared between packages (#2660):
StrictHandlerFuncandStrictMiddlewareFuncare now type aliases, so one middleware works with every generated package for the same framework. - Form request bodies send arrays as repeated keys (#2677): a client sending an
application/x-www-form-urlencodedbody now writes an exploded array astopic=a&topic=bwhen the spec says so, instead of alwaystopic[0]=a&topic[1]=b. - Property names that differ only by separator no longer collide (#2550, thanks @rifki...
v2.8.2: Security fixes for code generation
🎉 Notable changes
This is a security release on top of v2.8.1. It addresses two further security findings reported against oapi-codegen, both in code generation:
- A schema name could inject Go code through the implicit discriminator mapping of a
oneOf/anyOf - A whole-document external
$refcould inject Go code through the property names of the inlined document
Both only matter when you generate code from a specification, or a document it references, that you do not control. Thanks to @manus-use for reporting them.
Implicit discriminator mapping keys are validated
When a discriminated oneOf or anyOf lists a $ref variant that the mapping does not name, the generator maps it under the schema's name and writes that name into the generated ValueByDiscriminator switch. Explicit mapping keys were already checked, but the implicit ones were not, and a schema name is otherwise allowed to contain quotes. The derived key is now validated like an explicit one, including when the union is assembled by an allOf merge from a member holding the variants and another holding the discriminator, and a backslash is now rejected in any mapping key, since it would start an escape sequence in the generated case label. A null-typed branch, which the generator skips as a nullability marker, is left alone.
The contents of whole-document $refs are validated
A $ref without a fragment, such as $ref: ./other.yaml, has no name the generated code could refer to, so the generator inlines the referenced document as if it were written in place. Spec validation stopped at every $ref on the assumption that external content is never copied into the output, so the property names, parameter names and header names of such a document reached struct tags and string literals unchecked. The validator now walks a whole-document reference's contents for schemas, parameters, request bodies, responses, headers and callbacks, visiting each document once. References with a fragment are still not followed, and a document replaced by an x-go-type override is not walked either, since none of it reaches the generated code.
As with v2.8.1, valid specifications generate byte-for-byte the same code as before; a specification that would have produced code it had no business producing is now rejected with an error that points at the offending value.
🐛 Bug fixes
- Validate implicit discriminator mapping keys and the contents of whole-document $refs (2.8.x backport) (#2649) @mromaszewicz
Sponsors
We would like to thank our sponsors for their support during this release.
We'd also like to thank Greptile for allowing our project to use their code review system.
v2.8.1: Security fixes for codegen and at runtime
🎉 Notable changes
This is a security release on top of v2.8.0. It addresses five security findings reported against oapi-codegen:
- Strict servers could bind a different request body than the one the validation middleware checked (runtime behaviour of generated servers)
- Remote
$refs in an untrusted specification could make the generator issue requests to arbitrary hosts (code generation) - An
operationIdcould inject Go code through the Echo per-operation middleware key (code generation) - A request body content type could inject Go code through the webhook and callback initiators (code generation)
- Server
x-go-name, server variables and non-string enum values could inject Go code (code generation)
Four of the five only matter when you generate code from a specification you do not control. The first one affects running servers, so please upgrade the generated code and the oapi-codegen/runtime and validation middleware modules together, as described below.
Allow-listing the remote documents a specification may reference
oapi-codegen resolves external $refs while it loads a specification. Until now it fetched any http(s) URL a document named, so a specification written by someone else could make the generator reach any host the build machine can see.
There is a new top-level configuration option, allow-remote-refs-from. Each entry is the URL of a referenced document 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.yamlFor compatibility, this release defaults the option to "*" when it is omitted, so existing configurations keep working unchanged. The next minor release will default to refusing remote references. If your specification downloads other documents at generation time, tighten this now by listing them, or set the option to [] to refuse them all.
Better still, for reproducible builds, download the specifications you depend on, commit them next to your own, and reference them by relative path. References to local files are always followed, with no allow-listing involved, and your generated code no longer depends on a remote host being up and unchanged.
Strict servers bind the value the validation middleware validated
A validation middleware decodes the JSON request body to validate it, and the generated strict server then decoded it a second time. encoding/json matches member names case-insensitively, so a body such as
{"role": "user", "ROLE": "admin"}validates as role: user but was bound as Role: "admin", bypassing the schema's constraints.
Strict servers for every supported framework now bind the value the middleware already validated, with exact member-name matching, and only fall back to decoding the body themselves when no validated value is present. For the fix to take effect you need all three of:
- code generated with this release;
github.com/oapi-codegen/runtimev1.8.0 or later;- a validation middleware that keeps the validated value, which the following versions do by default:
github.com/oapi-codegen/nethttp-middlewarev1.3.1github.com/oapi-codegen/echo-middlewarev1.2.1github.com/oapi-codegen/echo-v5-middlewarev0.2.1github.com/oapi-codegen/gin-middlewarev1.2.1github.com/oapi-codegen/iris-middlewarev1.2.1github.com/oapi-codegen/fiber-middlewarev1.3.0github.com/oapi-codegen/fiber-v3-middlewarev0.3.0
Without them the generated code behaves as before, so the upgrade is safe to roll out in any order, but the fix is only in effect once all three are updated.
Fewer specification strings reach the generated code unescaped
Every string that the generator copies from a specification into Go source is now either emitted through strconv.Quote or checked before generation: content types in the webhook and callback initiators, the Echo per-operation middleware key, security scopes, non-string enum values (which must now be number or boolean literals), response status keys, component names, response header styles, and, when server-urls is enabled, server names, variables and their enum values. Valid specifications generate byte-for-byte the same code as before; a specification that would have produced code it had no business producing is now rejected with an error that points at the offending value.
🐛 Bug fixes
- Quote or validate every spec string that reaches generated Go source (2.8.x backport) (#2626) @mromaszewicz
- Apply the allow-remote-refs-from "*" default to the loader used after an overlay (2.8.x) (#2624) @mromaszewicz
- Refuse remote $refs unless their host is in allow-remote-refs-from (2.8.x backport, default "*") (#2623) @mromaszewicz
- Bind the validated request body value in all strict servers (2.8.x backport) (#2621) @mromaszewicz
Sponsors
We would like to thank our sponsors for their support during this release.
We'd also like to thank Greptile for allowing our project to use their code review system.
v2.8.0: OpenAPI 3.1, fewer assumptions, and a giant bug hunt
OpenAPI 3.1, webhooks, callbacks, and a lot of polish
This is a big one. After a long stretch of internal refactoring across the last couple of releases, we've been able to land some features that have been on the wishlist for years, most notably initial OpenAPI 3.1 support. As always, the full, automatically-generated changelog is at the bottom, and the sections below call out the things you'll actually want to read before upgrading.
When this project was originally released, it supported a narrow set of OpenAPI features, and over time, it has grown from generating code for hand crafted, structurally tight specifications, to very complex, and often messy specifications. I don't think we can ever handle every specification, however, over time, we're going to give users control over as many behaviors as possible, so that our assumptions, which can't be right for everyone, are configurable. More changes of this form will continue to come in the upcoming releases.
Before you upgrade
A couple of housekeeping notes up front:
- Go 1.25 is now required. If you're not there yet, you'll need to bump your toolchain before pulling this in. We had to update to 1.25 to pull in a kin-openapi that supports OpenAPI 3.1
- Use generated code with
runtimev1.6.0 or newer. Several features in this release (the newDurationtype, escaped-path-parameter handling, typed response headers) rely on functionality that landed in the runtime, so make sure you're ongithub.com/oapi-codegen/runtimev1.6.0+ when you regenerate.
☢️ Breaking changes
We try hard to avoid breaking changes, and when we can't, to make them narrow or configurable.
Trailing-slash routes on the net/http server no longer act as catch-alls (#2460)
This one only affects the standard-library net/http server (the one built on ServeMux). It's a correctness fix, which is why we decided to just do it rather than hide it behind a flag.
Here's the problem: a ServeMux pattern ending in / matches the entire subtree beneath it, but an OpenAPI path ending in / means exactly that path and nothing deeper. So we were both mismatching the spec's semantics and, worse, panicking at registration time when two such patterns overlapped ambiguously. We now anchor any trailing-slash path with {$} so it matches only what the spec says it should.
The result: if your spec has trailing-slash paths, requests to deeper URLs that used to get swallowed by the catch-all will now correctly return 404. (ServeMux still issues its usual 307 redirect from the un-slashed path to the canonical one.) If you were relying on the old subtree behavior, that was never what your spec actually declared.
Security scopes are no longer emitted by default (#2440)
Generated servers used to emit per-scheme context key types (bearerAuthContextKey and friends), scope constants (BearerAuthScopes), and per-operation context stores that flattened your spec's security requirements into the request context. We've stopped emitting these by default.
The reason is that this machinery is fundamentally broken: it can't represent alternative (OR), combined (AND), or anonymous ({}) security requirements, so it quietly encourages people to build authorization logic on top of a representation that doesn't actually capture what the spec says. Authentication and authorization belong in the request validation middleware, which evaluates the real security requirements directly.
If you genuinely need the old emission back, there's an opt-in flag:
compatibility:
enable-auth-scopes-on-context: trueWe'd encourage you to migrate to the validation middleware instead, but the flag is there if you need a bridge.
🎉 Notable changes
OpenAPI 3.1 support (#2336)
Finally, after several years of requests, we've been able to close #373, adding OpenAPI 3.1 support. We've added support for callbacks and webhooks, and we support several OpenAPI 3.1 idioms, such as flexible enums via oneOf, as well as type: [T, "null"]-style nullability. This is initial support, so we'd love to hear about the specs it doesn't yet handle well.
While oapi-codegen would love to see an increase in sponsorship to make the project more sustainable, if we had to choose, we'd prefer to see that money go upstream to kin-openapi, which is the OpenAPI library that powers us and a large part of the Go ecosystem.
We're working to sponsor Pierre, the solo kin-openapi maintainer, with a significant portion of our own funds, and really hope that y'all consider sponsorship to support the important work that he does.
The OpenAPI 3.1 support in kin-openapi wouldn't have been possible without Pierre's maintainership, and a number of external contributors.
Optionally hoist anonymous schemas into named types (#2366)
You can now opt in to having every anonymous, inline schema hoisted into a top-level named type, with a name derived from its location (path) in the spec. If you've ever wanted a real, referenceable Go type for some deeply-nested inline object instead of an anonymous struct, this is for you.
We now validate the spec before generating (#2435)
oapi-codegen has always been extremely permissive about the specs it accepts, which is great until a malformed spec leads to non-compiling generated code and a confusing debugging session. We now run a validation pass over the spec before code generation, which lets us catch a class of errors that are hard to detect during codegen and abort early with a meaningful error message instead of emitting broken Go. As a bonus, this makes us considerably more resilient to malicious or garbage input.
Handlers are now registered in spec order (#2465, #2477)
Some routers make matching decisions based on the order in which handlers are registered. To make behavior predictable and match your intent, we now emit route registrations in the same order the paths appear in your spec, so you have control of the order by controlling the order in which you declare them. To go back to the previous behavior, add this to your configuration:
compatibility:
sort-handler-registrations: trueformat: duration now maps to a real Duration type (#2458)
A type: string, format: duration schema used to fall through to a plain Go string, leaving all the parsing and validation up to you. The runtime now ships an RFC 3339 Duration type (added in runtime v1.5.0), and the default type mapping resolves format: duration to it, right alongside the other formats like date, uuid, email, and binary.
This does change the generated type for specs already using format: duration. If you'd rather keep the old plain-string behavior, map the format back explicitly in your config:
output-options:
type-mapping:
string:
formats:
duration:
type: stringThe rest of the notables and new features
A quick rundown of the other behavior-affecting changes worth knowing about:
- Fiber v3 support (#2431, thanks @dillonbuchanan-maia-tech) — codegen now targets the stable Fiber v3, in addition to v2.
- Anonymous security alternatives are allowed (#2432, thanks @kriptoburak) — an empty
{}entry in asecuritylist (i.e. "auth optional here") is now handled correctly. - Response models expose schema-extraction helpers (#2379, thanks @rd-andreas-tollkoetter) — added functions on response models to make it easier to pull schemas back out.
deprecatedGodoc is emitted correctly (#2405, thanks @jamietanna) — deprecation markers now land on the right declarations so your tooling actually flags them.- Better generated client Godoc (#2407, thanks @jamietanna) — improved documentation comments on generated client code.
- Escaped-path-parameter handling (#2457) — generated code now tells the runtime whether the router delivers already-escaped path parameter values, fixing a class of decoding bugs (this is part of why you want runtime v1.6.0+).
- Typed response headers (#2462, #2463) — response headers are now parsed into typed fields on the client response wrappers.
There's a great deal more in the way of bug fixes below — this release fixes a large batch of long-standing issues in the aggregate-type (allOf/anyOf/oneOf), discriminator, and external-$ref code paths. Thank you to everyone who reported issues and sent PRs.
☢️ Breaking changes
- Anchor trailing-slash stdhttp routes with {$} to match OpenAPI semantics (#2460) @mromaszewicz...
v2.7.2 More fixes for code injection issues
String escaping fixes due to more code injection issues
We've had two more code injection issues reported in oapi-codegen, thanks @Gal3m, @mrostamipoor for these findings.
These specific issues are now patches in the main branch and in this v2.7.2 release.
You shouldn't blindly trust OpenAPI specs
This code wasn't originally written assuming code generation from random specs from the internet, and it never took any measures to protect itself from malicious specifications, the assumption being that you control your specification, and that you actually look over generated code.
For example, all these RCE exploits rely on using the package init() function in the generated code to run some malicious code at package startup. A way to test for this is to see whether an init() function is emitted, which we currently don't do.
When working with OpenAPI specifications, especially specs you find on remote servers, you should download the spec locally, run some kind of spec validator on it, like openapi-spec-validator, and only then feed it into oapi-codegen. We're very permissive in accepting broken specifications, intentionally, since people feed a lot of garbage input, but this flexibility also makes us weak to these kinds of attacks. There are hundreds of injection sites in oapi-codegen based on my survey.
For the next minor release, v2.8.0, we're going to validate the spec before code generation (#2435), however, since this introduces a new set of failure modes, I don't want to include it in a maintenance release version. The future release is resilient against many forms of injection, and the spec validation has the added benefit that it can generate meaningful error messages for garbage input, where currently, we generate non-compiling code.
Until then, please do sanity checks on your input specifications, on the generated output, and don't fetch specs from the internet in your build, commit both the spec locally into your source control, and go through code review. In our repo, we've hooked up Greptile to catch issues like this, and you should also use some code quality tool. We can't possibly protect against every kind of attack with simple heuristics.
Sponsors
We would like to thank our sponsors for their support during this release.
We'd also like to thank Greptile for allowing our project to use their code review system.
Security fix for Go code injection
This is a security fix for a code injection vulnerability in v2.7.0, please see:
Note
A vulnerability like this requires that it is missed in code review and that you then call the malicious method.
Using an init() function could be enough to not require a direct call to the code, and instead rely on you importing the package, but either way, code review should be performed before any oapi-codegen generated code is executed.
We strongly recommend all users to be reviewing changes to their generated code before they execute anything within it, to protect against supply chain attacks or malicious injected code.
This is also why we recommend oapi-codegen generated code is committed to source control.
We're more strict about escaping strings passed into the OpenAPI specification, so that people can't inject Go code into generated code.
The problem was that it was possible to craft a description for server URL's which would emit arbitrary Go code, so if an attacker controlled your specification, they could inject Go code into your generated code which could do something malicious.
v2.7.0: Squashing bugs, many bugs (and adding some features)
Many improvements and even more bug fixes
This v2.7.0 release of oapi-codegen contains quite a bit of internal refactoring, focused on our most historically fragile code paths, which relate to the aggregate types (allOf/anyOf/oneOf), $ref to external specs, enums, and the spec traversal logic missing quite a few leaf nodes where models should have been generated, but were skipped.
The biggest changes are explicitly described in the sections below, and the full list of commits is at the bottom.
Thank you to all contributors, we've been going through all past PR's and updating them and merging where we can, and thanks to all our users for reporting issues that you hit.
I've (@mromaszewicz) used a lot of LLM help here to scrub through old issues and do some deep internal refactoring to address common problem areas. I intend to continue doing this, since the conditional generation logic is getting quite complicated. When I originally released oapi-codegen, the use case was much simpler, all the models were under #/components/schemas, and all the references to them were in the requests, responses, etc. I never imagine how many things would be external references or unions, and how many complex OpenAPI specifications people would be generating code for. The initial design was never flexible enough to handle that, so ongoing bug fixes are getting increasingly complex due to edge cases. This version has a lot of internal changes you won't see as a user, but the way we handle type generation internally is unifying lots of copy/paste re-implementations into reusable code for consistency. Most of these changes can be done transparently, but some can't, so, onto the changes:
Code generation changes which might require some changes on your end
This release contains three changes, all very narrow in scope, which will require some manual adjustment of your own code. We've decided that these are small enough and uncommon enough not to require opt-in, which causes internal complexity. It's always a judgment call with these. If we got it wrong, we're happy to revisit it in a maintenance release.
Strict-server external response refs require strict-server generation in both packages (#2357)
If your strict-server spec uses an external $ref to a components/responses/... defined in another spec, that other
spec must also be generated with strict-server: true. Add it to the source spec's config and regenerate:
# config for the spec being $ref'd
generate:
models: true
strict-server: true # now required when imported by a strict-server specThis restores the v2.0.0 behavior that lets you cast response models across package boundaries — the standard pattern
for sharing error models (e.g. a common 400) across services. PR #1387 had silently changed the embedded type from N400JSONResponse to the bare externalRef0.N400, so the local and external response structs no longer had
matching types and casts stopped compiling.
Many more anonymous inner schemas are now hoisted into top level schemas
Inline oneOf, anyOf, and additionalProperties schemas embedded directly under an operation's request or response
body now flow through the same boilerplate-emission pipeline as components/schemas, so they get the
As* / From* / Merge* accessor methods they were previously missing. As part of that change, two older naming patterns
are replaced with one pattern, shared with all components:
GetPets_200_Data_Item → GetPets200JSONResponseBody_Data_Item
GetPets200JSONResponse_Data_Item → GetPets200JSONResponseBody_Data_Item
In practice, we think this shouldn't break anyone, because this change addresses a bug which produced pointless types
with no benefit, and you never interact with these directly, but rather you'd call an accessor on a field of a model.
Strict middleware typedefs are now inlined (#2271)
StrictHandlerFunc and StrictMiddlewareFunc in generated strict-server code are now inline type definitions instead
of aliases to github.com/oapi-codegen/runtime/strictmiddleware/<framework>. Generated servers no longer import that package.
Before (Echo example):
import strictecho "github.com/oapi-codegen/runtime/strictmiddleware/echo"
type StrictHandlerFunc = strictecho.StrictEchoHandlerFunc
type StrictMiddlewareFunc = strictecho.StrictEchoMiddlewareFuncAfter:
type StrictHandlerFunc func(ctx echo.Context, request any) (any, error)
type StrictMiddlewareFunc func(f StrictHandlerFunc, operationID string) StrictHandlerFuncIf your code referenced the per-framework names directly — strictecho.StrictEchoHandlerFunc, strictgin.StrictGinHandlerFunc, strictnethttp.StrictHTTPHandlerFunc, strictiris.StrictIrisHandlerFunc, strictecho5.StrictEcho5HandlerFunc — switch to the local StrictHandlerFunc / StrictMiddlewareFunc exposed by the generated server package, or import runtime/strictmiddleware/<framework> yourself if you really want those names. The underlying signatures are unchanged, so any value satisfying the old type still satisfies the new one.
🎉 Notable changes
Go 1.24 required (#2264)
oapi-codegen itself now requires Go 1.24.4+ to build and run. The toolchain in your project's go.mod (the one used to invoke the codegen) must be ≥ 1.24.4. The code generated will still likely work on older versions. We had to update to Go 1.24 in order to update some dependencies to address vulnerabilities. Go 1.24 is no longer supported, so our next release will update to Go 1.25,
and the plan is to stay on supported Go versions. I'm not sure if 1.25 will come in v2.8.0 or v2.7.1 yet, but it's imminent. We
have a number of submodules in this repo which exist only to test Go 1.25 routers in a 1.24 module, and it allows us to
simplify.
Unfortunately, some of our transitive dependencies result in a broken build, by default, so you might have to pin these
packages to specific versions:
- github.com/speakeasy-api/jsonpath v0.6.3
- github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 (See #2015 for some discusion)
Multi-pass type name resolution (#2213)
Set output-options.resolve-type-name-collisions: true to make the codegen detect identifier collisions across schemas, parameters, request bodies, response components, and operation-derived types — and resolve them deterministically by suffixing the loser. Specs that previously failed to generate because two definitions wanted the same Go name now succeed.
Trivial example. With this spec:
components:
schemas:
Status:
type: string
enum: [active, archived]
parameters:
Status:
name: status
in: query
schema:
type: stringoutput-options.resolve-type-name-collisions: true produces:
type Status string // from components.schemas.Status
const StatusActive Status = "active"
const StatusArchived Status = "archived"
type StatusParameter = string // from components.parameters.StatusCollision resolution is opt-in. Generated identifier names depend on the current set of collisions in the spec;
adding a new schema or parameter later that collides with an existing one will rename the existing one to break the new collision.
That can silently break user code that imports the previously-stable name as the spec drifts. However, despite the drift,
more specs can now correctly generate boilerplate.
Parameter binding matrix (#2307)
The OpenAPI parameter style × explode × type matrix is now fully supported and round-trips consistently across
every server backend. Path/query/header/cookie parameters across primitive, array, and object types — including
style: form / spaceDelimited / pipeDelimited / deepObject × explode: true/false, and style: simple for headers —
generate the same binding logic on every server, and the client-side encoding is symmetric. The internal parameter test suite (internal/test/parameters/) now exercises every combination through a server round-trip per backend.
If you previously hit an unsupported style error, or saw a parameter serialization work under one backend but not another,
regenerate and the issue should be gone.
You will need to use version v1.4.0 or higher of github.com/oapi-codegen/runtime.
Optional / nullable response headers (#2301)
For strict-server responses, optional and nullable headers now generate as pointer fields (or nullable.Nullable[T]
when the nullable-types output option is set). The generated server only calls w.Header().Set(...) when the field
is non-nil, so callers can omit optional headers cleanly.
Spec:
responses:
'200':
headers:
X-Required: { required: true, schema: { type: string } }
X-Optional: { schema: { type: string } }Before:
type GetFoo200ResponseHeaders struct {
XRequired string
XOptional string // always emitted, even when empty
}After:
type GetFoo200ResponseHeaders struct {
XRequired string
XOptional *string // nil → header not sent
}To opt out of this change, set compatibility.headers-implicitly-required: true to restore the previous always-required behavior. This change breaks enough code that we flagified it.
🚀 New features
Echo v5 server support ([#2188](https://github.com/oapi-codegen/oapi-cod...
v2.6.0: 7th anniversary release 🎂
For those that aren't aware, 7 years ago to the day, oapi-codegen was born!
(Well, technically it's tonight at midnight UTC, but who's splitting hairs?)
There's nothing too special planned for today, but we thought it'd be the perfect time to cut a slice of cake a release!
🎉 Notable changes
New generated code requires oapi-codegen/runtime v1.2.0+
As part of #2256, github.com/oapi-codegen/runtime v1.2.0 is needed alongside github.com/oapi-codegen/oapi-codegen, for new generated code.
This is providing a more future-proofed means to bind parameters.
See the release notes for the runtime package, and #2256 for more information.
oapi-codegen was part of the GitHub Secure Open Source Fund
oapi-codegen was one of the projects taking part in the third GitHub Secure Open Source Fund session.
We've written up more about what we've learned, and have some more things to share with you over the coming months about lessons we've learned and improvements we've taken that we can share.
We were pretty chuffed to be selected, and it's already helped improve our security posture as a project, which is also very important for the wider ecosystem!
go directive bump in next release
Long-time users will be aware that we work very hard to try and keep our requirement for Go source compatibility, through the go directive, especially as we recommend folks use oapi-codegen as a source-tracked dependency.
For more details about this, see our Support Model docs.
In the next minor release, we'll be setting our minimum go directive to Go 1.24 (End-of-Life on 2026-02-11), as it's required for a number of dependencies of ours to be updated any higher, and a change to the module import path for Speakeasy's OpenAPI Overlay library requires us fix this centrally for our users to be able to continue updating their libraries.
Note
Nothing is changing as part of v2.6.0, this is a pre-announcement for v2.7.0.
Behind the scenes cleanup
There's also been some work behind-the-scenes to try and clean up outstanding issues (of which we know there are many!) that have been fixed, as well as Marcin's work on trying to do some more significant rework of the internals with help from Claude.
There's still, as ever, work to go with this - as we've mentioned before, sponsoring our work would be greatly appreciated, so we can continue to put in the work, considering this is a widely used and depended on project.
🚀 New features and improvements
- feat: Pass schema type/formats to runtime v1.2.0 to allow better parameter serialization (#2256) @mromaszewicz
- feat: add Valid() method to generated enum types (#2227) @mromaszewicz
- Support nullable slice elements and map values (#2185) @iamtakingiteasy
- feat: add configurable type mapping for OpenAPI primitive types (#2223) @mromaszewicz
- Support unions with multiple mappings pointing to a single underlying type (#2071) @tobio
- feat: add support for custom package alias for external ref imports (#2211) @InventivetalentDev
- feat(output-options): add
resolve-type-name-collisionsto avoid name collisions (#200) @mgurevin - Adopt fiber middleware template for updated GetReqHeaders() method signature (#1419) @getBolted
🐛 Bug fixes
- fix: qualify external ref schema types in default response codes (#2241) @mromaszewicz
- fix: add omitempty to optional nullable fields (#2221) @mromaszewicz
- fix(codegen): generate
nullable.Nullablein arrays (#2242) @jamietanna - fix: support x-oapi-codegen-extra-tags on parameter schemas (#2232) (#2235) @mromaszewicz
- fix(templates/client): correctly nil check query parameters (#2237) @jamietanna
- fix(server-urls): restore generation of constants (#2239) @jamietanna
- fix(server-urls): use URL in GoDoc if
descriptionis empty (#2226) @jamietanna - fix: set indentation to 2 when marshalling spec for overlay (#2172) @wndhydrnt
- fix: handle optional request bodies in strict server mode (#2222) @mromaszewicz
- fix(strict-server): generate correct type for
$reftext responses (#2225) @mromaszewicz - Fix schema gathering oversight (#2219) @mromaszewicz
- fix: handle duplicate path parameters in OpenAPI specs (#2220) @mromaszewicz
- fix: escape quoted media type directives (#2217) @brahmlower
- Fix Iris strict server for no content case (#1411) @ShouheiNishi
- Fixes type collision for enum values that start with _ (underscore) (#1438) @ula
📝 Documentation updates
- chore: readme update (#2209) @mromaszewicz
- docs: fix link to example (#1884) @rkosegi
- docs(extensions): correct links to examples (#1836) @yuro241
- docs(sponsors): update section (#2195) @jamietanna
- docs(sponsors): remove Elastic as a sponsor (#2083) @jamietanna
👻 Maintenance
- chore(renovate): add module path to security updates + override test-only dependencies' label (#2249) @jamietanna
- Configure Greptile code review (#2236) @mromaszewicz
- style(gofix): Apply
go fix(#2229) @gaiaz-iusipov - Run golangci-lint on a supported Go version (#2215) @mromaszewicz
- refactor(internal): move Fiber tests into their own modules (#2212) @mromaszewicz
- build: use a re-usable, single, workflow for running CI (#2205) @jamietanna
- fix(renovate): only run
make tidyafter Go module updates (#2159) @jamietanna - chore(renovate): run
make tidyafter dependency updates togo.mod(#2150) @jamietanna
📦 Dependency updates
8 changes
- chore(deps): update module github.com/golangci/golangci-lint to v2.10.1 (makefile) (#2153) @renovate[bot]
- chore(deps): update github/codeql-action action to v4.32.4 (.github/workflows) (#2157) @renovate[bot]
- chore(deps): update actions/setup-go action to v6.3.0 (.github/workflows) (#2164) @renovate[bot]
- chore(deps): update actions/checkout action to v6 (.github/workflows) - autoclosed (#2165) @renovate[bot]
- chore(deps): update release-drafter/release-drafter action to v6.2.0 (.github/workflows) (#2253) @renovate[bot]
- chore(deps): update actions/upload-artifact action to v7 (.github/workflows) (#2254) @renovate[bot]
- chore(deps): update dessant/label-actions action to v5 (.github/workflows) (#2255) @renovate[bot]
- chore(deps): update release-drafter/release-drafter action to v6.1.0 (.github/workflows) (#2132) @renovate[bot]
Sponsors
We would like to thank our sponsors for their support during this release.
v2.5.1: fix a couple of regressions from v2.5.0
🐛 Bug fixes
- fix(templates): correctly nil check arrays (#2118) @jamietanna
- fix: report formatting errors with line numbers (#2117) @jamietanna
- fix(output-options): correctly reference
x-go-type-skip-optional-pointerinallOf(#2042) @magnetikonline
📝 Documentation updates
- docs: clarify support +
godirectives (#2099) @jamietanna - docs: correct level of headers (#2095) @jamietanna
- docs(sponsors): update Speakeasy logo (#2049) @chailandau
- Fix bullet point line
prefer-skip-optional-pointer-with-omitzerotypo inREADME.md(#2028) @magnetikonline
👻 Maintenance
- build: handle additional values in
GOVERSION(#2119) @jamietanna - build: add explicit
permissionsblocks fortidy.yml(#2101) @jamietanna - build: add explicit
permissionsblocks for Actions (#2100) @jamietanna - build: add Scorecards workflow (#2098) @jamietanna
- build: capture
govulncheckresults as Code Scanning alerts (#2084) @jamietanna - build: test against Go 1.25 (#2056) @jamietanna
Renovate configuration changes
- chore(renovate): improve actionability of pending updates (#2120) @jamietanna
- chore(renovate): don't exclude
examplesandinternal/test(#2033) @jamietanna - chore(renovate): correctly create branches for top-level files (#2138) @jamietanna
📦 Dependency updates
9 changes
- fix(deps): update module github.com/getkin/kin-openapi to v0.133.0 (go.mod) (#2141) @renovate[bot]
- fix(deps): update module github.com/stretchr/testify to v1.11.1 (go.mod) (#2142) @renovate[bot]
- chore(deps): update module github.com/golangci/golangci-lint to v2.6.0 (makefile) (#2140) @renovate[bot]
- chore(deps): update ossf/scorecard-action action to v2.4.3 (.github/workflows) (#2128) @renovate[bot]
- chore(deps): update actions/upload-artifact action to v5 (.github/workflows) (#2136) @renovate[bot]
- chore(deps): update actions/setup-go action to v6 (.github/workflows) (#2135) @renovate[bot]
- chore(deps): update actions/labeler action to v6 (.github/workflows) (#2134) @renovate[bot]
- chore(deps): update actions/checkout action to v5 (.github/workflows) (#2133) @renovate[bot]
- chore(deps): update github/codeql-action action to v4 (.github/workflows) (#2137) @renovate[bot]
Sponsors
We would like to thank our sponsors for their support during this release.
v2.5.0: No more optional pointers (optionally), `omitzero`, better control over initialisms, and so much more!
v2.5.0: No more optional pointers (optionally)!
🎉 Notable changes
Begone optional pointers! (optionally)
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 anomitemptyJSON tagprefer-skip-optional-pointer-with-omitzero: when used in conjunction withprefer-skip-optional-pointer, any optional fields are generated with anomitzeroJSON 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).
Note
The default is not changing.
We take care to avoid breaking changes so this is, as many changes, an opt-in.
See Globally skipping the "optional pointer" for more details.
Generating omitzero JSON tags, with x-omitzero
Related to the above functionality, it is possible to define the OpenAPI extension x-omitzero on fields to generate the omitzero JSON tag, based on the (now not-so-new) Go 1.24 release.
Thanks to @lzap for the contribution 🚀
Note
oapi-codegen does not currently validate the Go version that the module it's generating code for.
This could lead to the omitzero JSON tag being generated, but not being actually usable.
Ensure that you're using a Go 1.24+ version, and that your go directive (for source compatibility) is go 1.24 or i.e. go 1.24.1
Using OpenAPI 3.1 with oapi-codegen
There's some promising behind-the-scenes discussions with may lead to OpenAPI 3.1 support (#373) coming in the not-too-distant future 👀
In the meantime, Jamie (one of the Core Maintainers) has written a blog post about how to use oapi-codegen with OpenAPI 3.1 specs (by downgrading them to OpenAPI 3.0).
Defining your own initialisms
As a means to define your own custom initialisms, it's possible to use the additional-initialisms Output Option.
Thanks @micaelmalta for the contribution 🚀
If your organisation uses a lot of TLAs (Two Letter Acronyms or Three Letter Acronyms) or any other sorts of initialisms, it's handy to be able to configure these yourself.
For instance, if you regularly use the term CSP to refer to Cloud Service Provider, you may want CSP to be used in variable names.
This makes it possible to define i.e.
# ...
output-options:
name-normalizer: ToCamelCaseWithInitialisms
additional-initialisms:
- CSPNote
This only works when the name-normaliser Output Option is set to ToCamelCaseWithInitialisms. An error will occur if you've not configured this correctly.
Minimum version of Go needed for oapi-codegen is now 1.22.5
As part of a couple of updates in #1888 and #1986, we're now requiring Go >= 1.22.5.
Similar to the bump to Go 1.21 in v2.4.0
Notable background work
Since the last oapi-codegen release (all the way in September 2024 🥲) the following big changes towards the project and its ecosystem have been:
net/httpmiddleware v1.1.0: Better error handling, allow not validatingServers(by configuration) and return an HTTP 405 Method Not Allowed where appropriate- Jamie posted a look back at the last year
- Notably also writing up explicitly how the project is currently governed
runtime: fixes formaps andx-go-type-skip-optional-pointer
🚀 New features and improvements
- feat(client): Add
Bytes()toClientWithResponsesresponses (#1780) @grongor - feat(generate): allow generating Server URL boilerplate (#2002) @jamietanna
- feat(output-options): add
prefer-skip-optional-pointer-on-container-types(#1979) @jamietanna - feat(output-options): add
prefer-skip-optional-pointerto default to skipping optional pointers (#1694) @aksdb - feat(output-options): add
yaml-tagsoption (#1798) @deitch - feat(templates): consolidate logic for whether to use an optional pointer (#1981) @jamietanna
- feat(x-deprecated-reason): add default deprecation message (#2022) @jamietanna
- feat: allow specifying
additional-initialisms(#1733) @micaelmalta
🐛 Bug fixes
- Handle leading underscores in property names (#1822) @tobio
- fix(codegen): allow exposing the input spec's
operationId(#1945) @jamietanna - fix(codegen): allow using x-go-type and x-go-type-skip-optional-pointer together (#1957) @Nivl
- fix(output-options): obey
prefer-skip-optional-pointerin reference types + add tests forpreferskipoptionalpointer(#2021) @jamietanna - fix(overlay): correctly resolve references after Overlay application (#1825) @jgraeger
- fix(stdhttp): correctly generate root paths (#1953) @jamietanna
- fix: Print the warning message to stderr instead of stdout (#1895) @ignassew
- fix: create directories if they do not exist before writing output file (#1994) @kf-pineapple
- fix: don't generate an "optional pointer" for unknown types (#610) @jens1205
📝 Documentation updates
- docs: add example for how to downgrade OpenAPI 3.1 to 3.0 (#1966) @jamietanna
- Add blog post about using oapi-codegen in a Chi project (#1791) @0xi4o
- Fix broken anchor link for validation middleware section (#2013) @Park-Jongseok
- chore(tests): add additional test case for underscore naming (#1980) @jamietanna
- docs(client): document known issue with duplicated
Responsemodels (#2025) @jamietanna - docs(extensions): correct typo to example (#1999) @i-sevostyanov
- docs(extensions): don't use
<details>blocks in<table>(#2019) @jamietanna - docs(extensions): update example code for
x-enumNames(#2000) @jamietanna - docs(middleware): clarify use of
nethttp-middlewarefor other purposes (#1951) @jamietanna - docs(sponsors): add Livepeer (#1849) @jamietanna
- docs(sponsors): update Speakeasy URL (#1970) @ndimares
- docs(std-http-server): warn when not using Go 1.22 (#1967) @jamietanna
- docs: add contributors image (#1795) @jamietanna
- docs: add example of using
go toolfor Go 1.24+ (#1908) @jamietanna - docs: fix GitHub flavoured markdown (#1934) @MarvinJWendt
- docs: fix typo in flags usage (#1796) @AlekSi
- docs: note the use of a multi-module
tools.go(#1788) @jamietanna - docs: simplify go tool example (#1910) @gaiaz-iusipov
- docs(additional-initialisms): add a usage example (#2026) @jamietanna
👻 Maintenance
- build(labels): add additional labelling (#1848) @jamietanna
- build(labels): add autolabeller for "no
mainbranch please" (#1847) @jamietanna - build: build against Go 1.24 (#1901) @jamietanna
- build: ensure separately named "Check results" steps (#1850) @jamietanna
- chore(examples): use Go 1.24 with Go 1.24 example (#1925) @jamietanna
- chore(tests): add additional test case for underscore naming (#1980) @jamietanna
- chore: don't use non-GitHub URL for tests (#1926) @jamietanna
- fix(output-options): obey
prefer-skip-optional-pointerin reference types + add tests forpreferskipoptionalpointer(#2021) @jamietanna
📦 Dependency updates
13 changes
- fix(deps): update module github.com/getkin/kin-openapi to v0.132.0 (#2024) @renovate[bot]
- fix(deps): update module github.com/getkin/kin-openapi to v0.131.0 [security] (#1986) @renovate[bot]
- chore(deps): update module github.com/golangci/golangci-lint to v2.2.2 (#2014) @renovate[bot]
- fix(deps): update module github.com/speakeasy-api/openapi-overlay to v0.10.2 (#1973) @renovate[bot]
- chore(deps): update module github.com/golangci/golangci-lint to v2 (#1940) @renovate[bot]
- chore(deps): update actions/setup-go digest to d35c59a (#1969) @renovate[bot]
- fix(deps)!: update module github.com/speakeasy-api/openapi-overlay to v0.10.1 (#1888) @renovate[bot]
- chore(deps): pin dependencies (#1948) @renovate[bot]
- chore(deps): update module github.com/golangci/golangci-lint to v1.64.5 (#1871) @renovate[bot]
- fix(deps): update module golang.org/x/text to v0.20.0 (#1792) @renovate[bot]
- fix(deps): update module github.com/stretchr/testify to v1.10.0 (#1844) @renovate[bot]
- chore(deps): update module github.com/golangci/golangci-lint to v1.62.2 (#1828) @renovate[bot]
- fix(deps): update module github.com/getkin/kin-openapi to v0.128.0 (#1794) @renovate[bot]
Sponsors
We would like to thank our sponsors for their support during this release.