oapixconstgen
A Go tool that extracts typed constants from OpenAPI specification files and generates Go code.
An OpenAPI spec often repeats the same values: a page size used as a default and a maximum, a password length used as minLength in several schemas. YAML anchors let the spec define each value once. oapixconstgen reads those values from the x-constants extension at the top of the spec and writes them to a Go file as typed constants, so the handlers, validation and tests use the numbers the spec declares instead of copies that drift.
Install
go install github.com/psyb0t/oapixconstgen@latest
Or add it as a versioned tool of your own module (Go 1.24 or newer):
go get -tool github.com/psyb0t/oapixconstgen@latest
That records it under the tool directive of your go.mod, and you run it with go tool oapixconstgen. The module itself declares go 1.26 in its go.mod, so building it needs Go 1.26 or newer.
Quick look
Define the values under x-constants, grouped by Go type, and reference them through anchors:
openapi: "3.0.0"
x-constants:
int:
defaultPageSize: &defaultPageSize 20
maxPageSize: &maxPageSize 100
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
It writes internal/api/constants.gen.go:
// Code generated by oapixconstgen. DO NOT EDIT.
package api
const (
DefaultPageSize int = 20
MaxPageSize int = 100
)
Where to go next
| You want to | Read |
|---|---|
Learn every flag, the exit codes and the log lines, or wire it into go generate | Command line |
Write the x-constants block: type keys, values, names and ordering | The x-constants block |
| Build, lint and test the tool itself, or see how CI and releases run | Development |
The source is on GitHub, and the release history is in the CHANGELOG.