oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

`GetSwagger()` fails with: "failed to solve fragment in URI map key not found"

Open luminoso opened this issue 1 year ago • 0 comments

For a given schema:

components:
  schemas:
    SampleSchema:
      properties:
        foo_bar:
          $ref: '#/components/schemas/foo_bar'
    foo_bar:
      properties:
        is_valid:
          type: boolean

with the endpoints:

components:
  schemas:
    ASampleSchemaList:
      $ref: "#/components/schemas/SampleSchema"
    SampleSchema:
      $ref: "sample_schema.yaml#/components/schemas/SampleSchema"
openapi: 3.0.3
paths:
  /failed-endpoint:
    get:
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ASampleSchemaList"
          description: Sample endpoint
info: {title: "", version: ""}

where the oapi-codegen config is defined as:

package: ioapi
generate:
  echo-server: true
  embedded-spec: true
output: ioapi/ioapi-server.gen.go

When generating the server with

go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=server.cfg.yaml endpoints.yaml 

The generated GetSwagger() fails due to swaggerSpec being incorrectly generated, with the error:

failed to resolve "foo_bar" in fragment in URI: "#/components/schemas/foo_bar": map key "foo_bar" not foundexit status 1

Funny enough, if the endpoint schema is renamed from ASampleSchemaList to SomeSampleSchemaList, like so:

components:
  schemas:
    SomeSampleSchemaList:
      $ref: "#/components/schemas/SampleSchema"
    SampleSchema:
      $ref: "sample_schema.yaml#/components/schemas/SampleSchema"
openapi: 3.0.3
paths:
  /failed-endpoint:
    get:
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SomeSampleSchemaList"
          description: Sample endpoint
info: {title: "", version: ""}

The problem fades away.

I've been facing this problem in more ways, not just the schema name, but this is the simplest form I've found.

I have no idea why this happens or why the fix also works.

oapi-codegen v2.4.1 with kin-openapi v0.128.0

I've created a repository with the sample code at: https://github.com/luminoso/oapi-code-gen-fragment-bug

luminoso avatar Oct 15 '24 16:10 luminoso