Skip to content

Repository files navigation

openapi-codegen-example

Demonstrate how to use openapi-codegen to generate separate model vs server packages.

Requires Go 1.24+

Commands

go get -tool github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@latest
go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@latest --config=openapi_gen_model.yaml  openapi_spec_components.yaml
go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@latest --config=openapi_gen_server.yaml openapi_spec_paths.yaml

Problem

Below are excerpts from the generated openapi_gen_server.go file. There is a mix of externalRef0 and ExternalRef0 qualifiers; only the lowercase one works.

Import

externalRef0 "oapi-codegen-example/internal/openapi/model"

Correct

type GetUser200JSONResponse []externalRef0.User
type PostUser200JSONResponse externalRef0.User

Incorrect

type GetUser400JSONResponse struct{ ExternalRef0.HTTP400 }
type PostUser400JSONResponse struct{ ExternalRef0.HTTP400 }

Thoughts

oapi-codegen seems to handle external references differently for the API responses in openapi_spec_paths.yaml.

HTTP 200 responses for both APIs are OK. HTTP error responses for both APIs don't compile.

responses:
'200':
description: User created successfully.
content:
application/json:
schema:
$ref: './openapi_spec_components.yaml#/components/schemas/User'
'400':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP400'
'401':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP401'
'403':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP403'
'404':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP404'
'429':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP429'
'500':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP500'
'503':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP503'
'504':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP504'
responses:
'200':
description: A JSON array of 0 or more Users.
content:
application/json:
schema:
type: array
items:
$ref: './openapi_spec_components.yaml#/components/schemas/User'
'400':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP400'
'401':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP401'
'403':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP403'
'404':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP404'
'429':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP429'
'500':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP500'
'503':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP503'
'504':
$ref: './openapi_spec_components.yaml#/components/responses/HTTP504'

About

Demonstrate how to use openapi-codegen to generate separate model vs server packages.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors