Import mapping and inline reference are not suitable when the spec grows and requires schemas defined in separate files. Overtime, the spec will become crowded. The final solution for this situation is bundling, which is the process of combining the specs and the schemas it references into a single file. That single file is then used in oapi-codegen
Let’s start with the parent spec and the other referenced files.
openapi.yaml
openapi: 3.0.3
info:
title: Journal API
version: 0.1.0
servers:
- url: http://localhost:8080
paths:
/journals:
$ref: "./paths/journals.yaml"
journals.yaml
post:
summary: Create a journal
operationId: CreateJournal
tags:
- Journal
requestBody:
required: true
content:
application/json:
schema:
$ref: "../components/schemas.yaml#/JournalEntryCreate"
responses:
"201":
description: Created
content:
application/json:
schema:
$ref: "../components/schemas.yaml#/JournalEntry"
codegen.yaml
package: api
generate:
echo-server: true
strict-server: true
models: true
output: server/codegen/gen.go
Run redocly (without installing it): npx @redocly/cli@latest bundle openapi/openapi.yaml -o openapi/_bundled/openapi.yaml
This command creates a bundle under _bundled folder using the parent spec openapi.yaml and generates another spec, the bundled version.
Then we feed the bundled version to codegen tool: go tool oapi-codegen -config openapi/config/codegen.yaml openapi/_bundled/openapi.yaml
Just like before, oapi-codegen generates gen.go