Search code examples
node.jsexpressopenapiopenapi-generatorajv

openapi-generator codegen: Ajv cannot resolve reference to requestBodies from openapi 3.0.0


I created a server stub using my own openapi-3.0.0 template from openapi-generator. While implementing the API logic for creating resource, I'm referencing a component declared under requestBodies as follows

components:
  requestBodies:
    SamyojyaUser:
      content:
        application/json:
          schema:
           $ref: '#/components/schemas/SamyojyaUser'
        application/xml:
          schema:
           $ref: '#/components/schemas/SamyojyaUser'
    description: Samyojya User object that needs to be added to the system
    required: true

The API is declared as follows

paths:
  /samyojya-user:
    post:
      operationId: addSamyojyaUser
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/requestBodies/SamyojyaUser'
              x-content-type: application/json

However, while processing the request Ajv complains saying

can't resolve reference #/components/requestBodies/SamyojyaUser from id #

Looking like there seems to be some issue with registering requestBodies component. I see the other components showing up in the Ajv when I debug. I am tempted to use the user component directly at the path object but I want to customize the request body further. Any thoughts on tweaking it further?


Solution

  • References to #/components/requestBodies/... can only be used directly under requestBody and not under schema:

    paths:
      /samyojya-user:
        post:
          operationId: addSamyojyaUser
          requestBody:
            $ref: '#/components/requestBodies/SamyojyaUser'
    

    Also, the indentation in the request body component in wrong - the description and required: true must be on the same level as content.

    components:
      requestBodies:
        SamyojyaUser:
          content:
            application/json:
              schema:
               $ref: '#/components/schemas/SamyojyaUser'
            application/xml:
              schema:
               $ref: '#/components/schemas/SamyojyaUser'
    
          # vvvv  Note the indentation level
          description: Samyojya User object that needs to be added to the system
          required: true
    

    Use https://editor.swagger.io (or other validators) to validate your OpenAPI definitions before generating code.