Configuration¶
oapi-codegen uses YAML configuration files to control code generation behavior. This page documents all available configuration options.
Basic Usage¶
Create a configuration file (e.g., cfg.yaml) and reference it when running oapi-codegen:
go run github.com/doordash-oss/oapi-codegen-dd/v3/cmd/oapi-codegen --config cfg.yaml spec.yaml
Tip
Use the JSON schema for IDE autocomplete and validation:
# yaml-language-server: $schema=https://raw.githubusercontent.com/doordash/oapi-codegen/HEAD/configuration-schema.json
Configuration Options¶
Package Settings¶
package¶
Type: string | Default: "gen"
The Go package name for generated code.
package: myapi
copyright-header¶
Type: string | Default: "Code generated by oapi-codegen. DO NOT EDIT."
Header comment added to all generated files.
copyright-header: "Copyright 2024 My Company. Code generated by oapi-codegen. DO NOT EDIT."
skip-prune¶
Type: boolean | Default: false
When true, keeps all types from the spec even if they're not referenced by any operations. By default, unreferenced types are pruned.
skip-prune: true
Overlay Settings¶
overlay.sources¶
Type: string[] | Default: []
List of overlay files to apply to the OpenAPI spec before code generation. Each source can be a file path or URL. Overlays are applied in order.
overlay:
sources:
- ./overlays/add-go-names.yaml
- https://example.com/shared-overlay.yaml
See Overlays for detailed documentation and examples.
Output Settings¶
output.use-single-file¶
Type: boolean | Default: true
Generate all code in a single file. When false, splits code into multiple files (types, client, etc.).
output:
use-single-file: false
Note
When use-single-file: false, the generator automatically creates a subdirectory named after the package value. For example, with package: api and directory: ".", files are written to ./api/. To control the exact output location, set directory explicitly (e.g., directory: api).
output.directory¶
Type: string | Default: "."
Directory where generated files should be placed.
output:
directory: "./generated"
Note
When use-single-file: false, the package name is appended as a subdirectory. For example, directory: "./generated" with package: api outputs to ./generated/api/. When use-single-file: true, files are written directly to the specified directory.
output.filename¶
Type: string | Default: "gen.go"
Filename to use when use-single-file: true.
output:
filename: "api.gen.go"
Generation Settings¶
generate.client¶
Type: boolean | Default: false
Generate HTTP client code for calling the API.
generate:
client: true
See examples/client/example1/cfg.yaml for a complete example.
generate.omit-description¶
Type: boolean | Default: false
Omit schema descriptions from generated code comments.
generate:
omit-description: true
generate.default-int-type¶
Type: string ("int" | "int32" | "int64") | Default: "int"
Default Go type to use for OpenAPI integer types without a format specifier.
generate:
default-int-type: int64
generate.always-prefix-enum-values¶
Type: boolean | Default: true
Prefix enum constants with the schema name to avoid naming conflicts.
generate:
always-prefix-enum-values: false
generate.models¶
Type: boolean | Default: true
Generate model types. Set to false when models are generated in a separate package and you only want to generate client or handler code.
generate:
models: false
generate.handler.output.overwrite¶
Type: boolean | Default: false
Force regeneration of scaffold-once files (e.g., service.go, middleware.go). Normally these files are only generated if they don't exist.
generate:
handler:
output:
overwrite: true
Validation Settings¶
generate.validation.skip¶
Type: boolean | Default: false
Skip generation of Validate() methods on types.
generate:
validation:
skip: true
generate.validation.simple¶
Type: boolean | Default: false
Use simple validation approach with validate.Struct() for all types.
generate:
validation:
simple: true
generate.validation.response¶
Type: boolean | Default: false
Generate Validate() methods for response types (useful for contract testing).
generate:
validation:
response: true
Handler/Server Generation¶
Generate server-side handler code with a service interface pattern. Supports multiple router frameworks.
generate.handler.kind¶
Type: string | Required
The router/framework to generate handler code for. Supported values:
chi- go-chi/chiecho- labstack/echofiber- gofiber/fibergin- gin-gonic/ginstd-http- Go standard librarynet/http
generate:
handler:
kind: chi
generate.handler.name¶
Type: string | Default: "Service"
Name of the generated service interface.
generate:
handler:
kind: chi
name: "APIService"
generate.handler.models-package-alias¶
Type: string | Default: ""
Package alias to prefix model types with. Used when models are generated in a separate package (generate.models: false).
generate:
models: false
handler:
kind: chi
models-package-alias: types
This generates types.User instead of User in the handler code.
generate.handler.multipart-max-memory¶
Type: integer | Default: 32
Maximum memory in MB for multipart form parsing. Files exceeding this limit are stored in temporary files on disk.
generate:
handler:
kind: chi
multipart-max-memory: 64
generate.handler.validation.request¶
Type: boolean | Default: false
Enable validation of incoming requests in handlers.
generate:
handler:
kind: chi
validation:
request: true
generate.handler.validation.response¶
Type: boolean | Default: false
Enable validation of outgoing responses in handlers. Useful for contract testing.
generate:
handler:
kind: chi
validation:
response: true
generate.handler.output¶
Type: object | Default: uses root output settings
Output settings for scaffolded handler files (service.go, middleware.go).
generate:
handler:
kind: chi
output:
directory: api
package: api
generate.handler.middleware¶
Type: object | Default: null
Enable generation of middleware.go scaffold file. If not set, no middleware file is generated.
generate:
handler:
kind: chi
middleware: {}
generate.handler.server¶
Type: object | Default: null
Enable generation of a runnable server/main.go file.
generate:
handler:
kind: chi
server:
directory: server
port: 8080
timeout: 30
handler-package: github.com/myorg/myapi/api
| Property | Type | Default | Description |
|---|---|---|---|
directory |
string |
"server" |
Output directory for main.go |
port |
integer |
8080 |
Port the server listens on |
timeout |
integer |
30 |
Request timeout in seconds |
handler-package |
string |
required | Full import path of the handler package |
See examples/server/ for complete examples of handler generation with different frameworks.
Filtering¶
Filtering allows you to include or exclude specific parts of your OpenAPI specification during code generation. This is useful when you only need to generate code for a subset of your API.
How Filtering Works¶
- Include filters - Only generate code for matching items
- Exclude filters - Generate code for everything except matching items
- Precedence - Exclude filters take precedence over include filters
- Transitive pruning - When schema properties are filtered out, schemas that are only referenced by those properties are also pruned
Filter by Paths¶
Filter operations by API path patterns.
filter:
include:
paths:
- /client
- /orders
See examples/filtering/by-path/cfg.yaml for a complete example.
Filter by Tags¶
Filter operations by OpenAPI tags.
filter:
include:
tags:
- purchase
- admin
See examples/filtering/by-tag/cfg.yaml for a complete example.
Filter by Operation IDs¶
Filter specific operations by their operationId.
filter:
include:
operation-ids:
- getUser
- createUser
exclude:
operation-ids:
- deleteUser
Filter by Schema Properties¶
Filter which properties are included in generated types. This triggers transitive pruning - schemas that are only referenced by filtered-out properties will also be pruned.
filter:
include:
schema-properties:
User:
- id
- email
- name
- organization
Organization:
- id
- name
- plan
In this example:
- Only the specified properties are included in User and Organization types
- If User.address referenced an Address schema, and address is not in the include list, the Address schema will be pruned (unless referenced elsewhere)
See examples/filtering/by-property/cfg.yaml for a detailed example with comments explaining transitive pruning.
Filter by Extensions¶
Filter operations or schemas by custom OpenAPI extensions.
filter:
include:
extensions:
- x-audit-log
- x-display-name
exclude:
extensions:
- x-internal
- x-deprecated
See examples/filtering/by-extension/cfg.yaml for a complete example.
Component Pruning¶
By default, oapi-codegen prunes unused component schemas. You can control this behavior:
# Keep all schemas, even if unused
skip-prune: true
# Or use filtering to keep specific components
filter:
include:
paths:
- /users
# This will keep User schema and all schemas it references
See examples/filtering/by-components/cfg.yaml for examples of component pruning behavior.
Additional Imports¶
Add custom Go imports to generated code.
additional-imports:
- package: github.com/google/uuid
- package: github.com/shopspring/decimal
alias: dec
Error Mapping¶
Configure response types to implement the error interface. The value is a dotted path to the error message field.
error-mapping:
GetClientErrorResponse: message
UpdateClientErrorResponseJSON: arrayField[].code
When configured, the response type will have:
Error() stringmethod - Returns the value from the specified field path- Constructor function -
NewTypeName(message string)for easy error creation
Generated Code Example¶
Given this configuration:
error-mapping:
InvalidRequestError: error.message
The generator produces:
type InvalidRequestError struct {
ErrorData *ErrorData `json:"error,omitempty"`
}
func (i InvalidRequestError) Error() string {
res0 := i.ErrorData
if res0 == nil {
return "unknown error"
}
return res0.Message
}
func NewInvalidRequestError(message string) InvalidRequestError {
return InvalidRequestError{ErrorData: &ErrorData{Message: message}}
}
The constructor is useful in server implementations for returning typed errors:
func (s *Service) CreateUser(ctx context.Context, opts *CreateUserOpts) (*CreateUserResponse, error) {
if opts.Body.Email == "" {
return nil, NewInvalidRequestError("email is required")
}
// ...
}
See examples/client/example1/cfg.yaml for a complete example.
User Templates¶
Override default code generation templates with your own.
user-templates:
client.tmpl: ./templates/my-client.tmpl
types.tmpl: ./templates/my-types.tmpl
User Context¶
Provide custom context values that can be used in templates.
user-context:
api-version: v1
company-name: "My Company"
Complete Example¶
Here's a comprehensive configuration example:
# yaml-language-server: $schema=https://raw.githubusercontent.com/doordash/oapi-codegen/HEAD/configuration-schema.json
package: myapi
copyright-header: "Copyright 2024 My Company. Code generated by oapi-codegen. DO NOT EDIT."
output:
use-single-file: false
directory: "./generated"
generate:
client: true
omit-description: false
default-int-type: int64
always-prefix-enum-values: true
validation:
skip: false
response: true
client:
name: "APIClient"
timeout: 30s
filter:
include:
tags:
- users
- orders
schema-properties:
User:
- id
- email
- name
error-mapping:
ErrorResponse: message
additional-imports:
- package: github.com/google/uuid
generate:
validation:
response: true
Client Settings¶
client.name¶
Type: string | Default: "Client"
Name of the generated client struct.
client:
name: "APIClient"
client.timeout¶
Type: duration | Default: 3s
Default timeout for HTTP requests.
client:
timeout: 30s