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_ItemIn 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)
Echo v5 (the upcoming major version) is now a supported server framework. Generate with generate.echo5-server: true. Echo v4 is unchanged and remains the target of generate.echo-server.
Per-handler middleware in Fiber (#2302)
Fiber generated servers now accept a HandlerMiddlewares []HandlerMiddlewareFunc slice in FiberServerOptions, applied around every operation handler. The middleware signature is func(c *fiber.Ctx, next fiber.Handler) error, matching Fiber's native middleware pattern. Useful for cross-cutting concerns (auth, logging, metrics) that should run after path-level routing but inside the generated-handler boundary.
Per-operation middleware in Echo (#2353)
Echo's RegisterHandlersWithOptions now accepts an OperationMiddlewares map[string][]echo.MiddlewareFunc keyed by operationId, attaching middleware to specific operations at registration time:
api.RegisterHandlersWithOptions(e, server, api.RegisterHandlersOptions{
OperationMiddlewares: map[string][]echo.MiddlewareFunc{
"createPet": {authMiddleware, auditMiddleware},
"deletePet": {authMiddleware, adminOnlyMiddleware},
},
})Operations with no entry in the map (or a nil map) are registered with no extra middleware. Available for both Echo v4 and Echo v5 generated servers.
Strict-gin error handlers (#1600)
The Gin strict server now exposes RequestErrorHandlerFunc and ResponseErrorHandlerFunc on StrictServerOptions, matching the pattern already available for the Echo strict server. Bind errors and response-write errors flow through your custom handler instead of using gin's default abort behaviour. Defaults are preserved if you don't set them.
โข๏ธ Breaking changes
- Update external-refs to responses in strict-server to fix an old regression (#2357) @mromaszewicz
- Overhaul anonymous schema hoisting (#2348) @mromaszewicz
- Inline strict middleware typedefs (#2271) @mromaszewicz
๐ Notable changes
- Overhaul anonymous schema hoisting (#2348) @mromaszewicz
- fix: clean up and test parameter binding (#2307) @mromaszewicz
- support optional/nullable response headers (#2301) @mromaszewicz
- Update all dependencies to Go 1.24 (#2264) @mromaszewicz
- feat: multi-pass type name resolution (#2213) @mromaszewicz
๐ New features and improvements
- per-operation middleware in Echo (#2353) @mromaszewicz
- support all x-* extensions and with ref (#1880) @paulmach
- feat(client): Add ContentType() to ClientWithResponses responses (#2173) @CJourneaux
- Flagify enum validator generation (#2334) @mromaszewicz
- Strictgin error handler (#1600) @actatum
- Fix a streaming bug + document streaming through example (#1765) @perbu
- Add support for path aliases (#2312) @mromaszewicz
- fix: add x-go-name for server urls (#2304) @dhpollack
- Support handler-specific middleware for gofiber (#2302) @jpetrich
- feat: use http.MethodXXX constants instead of string literals in generated code (#2294) @imsugeno
- Generate types from components/securitySchemes to be used as a key in context.WithValue (#1187) @nek023
- feat: Support echo/v5 (#2188) @jinuthankachan
- feat: multi-pass type name resolution (#2213) @mromaszewicz
๐ Bug fixes
- Route server enums through general enums codegen (#2358) @mromaszewicz
- Update external-refs to responses in strict-server to fix an old regression (#2357) @mromaszewicz
- respect output file path on gofmt failure (#2356) @mromaszewicz
- Strict server: gate no-content response headers on nullable/optional (#2351) @mromaszewicz
- Synchronize strict servers (#2350) @mromaszewicz
- Overhaul anonymous schema hoisting (#2348) @mromaszewicz
- fix: allow x-go-type and x-go-type-skip-optional-pointer for allOf (#1610) @turip
- Propagate external refs into allOf (#2299) @mromaszewicz
- Add missing case to type generation traversal (#2298) @mromaszewicz
- fix: delegate MarshalJSON on strict response types wrapping union refs (#2332) @mromaszewicz
- fix: pointer skipping for client query params (#2330) @mromaszewicz
- fix: support x-oapi-codegen-extra-tags on path params in strict-server RequestObject (#2262) @mromaszewicz
- sanitize param names for http.ServeMux since they must be valid Go identifiers (#2279) @mromaszewicz
- Bug Report: demonstration of overlays and allOf not playing together nicely (#2087) @nelzblooket
- fix: include additional types for array response type (#1930) @viktorasm
- fix: allOf cycle detection oversight (#2316) @mromaszewicz
- fix: avoid stack overflow errors when using heavily recursive types (#1377) @yoshikipom
- fix: Change FormParams to FormValues for Echo v5 (#2311) @nicolasmattelaer
- Fix exploded parameter marshaling and binding inconsistencies (#2184) @TelpeNight
- fix(cli): remove unused
initialism-overridesoption (#2287) @gaiaz-iusipov - fix: getting cookie in fiber middleware (#2062) @YATAHAKI
- Fix typo in echo-v5 middleware import (#2285) @mromaszewicz
- fix(client): correctly marshal
text/plainrequests (#1975) @jamietanna - fix: allow response error handler to set status code (#1963) @sean-cunniffe
- AllOf : Only stop when merging schemas with multiple discriminators (#667) @LelouBil
- fix: use RequiresNilCheck for all params (#2263) @mromaszewicz
๐ Documentation updates
- docs: remove non-breaking spaces (#2328) @jamietanna
- docs: note that JSON Schema should be pinned (#2266) @jamietanna
๐ป Maintenance
- refactor(codegen): better Swagger compression, modern naming (#1909) @gaiaz-iusipov
- fix example codegen (#2354) @mromaszewicz
- Update Greptile settings (#2345) @mromaszewicz
- Replace old hand written slice sorting with slices package, and other built-in helpers (#2305) @gaiaz-iusipov
๐ฆ Dependency updates
9 changes
- Update YAML package where possible (#2333) @mromaszewicz
- chore(deps): update release-drafter/release-drafter action to v7.2.0 (.github/workflows) (#2322) @renovate[bot]
- fix(deps): use updated import path for
github.com/speakeasy-api/openapi/overlay(#2231) @netixx - fix(deps): update module github.com/getkin/kin-openapi to v0.135.0 (go.mod) (#2320) @renovate[bot]
- Update release-drafter config for V7 (#2317) @mromaszewicz
- chore(deps): update release-drafter/release-drafter action to v7 (.github/workflows) (#2293) @renovate[bot]
- fix(deps): update module github.com/getkin/kin-openapi to v0.134.0 (go.mod) (#2295) @ilia-rassadin-rn
- chore(deps): update release-drafter/release-drafter action to v6.3.0 (.github/workflows) (#2282) @renovate[bot]
- chore(deps): update oapi-codegen/actions action to v0.6.0 (.github/workflows) (#2273) @renovate[bot]
Sponsors
We would like to thank our sponsors for their support during this release.