oapixconstgen

July 27, 2026 ยท View on GitHub

CI coverage version license

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

FlagDefaultDescription
-spec(required)Path to the OpenAPI spec file
-out.Output directory for generated file
-pkgapiPackage 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 KeyGo Type
intint
int8int8
int16int16
int32int32
int64int64
uintuint
uint8uint8
uint16uint16
uint32uint32
uint64uint64
float32float32
float64float64
stringstring
boolbool

Naming Convention

Constant names are converted from snake_case or camelCase to Go exported names:

OpenAPI NameGo Constant
defaultLimitDefaultLimit
max_page_sizeMaxPageSize

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