ogen is a free, open source api development & testing project written in Go and released under Apache-2.0. It has 2,139 GitHub stars, 185 forks and 133 open issues, and was last pushed 4 days ago. On this registry it ranks #102 of 178 tracked projects in API Development & Testing, with 5 head-to-head comparisons available.

What is ogen?

ogen is an Apache-2.0-licensed OpenAPI v3 code generator for Go that converts an OpenAPI v3 specification into statically typed Go server interfaces and client code, aimed at Go teams who would rather generate their HTTP API layer from a spec than hand-write it.

What it is

ogen lives in the Go ecosystem and reads an OpenAPI v3 document, then writes Go structures, a server interface, and a client from that document. The generated code covers the parts of an HTTP API that are otherwise repeated by hand: request parsing, argument, header and URL query decoding into structures, validation, routing, and JSON encoding. Only the spec is the source of truth; the boilerplate that normally sits between the spec and the handlers is produced by the generator.

The concrete problem it solves is drift and labour in that boilerplate layer. Validation is code-generated according to the specification instead of being written and kept in sync manually, routing is a code-generated static radix router, and the JSON encoding is code-generated and optimized using go-faster/jx to work around encoding/json limitations. There is no reflection and no interface{} in the generated path, so a team keeps a statically typed client and server that both follow the same schema.

Key capabilities

  • The ogen command generates into a directory with flags such as --target target/dir, -package api, and --clean, and can be wired in as //go:generate go run github.com/ogen-go/ogen/cmd/ogen ... schema.json.
  • No reflection or interface{}; generated structures come directly from the OpenAPI v3 specification, including examples such as Pet with fields typed time.Time, net.IP, url.URL, uuid.UUID, and time.Duration.
  • Validation is code-generated from the spec, and routing uses a code-generated static radix router.
  • String formats uuid, date, date-time, and uri are represented by Go types directly rather than plain strings.
  • Optional, nullable, and optional-nullable fields are handled with generated Optional[T], Nullable[T], and OptionalNullable[T] wrappers, with documented nil semantics for arrays.
  • oneOf schemas produce generated sum types, using a discriminator field when defined and otherwise inferring the variant by unique fields, field types, or enum values.
  • OpenTelemetry tracing and metrics, Server-Sent Events support, and untyped parameters represented as Go any are available.

Who uses it and how

  • Go services that already maintain an OpenAPI v3 document and want the server interface and the client generated from that single document.
  • Teams that run generation inside the normal build through a //go:generate directive pointing at github.com/ogen-go/ogen/cmd/ogen.
  • Container-based or CI pipelines that run ghcr.io/ogen-go/ogen:latest with the repository mounted at /workspace and generate into a path under that volume.
  • Services that need Server-Sent Events or OpenTelemetry tracing and metrics in the generated layer.
  • New adopters can follow the sample project at github.com/ogen-go/example and the documentation at ogen.dev, with a Telegram group at @ogen_dev.

Getting started

Install the generator with go install -v github.com/ogen-go/ogen/cmd/ogen@latest, or skip the local toolchain and run the container image ghcr.io/ogen-go/ogen:latest with the working directory mounted at /workspace.

How it compares

The registry entry does not list paid products that ogen replaces, so no licence or cost comparison against commercial offerings is possible here. Its topic list places it alongside other OpenAPI tooling such as openapi-generator and swagger, which is the category it competes in, but the entry records no head-to-head comparison against those projects.

When to use it — and when not to

ogen is a generator, not a runtime, so a self-hoster mainly needs a Go toolchain and an OpenAPI v3 document; there is no database, storage, or SMTP component to operate. Teams that are not on OpenAPI v3, or that are not writing Go, should look elsewhere. Two limitations are visible in the facts: oneOf handling for fields that are both nullable and required is still marked as a TODO, and the project carries 133 open issues, so adopters should expect an actively changing generator.

project readme (upstream, from github) — read inline

ogen Go Reference codecov stable

OpenAPI v3 Code Generator for Go.

Install

go install -v github.com/ogen-go/ogen/cmd/ogen@latest

Usage

//go:generate go run github.com/ogen-go/ogen/cmd/ogen --target target/dir -package api --clean schema.json

or using container:

docker run --rm \
  --volume ".:/workspace" \
  ghcr.io/ogen-go/ogen:latest --target workspace/petstore --clean workspace/petstore.yml

Features

  • No reflection or interface{}
    • The json encoding is code-generated, optimized and uses go-faster/jx for speed and overcoming encoding/json limitations
    • Validation is code-generated according to spec
  • Code-generated static radix router
  • No more boilerplate
    • Structures are generated from OpenAPI v3 specification
    • Arguments, headers, url queries are parsed according to specification into structures
    • String formats like uuid, date, date-time, uri are represented by go types directly
  • Statically typed client and server
  • Convenient support for optional, nullable and optional nullable fields
    • No more pointers
    • Generated Optional[T], Nullable[T] or OptionalNullable[T] wrappers with helpers
    • Special case for array handling with nil semantics relevant to specification
      • When array is optional, nil denotes absence of value
      • When nullable, nil denotes that value is nil
      • When required, nil currently the same as [], but is actually invalid
      • If both nullable and required, wrapper will be generated (TODO)
  • Support for untyped parameters (any)
    • Parameters with no type specified in schema are represented as Go any
    • Decoded as strings from URI (path, query, header, cookie)
    • Client encoding uses fmt.Sprint for flexible value conversion
    • Useful for legacy APIs or dynamic parameter types
  • Generated sum types for oneOf
    • Primitive types (string, number) are detected by type
    • Discriminator field is used if defined in schema
    • Type is inferred by unique fields if possible
      • Field name discrimination: variants with different field names
      • Field type discrimination: variants with same field names but different types (e.g., {id: string} vs {id: integer})
      • Field value discrimination: variants with same field names and types but different enum values
  • Extra Go struct field tags in the generated types
  • OpenTelemetry tracing and metrics
  • Server-Sent Events (SSE) support

Example generated structure from schema:

// Pet describes #/components/schemas/Pet.
type Pet struct {
	Birthday     time.Time     `json:"birthday"`
	Friends      []Pet         `json:"friends"`
	ID           int64         `json:"id"`
	IP           net.IP        `json:"ip"`
	IPV4         net.IP        `json:"ip_v4"`
	IPV6         net.IP        `json:"ip_v6"`
	Kind         PetKind       `json:"kind"`
	Name         string        `json:"name"`
	Next         OptData       `json:"next"`
	Nickname     NilString     `json:"nickname"`
	NullStr      OptNilString  `json:"nullStr"`
	Rate         time.Duration `json:"rate"`
	Tag          OptUUID       `json:"tag"`
	TestArray1   [][]string    `json:"testArray1"`
	TestDate     OptTime       `json:"testDate"`
	TestDateTime OptTime       `json:"testDateTime"`
	TestDuration OptDuration   `json:"testDuration"`
	TestFloat1   OptFloat64    `json:"testFloat1"`
	TestInteger1 OptInt        `json:"testInteger1"`
	TestTime     OptTime       `json:"testTime"`
	Type         OptPetType    `json:"type"`
	URI          url.URL       `json:"uri"`
	UniqueID     uuid.UUID     `json:"unique_id"`
}

Example generated server interface:

// Server handles operations described by OpenAPI v3 specification.
type Server interface {
	PetGetByName(ctx context.Context, params PetGetByNameParams) (Pet, error)
	// ...
}

Example generated client method signature:

type PetGetByNameParams struct {
    Name string
}

// GET /pet/{name}
func (c *Client) PetGetByName(ctx context.Context, params PetGetByNameParams) (res Pet, err error)

Generics

Instead of using pointers, ogen generates generic wrappers.

For example, OptNilString is string that is optional (no value) and can be null.

// OptNilString is optional nullable string.
type OptNilString struct {
	Value string
	Set   bool
	Null  bool
}

Multiple convenience helper methods and functions are generated, some of them:

func (OptNilString) Get() (v string, ok bool)
func (OptNilString) IsNull() bool
func (OptNilString) IsSet() bool
func (OptNilString) IsEmpty() bool

func NewOptNilString(v string) OptNilString

Recursive types

If ogen encounters recursive types that can't be expressed in go, pointers are used as fallback.

Sum types

For oneOf sum-types are generated. ID that is one of [string, integer] will be represented like that:

type ID struct {
	Type   IDType
	String string
	Int    int
}

// Also, some helpers:
func NewStringID(v string) ID
func NewIntID(v int) ID

Discriminator Inference

ogen automatically infers how to discriminate between oneOf variants using several strategies:

1. Type-based discrimination (for primitive types)

Variants with different JSON types are discriminated by checking the JSON type at runtime:

{
  "oneOf": [
    {"type": "string"},
    {"type": "integer"}
  ]
}

2. Explicit discriminator (when discriminator field is specified)

When a discriminator field is defined in the schema, ogen uses it directly:

{
  "oneOf": [...],
  "discriminator": {
    "propertyName": "type",
    "mapping": {"user": "#/components/schemas/User", ...}
  }
}

3. Field-based discrimination (automatic inference from unique fields)

ogen analyzes the fields in each variant to find discriminating characteristics:

  • Field name discrimination: Variants have different field names
{
  "oneOf": [
    {"type": "object", "required": ["userId"], "properties": {"userId": {"type": "string"}}},
    {"type": "object", "required": ["orderId"], "properties": {"orderId": {"type": "string"}}}
  ]
}
  • Field type discrimination: Variants have fields with the same name but different types
{
  "oneOf": [
    {
      "type": "object",
      "required": ["id", "value"],
      "properties": {
        "id": {"type": "string"},
        "value": {"type": "string"}
      }
    },
    {
      "type": "object",
      "required": ["id", "value"],
      "properties": {
        "id": {"type": "integer"},
        "value": {"type": "number"}
      }
    }
  ]
}

In this case, ogen checks the JSON type of the id field at runtime to determine which variant to decode.

  • Field value discrimination: Variants have fields with the same name and type but different enum values
{
  "oneOf": [
    {
      "type": "object",
      "required": ["status"],
      "properties": {
        "status": {"type": "string", "enum": ["active", "pending"]}
      }
    },
    {
      "type": "object",
      "required": ["status"],
      "properties": {
        "status": {"type": "string", "enum": ["inactive", "deleted"]}
      }
    }
  ]
}

In this case, ogen checks the actual string value of the status field at runtime and matches it against each variant's enum values. The enum values must be disjoint (non-overlapping) for this to work. If enum values overlap, ogen will report an error and suggest using an explicit discriminator.

Const values

ogen supports the JSON Schema const keyword, which specifies that a field must have a fixed value (introduced in JSON Schema draft 6 and supported in OpenAPI 3.0+). When a field has a const value, it is encoded directly in the generated JSON encoder without requiring the struct field to be set.

Example schema with const values

components:
  schemas:
    ErrorResponse:
      type: object
      properties:
        code:
          type: integer
          const: 400
        status:
          type: string
          const: "error"
        message:
          type: string

Generated code

The generated struct includes the field, but the encoder har

readme truncated — read the full docs on github

Frequently asked questions

Is ogen free to use?

ogen is open source under the Apache-2.0 licence. There is no licence fee and no seat count — you can self-host it or, where the project offers one, pay a vendor for a managed version instead.

What does ogen do?

OpenAPI v3 code generator for go

What is ogen written in?

ogen is primarily written in Go. Its source is publicly available at https://github.com/ogen-go/ogen, and it has 2,139 GitHub stars.