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 / operation-and-client-generation

Operation and client generation

Operation generation turns each OpenAPI path and method into a shared description of its name, parameters, request bodies, responses, and security rules. Client generation uses that description to produce request builders and HTTP client methods, while the response layer adds typed body and header access when the wire format is known. Shared parameter types are resolved across paths, webhooks, and callbacks before operation output is built, so the same global Go type namespace remains safe. This page is a child of generation pipeline; generator configuration, schema and model generation, server interface generation, specification filtering and validation, and template rendering describe the adjacent stages.

Operation definitions

An operation definition is the common contract between the OpenAPI document and the generated code. It keeps path data, normalized Go names, parameter groups, body and response descriptions, and related type definitions together so client, server, and strict-server output use the same view of an operation. OperationDefinitions reads normal paths; webhooks and callbacks use the same shape with a caller-supplied URL instead of a path template. Before these operation lists are built, shared path-item parameters are resolved across all three source kinds so their helper types cannot collide in the generated package (home/…/operations.go• L393-531, home/…/operations.go• L1718-1914, home/…/operations.go• L1930-2184).

Security requirements come from the operation when it defines them. Otherwise, the document-level requirements apply. References to security schemes that are not defined in the document are removed from the generated operation view so the emitted security helpers remain valid (home/…/operations.go• L618-651, home/…/operations.go• L1725-1883).

Operation names

The generated operation name comes from operationId after name normalization and any configured type prefix. If the document has no operationId, the generator derives a name from the HTTP method and path, such as GetV1FooBar for GET /v1/foo/bar. This name becomes the base for client methods, request types, response wrappers, and parameter types (home/…/operations.go• L1769-1785, home/…/operations.go• L2187-2203).

An internal path alias can point to an existing path item. The alias gets a unique client-facing name, but server wrapper references still target the canonical operation. The raw operation ID remains available where generated behavior must match the source document, such as per-operation middleware keys (home/…/operations.go• L1787-1807, home/…/operations.go• L654-722).

References: home/…/operations.go• L654-722 home/…/operations.go• L1769-1807 home/…/operations_test.go• L93-153

Parameter groups

Parameters are grouped by their wire location. Path parameters remain direct method arguments because they are required to build the route. Query, header, and cookie parameters are collected into one optional <Operation>Params value, which keeps method signatures stable as non-path parameters grow (home/…/operations.go• L808-829, home/…/operations.go• L2621-2679).

Path-item parameters apply to every method on that path. An operation-level parameter with the same name and location replaces the inherited one; duplicate parameters at the same level are rejected. Shared helper types are declared once for each path item. When the same helper name appears on different paths, webhooks, or callbacks, the generator adds a stable scope token to every colliding scope, while leaving non-colliding names unchanged. This keeps generated names stable for existing specifications and distinct for new collisions (home/…/operations.go• L393-605, home/…/operations.go• L3076-3104).

Parameter names stay separate from Go field and variable names. The original name is used for the HTTP key and JSON tag, while a normalized name is used in generated Go. Optional values use pointers unless the schema or output settings explicitly skip the optional pointer. OpenAPI 3.1 unions and untyped values get named helper types or nil-safe handling so generated parameter code can pass them to the runtime without treating a nil value as a concrete value (home/…/operations.go• L57-85, home/…/operations.go• L190-215, home/…/operations.go• L226-280, home/…/operations.go• L296-368).

References: home/…/operations.go• L57-85 home/…/operations.go• L204-368 home/…/operations.go• L393-605 home/…/operations.go• L808-829 home/…/operations_test.go• L760-839 home/…/operations_test.go• L1030-1141

Request generation

Request generation combines an operation's path, parameter object, and request body into a builder that returns an http.Request. The client method calls the builder, attaches the context, applies request editors, and sends the request through the configured HTTP doer (/home/user/repo/pkg/codegen/templates/client.tmpl#L86-L101).

Request method variants

Every operation gets one generic client method. An operation without a body uses the operation name directly; an operation with a body uses <Operation>WithBody and accepts a content type plus an io.Reader. Each client-supported request media type also gets a typed body variant, such as <Operation>WithJSONBody, that accepts the generated request-body type (home/…/client_view.go• L5-15, home/…/client_view.go• L61-121).

The typed variant marshals the body for its media type and forwards it to the generic builder. JSON uses the process-wide runtime JSON codec, form data uses form encoding, and plain text uses a string form for primitive or fmt.Stringer values. Other media types keep the generic reader method unless a configured content-type name supplies a model; a model alone does not add a typed client method (/home/user/repo/pkg/codegen/templates/client.tmpl#L113-L143, home/…/operations.go• L1273-1318).

This diagram shows how one operation becomes the public client surface and then an HTTP request.

flowchart LR
    Spec[OpenAPI path and method] --> Op[Operation definition]
    Op --> Params[Path arguments and Params object]
    Op --> Bodies[Request body definitions]
    Params --> Builder[Request builder]
    Bodies --> Builder
    Builder --> Request[http.Request]
    Request --> Client[Client method]
    Client --> Editors[Request editors]
    Editors --> Doer[HTTP doer]

References: home/…/client_view.go• L5-121 home/…/client.tmpl• L86-143 home/…/operations.go• L1153-1318

Parameter encoding

The request builder resolves path values into the operation path, then adds query, header, and cookie values. Schema style and explode rules control structured parameter encoding; JSON-valued parameters use the process-wide runtime JSON codec, and pass-through values are sent as strings. Optional parameters are omitted when their value is absent (/home/user/repo/pkg/codegen/templates/client.tmpl#L146-L167, /home/user/repo/pkg/codegen/templates/client.tmpl#L184-L220, /home/user/repo/pkg/codegen/templates/client-partials.tmpl#L17-L44).

Query encoding preserves styled query fragments separately from ordinary encoded values. This keeps delimiters such as commas in an OpenAPI-defined styled value instead of escaping them as part of a single value (/home/user/repo/pkg/codegen/templates/client.tmpl#L184-L220).

References: home/…/client.tmpl• L146-220 home/…/client-partials.tmpl• L17-44

Content-type behavior

Content types affect both the names of generated types and the way the client handles bytes on the wire. The media type remains the source of truth for encoding and decoding, while output-options.content-types can give a media type a short name and can make a model available for a media type that has no built-in model path (home/…/configuration.go• L539-569, home/…/operations.go• L2223-2376).

Request content types

Request bodies are described once per content entry. application/json is the default unsuffixed body name; other modeled entries use a media-type tag such as Formdata, Multipart, Text, or a configured tag. Vendored JSON types get a name derived from the media type when no short-name mapping matches (home/…/operations.go• L2223-2251).

The client has built-in typed request handling for JSON-like media types, URL-encoded form data, and plain text. Multipart and unknown media types use the generic body path, so callers provide the encoded content through io.Reader unless another generated layer provides the required handling (home/…/operations.go• L1273-1307, home/…/client_view.go• L101-118). For URL-encoded form bodies, supported primitive arrays can use repeated form keys when the OpenAPI encoding requests exploded form style; other encoding options do not change the client's body format (home/…/operations.go• L1321-1386, home/…/operations.go• L2307-2315).

References: home/…/operations.go• L1159-1318 home/…/operations.go• L1321-1386 home/…/operations.go• L2214-2323 home/…/client_view.go• L61-121 home/…/client.tmpl• L113-143

Response content types

Response definitions retain status, headers, and each declared content entry. The response-aware client exposes a raw body for every response and adds typed fields only for content that it knows how to decode. JSON-like media types use JSON decoding, YAML uses YAML decoding, and XML uses XML decoding; unsupported content remains available as raw bytes. The response field and the generated body model use the same media-type suffix when one response has multiple JSON-compatible entries. This also lets response references resolve to the correct local or external model (home/…/operations.go• L951-1150, home/…/operations.go• L1394-1683, home/…/template_helpers.go• L108-224).

When one response declares more than one JSON-compatible media type, the generated fields use media-type-specific names and require an exact Content-Type match. With one JSON-compatible entry, the parser can use a broader JSON content check. A response with no content type is treated as bodyless rather than sent through a decoder (home/…/operations.go• L951-976, home/…/template_helpers.go• L143-188, home/…/template_helpers.go• L228-261).

Response body types do not always have the same shape as the response envelope. When a schema cannot serve as a direct response value, the generated strict response keeps the typed value in a Body field; reusable response definitions can then be embedded without invalid pointer or interface shapes. The type decision is shared by response definition generation and the client response view so both sides refer to the same body type (home/…/operations.go• L1439-1515, home/…/operations.go• L2376-2463).

Response headers are exposed in typed status-specific header structs. The parser fills a header struct when the response status matches; an absent header leaves its zero value, while a present value that cannot bind to its declared type returns an error (/home/user/repo/pkg/codegen/templates/client-with-responses.tmpl#L41-L64, /home/user/repo/pkg/codegen/templates/client-with-responses.tmpl#L145-L176).

References: home/…/operations.go• L934-1150 home/…/operations.go• L1394-1683 home/…/operations.go• L2326-2572 home/…/client-with-responses.tmpl• L41-176 home/…/template_helpers.go• L108-261

Content-type name mappings

The built-in short names cover JSON, URL-encoded form data, multipart data, and plain text. A user mapping replaces the pattern list for a matching built-in key, and an empty list disables that key. A media type that matches more than one short name is rejected because the generated type names would be ambiguous (home/…/configuration.go• L555-569, home/…/content_types_test.go• L243-288).

Short names change generated identifiers, not wire behavior. For example, renaming the form tag still uses form marshaling, while mapping text/csv can create a request model but does not create a typed response field because the client has no CSV decoder (home/…/content_types_test.go• L95-148, home/…/content_types_test.go• L150-205).

References: home/…/configuration.go• L539-569 home/…/content_types_test.go• L95-148 home/…/content_types_test.go• L150-288

Response-aware clients

The response-aware client wraps the basic client and turns each returned http.Response into an operation-specific response value. That value keeps the raw body and HTTP response and can hold one typed body field for each recognized status and content-type pair (/home/user/repo/pkg/codegen/templates/client-with-responses.tmpl#L1-L14, /home/user/repo/pkg/codegen/templates/client-with-responses.tmpl#L53-L64).

Each <Operation>WithResponse method calls the matching basic client method and then parses the response. Parsing reads and closes the body, selects a decoder from status and Content-Type, stores the typed value when decoding succeeds, and preserves status, headers, and raw bytes for callers (/home/user/repo/pkg/codegen/templates/client-with-responses.tmpl#L116-L127, /home/user/repo/pkg/codegen/templates/client-with-responses.tmpl#L131-L177).

The generated response value always provides status and status-code access. Body getters are generated by default and can be disabled; an optional Bytes helper can expose the same raw body, and ContentType can expose the response header (/home/user/repo/pkg/codegen/templates/client-with-responses.tmpl#L66-L111, home/…/configuration.go• L458-484).

References: home/…/client-with-responses.tmpl• L1-177 home/…/configuration.go• L458-484

Server URL support

Server URL generation turns OpenAPI servers entries into reusable URL constants or constructors. A server with no URL variables becomes a constant. A server URL with variables becomes a New<ServerName> function that validates enum values, substitutes declared variables, accepts undeclared placeholders as strings, and rejects unresolved braces (home/…/server_urls.go• L48-98, /home/user/repo/pkg/codegen/templates/server-urls.tmpl#L1-L83).

Server names come from x-go-name, the server description, or the URL, with numeric suffixes for name conflicts. Only variables used by URL placeholders become generated types and function arguments. Enum variables get typed values and validation; non-enum variables use string-based types and optional defaults (home/…/server_urls.go• L100-160, home/…/server_urls.go• L329-394).

The generated client stores its base server URL in Server. Construction normalizes it with a trailing slash, and each request resolves the operation path against it. A relative base path therefore remains part of the final request URL. WithBaseURL provides a checked option for replacing the base URL (/home/user/repo/pkg/codegen/templates/client.tmpl#L13-L53, /home/user/repo/pkg/codegen/templates/client.tmpl#L169-L183, /home/user/repo/pkg/codegen/templates/client-with-responses.tmpl#L18-L27).

Webhooks and callbacks use a different URL model. Their initiators do not store a server URL because the caller supplies the full target URL for each call; their operation definitions therefore reject path parameters instead of silently leaving route placeholders unresolved (home/…/operations.go• L764-795, /home/user/repo/pkg/codegen/templates/initiator.tmpl#L1-L12, /home/user/repo/pkg/codegen/templates/initiator.tmpl#L89-L103).

References: home/…/server_urls.go• L48-160 home/…/server_urls.go• L329-394 home/…/server-urls.tmpl• L1-83 home/…/operations.go• L764-795 home/…/operations.go• L1917-2184

Generation boundaries

The main generation pass builds normal path operations first, then adds webhook and callback operations for shared type and import collection. Client output is enabled by generate.client; request and operation types are emitted through the model/type path, so a client-only configuration must still account for the types its methods reference (home/…/codegen.go• L311-368, home/…/codegen.go• L516-539).

Server URL output is separate from operation and model output. generate.server-urls emits its URL constructors and variable types even when generate.models is disabled, while the client uses a caller-provided server string unless the generated URL helpers are chosen by the caller (home/…/configuration.go• L183-190, home/…/codegen.go• L395-422). Specification filtering and validation determines which operations reach this stage, and template rendering turns the shared definitions into Go source.

References: home/…/codegen.go• L311-368 home/…/codegen.go• L395-422 home/…/codegen.go• L516-539

Change checklist

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

  • Keep OperationDefinition fields, ClientMethodVariants, and both client templates aligned. A change to a method suffix or argument list must apply to interfaces, implementations, request builders, and response wrappers.
  • Keep request and response content-type naming in sync with output-options.content-types. A short-name change must still leave wire encoding and decoder selection based on the media type.
  • Keep JSON request bodies and JSON-valued parameter paths on the runtime JSON codec. A direct encoder call can bypass process-wide codec settings and make generated requests differ from generated models or server code.
  • Keep form body encoding metadata aligned with the client serializer. A change to exploded primitive arrays must update both the operation data and the generated form encoder.
  • Keep GetResponseTypeDefinitions and genResponseUnmarshal aligned. Every typed response field needs a matching status and content-type branch, and every declared bodyless response must avoid an empty-body decode.
  • Keep shared path-item parameter handling aligned with operation-local parameter merging. Helper types must be emitted once per path item while each operation still receives the full parameter set. Collision checks must cover normal paths, webhooks, and callbacks because they share one generated Go namespace.
  • Keep operation name normalization, raw operation IDs, and alias targets aligned. Client names may be unique generated names while server wrappers and middleware keys still refer to different source identities.
  • Keep security requirement filtering aligned with generated security scheme types. An undefined scheme must not produce a middleware or context-key reference.
  • Keep server URL variable discovery, generated function parameters, enum declarations, and substitution logic in sync. Used and undeclared placeholders must produce a usable constructor signature.
  • Keep webhook and callback operation extraction aligned with initiator signatures. These operations use a full target URL and cannot accept path parameters.

Important failure modes

TriggerConsequenceGuard
A media type matches more than one content-type short nameGeneration cannot choose stable request or response type namesValidate mappings and use one matching pattern set per media type (home/…/content_types_test.go• L207-220)
A mapped unsupported response media type has no known decoderThe client exposes only raw bytes, not a typed response fieldTreat the mapping as a naming rule; add a decoder path before expecting typed response access (home/…/content_types_test.go• L198-205)
A generated response field and unmarshal branch use different media-type namingGenerated code can refer to a field or type that does not existDerive both from GetResponseTypeDefinitions and the same content-type rules (home/…/operations.go• L934-1150, home/…/template_helpers.go• L151-188)
A JSON request path bypasses the configured runtime codecCustom JSON behavior does not apply to that request body or parameterUse the runtime JSON codec for request bodies and JSON-valued path, query, and cookie parameters (/home/user/repo/pkg/codegen/templates/client.tmpl#L113-L143, /home/user/repo/pkg/codegen/templates/client.tmpl#L149-L167, /home/user/repo/pkg/codegen/templates/client.tmpl#L196-L203, /home/user/repo/pkg/codegen/templates/client.tmpl#L238-L245)
A form array's operation metadata and serializer disagreeThe client sends indexed values when the API expects repeated keys, or the reverseKeep ExplodedFormArrays and form encoding behavior derived from the same schema and encoding rules (home/…/operations.go• L1321-1386, home/…/operations.go• L2307-2315)
Two operation-derived helper types collide with a component typeGeneration fails instead of emitting Go code with duplicate type namesKeep operation type naming distinct from component names and surface the duplicate typename error (home/…/operations_test.go• L1077-1108)
A callback or webhook declares a path parameterThe initiator has no route template in which to substitute the valueReject the operation during extraction (home/…/operations.go• L1977-1984, home/…/operations.go• L2128-2135)
A security requirement names an undefined schemeGenerated operation security code can refer to a type or helper that does not existFilter requirements against components.securitySchemes before emitting operation definitions (home/…/operations.go• L639-651, home/…/operations.go• L1725-1883)
A server URL contains a placeholder without a declared variableThe constructor cannot use the URL safely unless the caller supplies the valueAdd the placeholder as a string constructor argument and reject any braces left after substitution (home/…/server_urls.go• L69-98, /home/user/repo/pkg/codegen/templates/server-urls.tmpl#L58-L82)
Shared helper parameters on different paths use the same generated nameGenerated packages can contain duplicate helper types or unstable namesResolve shared parameter scopes across paths, webhooks, and callbacks, then add stable scope tokens only to colliding scopes (home/…/operations.go• L438-562)

Key files

FileWhy to read it
home/…/operations.goDefines the operation view and turns paths, parameters, bodies, responses, webhooks, and callbacks into generation inputs.
home/…/client_view.goDefines the method variants shared by client interfaces, implementations, and request builders.
/home/user/repo/pkg/codegen/templates/client.tmplShows base client construction, request building, parameter encoding, body handling, runtime JSON encoding, and HTTP execution.
/home/user/repo/pkg/codegen/templates/client-with-responses.tmplShows typed response wrappers, response parsing, status handling, and response headers.
/home/user/repo/pkg/codegen/templates/client-partials.tmplShows the shared header parameter serialization used by path clients and initiators.
home/…/template_helpers.goDefines response decoder selection and status/content-type matching.
home/…/server_urls.goDefines server URL discovery, variable types, enum validation, and constructor inputs.
/home/user/repo/pkg/codegen/templates/server-urls.tmplShows the generated constant and constructor forms for server URLs.
home/…/configuration.goDefines content-type naming and client response options that change this generation surface.
home/…/codegen.goShows where operation, type, server URL, client, webhook, and callback generation passes connect.