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

Request body with oneOf schema not generated correctly

Open m-kay opened this issue 7 months ago • 1 comments

When using a schema with oneOf in the requestBody the code is not generated accoring to the documentation.

Version v2.4.1

openapi.yaml

openapi: 3.0.1
info:
  title: openapi test
  version: v0.0.1

paths:
  /change:
    post:
      operationId: change
      requestBody:
        description: the request
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - $ref: '#/components/schemas/NameChange'
                - $ref: '#/components/schemas/AddressChange'
              discriminator:
                propertyName: changeType
                mapping:
                  name: '#/components/schemas/NameChange'
                  address: '#/components/schemas/AddressChange'
      responses:
        200:
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  response:
                    type: object
                    description: Object containing the response.
                    properties:
                      changeType:
                        type: string
                        description: the type of change made

components:
  schemas:
    Change:
      type: object
      required:
        - changeType
      properties:
        changeType:
          type: string
    NameChange:
      allOf:
        - $ref: '#/components/schemas/Change'
        - type: object
          required:
            - newName
          properties:
            newName:
              type: string
    AddressChange:
      allOf:
        - $ref: '#/components/schemas/Change'
        - type: object
          required:
            - newAddress
          properties:
            newAddress:
              type: string

Expected According to the documentation there should be helper methods generated like the following:

func (t *ChangeJSONRequestBody) FromNameChange(v NameChange) error {
	b, err := json.Marshal(v)
	t.union = b
	return err
}

Actual The types are generated but without helper methods as you can see in this example

m-kay avatar Jul 10 '25 08:07 m-kay

I found that if I move the inline oneOf definition into a named schema under components/schemas and then reference it from the requestBody, the expected helper methods (like FromNameChange) are generated correctly.

YukiMichishita avatar Sep 09 '25 08:09 YukiMichishita