OpenAPI Codegen has an issue with existing specs (e.g., openapi.yaml) that has local reference to external schema. Let’s start with what we got before.
The configuration below uses local reference, where openapi.yaml references journals.yaml, which references schemas.yaml.
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 defines a post method for the /journals path defined above.
post:
summary: Create a journal
operationId: CreateJournal
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"
Let’s use a config named codegen.yaml for the new tool. This basically specifies the target file where generated Go code will be outputted.
package: api
generate:
echo-server: true
models: true
output: server/codegen/gen.go
When we run oapi-codegen, it says that it does not recognize the references conveniently like how openapi-generator-cli does.
go tool oapi-codegen -config openapi/config/codegen.yaml openapi/openapi.yaml
error generating code: error creating operation definitions: error generating body definitions: error generating request body definition: error turning reference (../components/schemas.yaml#/JournalEntryCreate) into a Go type: unrecognized external reference '../components/schemas.yaml'; please provide the known import for this reference using option --import-mapping
This is because when the tool tries to convert the spec into Go code, it references the referenced schema as objects. This means we need to separate the generation of schemas into models first.
To do that, let’s declare codegen-models.yaml. This outputs the models to a separate package and path. on the other hand, codegen.yaml has this important attribute: import-mapping. This is what the tool was asking for: what package to look for when importing models that are based on schemas.yaml. Other spec files remain the same.
codegen-models.yaml
package: models
generate:
models: true
output: server/codegen/models/gen.go
codegen.yaml
package: api
generate:
echo-server: true
strict-server: true
models: true
output: server/codegen/gen.go
import-mapping:
../components/schemas.yaml: repo/server/codegen/models
To generate the files:
go tool oapi-codegen -config openapi/config/codegen-models.yaml openapi/components/openapi-models.yaml
go tool oapi-codegen -config openapi/config/codegen.yaml openapi/openapi.yaml