Introducing a new way to review your PRs.

Read the announcement

oapi-codegen / oapi-codegen

Generate Go client and server boilerplate from OpenAPI 3 specifications

View on GitHub

20 documents · Updated Nov 23, 2026

docs / server-interface-generation

Server interface and middleware generation

Server generation turns OpenAPI operations into application-facing server contracts and route adapters for a selected Go web framework. The generated layer binds incoming data, runs middleware, and writes declared responses so application code can focus on operation behavior. It also turns OpenAPI server URLs into safe, usable Go constants or constructors for generated clients and servers.

Server contract

The server contract defines how application code receives an operation request and returns its result. Normal server generation exposes framework-shaped handlers, while strict generation adds typed request and response objects around the same routes.

Handler interface

ServerInterface contains one handler method for each non-alias operation. The method receives the framework request context, path values, and an operation parameter object when the operation has grouped query, header, or cookie parameters. An alias route reuses the canonical operation handler, so it does not require a second application method.

The selected framework sets the handler shape. Standard HTTP servers use a response writer and request. Echo and Fiber return an error. Gin and Iris use their native context types. The operation and client generation page describes how these operation inputs are formed.

References: pkg/…/server-interface.tmpl• L1-25 pkg/…/operations.go• L637-665

Route registration

Route registration maps each OpenAPI path and method to a generated wrapper. The wrapper connects the framework request to the server contract and applies the configured base path and middleware options. Registration normally follows source path order. A compatibility setting can restore the older path-and-method sort order.

The route layer keeps framework concerns outside application handlers. Its exact router and error options vary by target; see framework server templates and generator configuration.

This diagram shows how one operation becomes both an application contract and a framework route.

flowchart LR
    Spec[OpenAPI operation] --> Contract[ServerInterface method]
    Spec --> Route[Framework route]
    Route --> Wrapper[Generated request wrapper]
    Contract --> Wrapper
    Wrapper --> App[Application handler]

References: pkg/…/operations.go• L2480-2521 pkg/…/operations.go• L2524-2652 pkg/…/server-handler.tmpl• L15-69

Server URL construction

OpenAPI server objects become generated URL constants when they have no active variables. A server with URL placeholders becomes a constructor that accepts the values needed to replace those placeholders and returns the complete URL.

Only variables that appear in the URL become generated types, defaults, or constructor parameters. A placeholder with no declared server variable becomes a plain string parameter. Enum variables use typed values and validate them before substitution. The generator rejects an enum default that is not in its enum and keeps generated names stable when enum values or server names collide.

The URL generator escapes specification text before placing it in Go comments and string literals. It also checks that no placeholder braces remain after substitution, so malformed input cannot silently produce a partial URL.

References: pkg/…/server_urls.go• L17-27 pkg/…/server_urls.go• L39-98 pkg/…/server_urls.go• L100-160 pkg/…/server_urls.go• L224-377 pkg/…/server-urls.tmpl• L1-83

Request binding

Request binding converts framework request data into the typed values expected by an operation. The generated wrapper checks required values and decodes path, query, header, cookie, and body data before it calls application code.

Parameter sources

Parameter location and OpenAPI serialization rules determine how each value is read. Simple values use their wire text. JSON and styled values use the shared binding rules for encoding, schema type, format, and union types. A missing required value or invalid encoding stops the request before the application handler runs.

Path-item parameters apply to every operation under that path. The generator emits shared helper types once for each scope. It keeps names unique across paths, webhooks, and callbacks without changing the values sent to the handler.

References: pkg/…/server-middleware.tmpl• L24-217 pkg/…/operations.go• L34-351 pkg/…/operations.go• L376-579

Request bodies

Request bodies become fields on strict request objects or operation-specific body types. The wrapper selects a body from the request Content-Type when an operation accepts more than one media type. JSON and form data become typed values. Multipart data becomes a reader. Text and other stream-like data remain raw bytes or a stream for application control.

An optional body may be empty. A required body treats an empty or unreadable value as a request error. Framework templates use the selected framework's binder, but they preserve this same contract. Echo, Fiber, Gin, and Iris can reuse a value stored by request validation so the handler receives the value that passed validation.

References: pkg/…/operations.go• L1136-1289 pkg/…/strict-http.tmpl• L43-128 pkg/…/strict-echo.tmpl• L35-111 pkg/…/strict-fiber.tmpl• L42-98 pkg/…/strict-gin.tmpl• L80-157 pkg/…/strict-iris.tmpl• L35-112

Response contract

Strict server generation gives each operation a typed response contract. Application code returns one declared response object and an error. The response object selects the status and content type, carries response headers, and writes the wire response through its visitor.

Response variants

Generated response types represent the status and content choices in the OpenAPI document. Fixed responses can use a compact body type. A response with variable status or content type uses an envelope that carries the selected status, content type, body, and related response data. Typed fields represent declared headers.

The response visitor writes JSON, form, text, multipart, stream, and raw-reader bodies in the required wire form. JSON bodies are written through the generated runtime JSON codec. This keeps custom JSON behavior and protocol work in generated code while application code selects a valid business result.

References: pkg/…/strict-interface.tmpl• L19-181 pkg/…/strict-responses.tmpl• L1-52 pkg/…/operations.go• L1298-1360 pkg/…/operations.go• L2102-2295

Response dispatch

The strict adapter runs operation middleware and then checks the returned value against the operation's response contract. A valid response is passed to its visitor. A handler error, a response write error, or an unexpected response type follows the configured error path.

Streaming responses can be delivered in chunks when the framework writer supports flushing. Without that support, the visitor uses a normal copy path. Fiber uses its stream callback and flushes each chunk through its response API.

References: pkg/…/strict-http.tmpl• L130-147 pkg/…/strict-gin.tmpl• L159-177 pkg/…/strict-fiber.tmpl• L100-118 pkg/…/strict-iris.tmpl• L114-137

Middleware helpers

Generated middleware helpers provide a common place for behavior that surrounds request handling. Router middleware applies across routes. Operation middleware wraps one operation after its request values are built and before its application handler runs.

Middleware shapes

Each framework uses its native handler and error model. Standard HTTP-family targets use handler middleware. Echo, Gin, Fiber, and Iris use framework-specific context functions. Fiber keeps router middleware and handler middleware distinct because its handler chain returns errors.

Strict middleware uses type aliases for its handler and middleware functions. This allows middleware written for one generated package to work with another package that uses the same framework. Each middleware also receives the OpenAPI operation ID, which lets shared middleware apply operation-specific rules.

References: pkg/…/server-middleware.tmpl• L15-22 pkg/…/strict-http.tmpl• L1-5 pkg/…/strict-echo.tmpl• L1-5 pkg/…/strict-fiber.tmpl• L1-5 pkg/…/strict-gin.tmpl• L1-5 pkg/…/strict-iris.tmpl• L1-5

Middleware keys

Per-operation middleware maps use the raw OpenAPI operationId, not the normalized Go method name. This preserves the specification identity when Go naming rules change the generated symbol. Alias routes use the canonical handler for execution while the exposed operation keeps its own middleware key.

References: pkg/…/operations.go• L686-705 pkg/…/echo-register.tmpl• L18-50 pkg/…/strict-echo.tmpl• L113-128

Strict server support

Strict server support adds typed request and response boundaries to the normal server routes. The generated adapter receives a framework request, fills the operation request object, invokes StrictServerInterface, and visits the returned response. This lets one typed application contract work with the selected framework's route model.

Strict adapter

NewStrictHandler connects a StrictServerInterface implementation to the normal ServerInterface. The adapter uses a common middleware boundary with an untyped request and response because it must serve operations with different types. The application-facing strict interface remains typed per operation.

Request errors and response or handler errors use framework-specific hooks where the target provides them. The default split treats request decode failures as client errors and application or response failures as server errors. Gin exposes separate request, handler, and response hooks. Standard HTTP exposes request and response hooks. Echo, Fiber, and Iris use their native error return or stop behavior.

References: pkg/…/configuration.go• L161-190 pkg/…/codegen.go• L496-514 pkg/…/strict-http.tmpl• L7-41 pkg/…/strict-gin.tmpl• L7-59

Framework targets

Strict generation supports one compatible server target at a time because each target emits the same package-level strict names with a different context and response signature. The target determines how the adapter reads requests, reports errors, and writes responses.

Server targetContext and response boundary
Chi, Gorilla, or standard HTTPhttp.ResponseWriter and *http.Request
Echo or Echo 5Echo context and response APIs
Gin*gin.Context
Fiber or Fiber v3Fiber context and response APIs
IrisIris context and response APIs

See framework server templates for the normal framework route model and generator configuration for target selection.

References: pkg/…/operations.go• L2655-2702 pkg/…/strict-echo.tmpl• L1-132 pkg/…/strict-fiber.tmpl• L1-121 pkg/…/strict-gin.tmpl• L1-179 pkg/…/strict-http.tmpl• L1-150 pkg/…/strict-iris.tmpl• L1-137

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep normal server method signatures aligned with generated parameter and body types.
  • Keep route names aligned with normalized Go handlers while middleware maps use raw OpenAPI operation IDs.
  • Keep request binding behavior aligned across every strict framework target, including validated request body reuse.
  • Keep response type names and visitor methods aligned with status and content selection.
  • Keep JSON response visitors on the shared runtime JSON codec so custom marshal behavior remains consistent.
  • Keep server URL type definitions and URL constructors aligned. A variable should not be emitted in one generated path but omitted from the other.
  • Keep server URL placeholder parameters aligned with the URL text. Declared-but-unused variables should not create dead parameters, and undeclared placeholders must remain callable through string parameters.
  • Keep server URL enum value names and default-pointer targets aligned when duplicate values fold to the same Go identifier.
  • If a framework context or response API changes, update its normal wrapper, route registration, strict adapter, and response visitor together.
  • If strict generation adds a target, enforce the one-target rule and provide its matching middleware and response boundary.

Important failure modes

TriggerConsequenceGuard
A required parameter or body is missing or cannot be decodedThe wrapper returns a request error before application code runs.Preserve required checks and route binding errors through the framework's request error path.
A strict handler returns an undeclared response typeThe adapter reports a response error instead of writing an undefined response.Return the operation's generated response object.
More than one strict target is enabledPackage-level strict declarations conflict.Enable one strict-compatible target.
Middleware uses a normalized Go name as its map keyThe middleware is not found for the OpenAPI operation.Use the raw operationId.
A JSON response bypasses the shared runtime codecCustom JSON marshal behavior or generated union handling can be lost.Keep strict JSON visitors on runtime.JSONMarshalWrite.
A server URL contains a declared variable that is not usedThe generated output can expose dead types or constructor parameters.Generate server URL variables only from placeholders present in the URL.
A server URL contains an undeclared placeholderURL construction can leave braces in the result or fail at runtime.Add the placeholder as a string constructor parameter and reject any remaining braces.
A server URL enum default is not one of its enum valuesCode generation fails instead of producing a misleading constant reference.Fix the OpenAPI default or enum list.
A server URL enum value collides with a generated default nameGenerated Go declarations can conflict.Use the collision-safe default-pointer name and keep its target tied to the deduplicated enum name.
A strict target changes its context or response API without matching visitorsGenerated code can fail to compile or write the response incorrectly.Update the target adapter and response visitor as one contract.

Key files

FileWhy to read it
pkg/…/operations.goDefines the operation data that feeds server contracts, binding, response types, route order, and strict target selection.
pkg/…/codegen.goShows where normal and strict server output and server URL type definitions enter the main generation flow.
pkg/…/server_urls.goDefines the high-level rules for turning OpenAPI server objects into URL constants, constructors, and typed enum definitions.
pkg/codegen/templates/server-urls.tmplShows the generated server URL interface and placeholder substitution contract.
pkg/codegen/templates/server-interface.tmplDefines the application-facing server contract.
pkg/codegen/templates/server-middleware.tmplShows shared parameter binding and middleware behavior.
pkg/codegen/templates/server-handler.tmplShows common route registration and handler options.
pkg/codegen/templates/strict/strict-http.tmplShows the standard HTTP strict adapter lifecycle.
pkg/codegen/templates/strict/strict-echo.tmplShows Echo strict binding, middleware, and response dispatch.
pkg/codegen/templates/strict/strict-fiber.tmplShows Fiber strict body handling and response dispatch.
pkg/codegen/templates/strict/strict-gin.tmplShows Gin strict error hooks and response handling.
pkg/codegen/templates/strict/strict-iris.tmplShows Iris strict request and response behavior.
pkg/codegen/templates/strict/strict-interface.tmplDefines strict request objects, response objects, response visitors, and the shared runtime JSON encoding boundary.
pkg/codegen/templates/strict/strict-responses.tmplDefines shared strict response declarations.
pkg/…/server_urls_test.goStates the safety and consistency guarantees for placeholder use, enum defaults, name collisions, and generated URL output.