oapixconstgen
July 27, 2026 ยท View on GitHub
A Go tool that extracts typed constants from OpenAPI specification files and generates Go code.
Overview
When defining OpenAPI specs, you often need to reuse constant values (like pagination limits, timeouts, or configuration values) across multiple places using YAML anchors. oapixconstgen reads these constants from the x-constants extension and generates a Go file with properly typed constants, keeping your API spec and Go code in sync.
Installation
go install github.com/psyb0t/oapixconstgen@latest
Or add as a project tool (Go 1.24+):
go get -tool github.com/psyb0t/oapixconstgen@latest
This adds it to your go.mod under the tool directive, making it a versioned project dependency.
Usage
oapixconstgen -spec=path/to/api.yaml [-out=output/dir] [-pkg=packagename]
Or if installed as a project tool:
go tool oapixconstgen -spec=path/to/api.yaml [-out=output/dir] [-pkg=packagename]
Flags
| Flag | Default | Description |
|---|---|---|
-spec | (required) | Path to the OpenAPI spec file |
-out | . | Output directory for generated file |
-pkg | api | Package name for generated Go file |
Example
Given an OpenAPI spec with x-constants:
openapi: "3.0.0"
x-constants:
int:
defaultPageSize: &defaultPageSize 20
maxPageSize: &maxPageSize 100
uint:
minPasswordLength: &minPasswordLength 8
float64:
requestTimeout: &requestTimeout 30.5
string:
defaultLocale: &defaultLocale "en-US"
bool:
enableCache: &enableCache true
info:
version: 1.0.0
title: My API
paths:
/items:
get:
parameters:
- name: limit
in: query
schema:
type: integer
default: *defaultPageSize
maximum: *maxPageSize
Run the generator:
oapixconstgen -spec=api.yaml -out=./internal/api -pkg=api
This generates internal/api/constants.gen.go:
// Code generated by oapixconstgen. DO NOT EDIT.
package api
const (
DefaultLocale string = "en-US"
DefaultPageSize int = 20
EnableCache bool = true
MaxPageSize int = 100
MinPasswordLength uint = 8
RequestTimeout float64 = 30.5
)
Supported Types
| Type Key | Go Type |
|---|---|
int | int |
int8 | int8 |
int16 | int16 |
int32 | int32 |
int64 | int64 |
uint | uint |
uint8 | uint8 |
uint16 | uint16 |
uint32 | uint32 |
uint64 | uint64 |
float32 | float32 |
float64 | float64 |
string | string |
bool | bool |
Naming Convention
Constant names are converted from snake_case or camelCase to Go exported names:
| OpenAPI Name | Go Constant |
|---|---|
defaultLimit | DefaultLimit |
max_page_size | MaxPageSize |
Use with go:generate
Add a generate directive to automate constant generation:
//go:generate oapixconstgen -spec=../../api/openapi.yaml -out=. -pkg=api
Or if using as a project tool:
//go:generate go tool oapixconstgen -spec=../../api/openapi.yaml -out=. -pkg=api
Then run:
go generate ./...
License
MIT