question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

schema references require a wrapping object

See original GitHub issue

When using referencing schemas to define the request or response body, express-openapi-validator seems to require a wrapping object in order to pass request and response validation.

Given the following spec:

openapi: 3.0.2
servers:
  - url: http://localhost:9000/
info:
  description: Campaign API
  version: 0.0.1
  title: Campaign API
paths:
  /campaign:
    post:
      summary: Create campaign
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateCampaign'
      responses:
        '201':
          description: Campaign successfully created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CampaignResponse'
components:
  schemas:
    CampaignResponse:
      type: object
      required:
        - id
        - name
        - description
        - startDate
        - createdAt
        - updatedAt
      properties:
        id:
          type: integer
        name:
          type: string
        description:
          type: string
        startDate:
          type: string
          format: date-time
        endDate:
          type: string
          format: date-time
        createdAt:
          type: string
          format: date-time
        updateAt:
          type: string
          format: date-time
    CreateCampaign:
      type: object
      required:
        - name
        - description
        - startDate
      properties:
        name:
          type: string
        description:
          type: string
        startDate:
          type: string
          format: date-time
        endDate:
          type: string
          format: date-time

Expected Behavior

I should be able to send a POST with body

{
    "name": "test",
    "description": "description",
    "startDate": "2020-08-25T20:37:33.117Z",
    "endDate": "2020-08-25T20:37:33.117Z"
}

Actual behavior

The spec has a valid schema and does not error out when it is installed. In addition, my swagger docs also believe this to be perfectly valid: image

However, sending the request results in the following error:

Bad Request: request should have required property 'body'
    at Object.POST-/campaign-application/json (.../node_modules/express-openapi-validator/dist/middlewares/openapi.request.validator.js:95:31)
    at RequestValidator.validate (.../node_modules/express-openapi-validator/dist/middlewares/openapi.request.validator.js:52:41)
    at requestValidationHandler (.../node_modules/express-openapi-validator/dist/index.js:162:79)
    at newFn (.../node_modules/express-async-errors/index.js:16:20)
    at Layer.handle [as handle_request] (.../node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (.../node_modules/express/lib/router/index.js:317:13)
    at .../node_modules/express/lib/router/index.js:284:7
    at Function.process_params (.../node_modules/express/lib/router/index.js:335:12)
    at next (.../node_modules/express/lib/router/index.js:275:10)
    at .../node_modules/express-openapi-validator/dist/middlewares/openapi.multipart.js:56:13

Workaround

After playing around, I was able to get satisfy the validator by changing up the spec like so:

schema:
  properties:
    campaign:
      $ref: '#/components/schemas/CreateCampaign'

But then my swagger docs believe that I need to wrap all the data like so: image

And based off of my reading from openapi docs, I believe the first example should be valid.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:7 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
rogerzxucommented, Aug 28, 2020

@cdimascio Thanks for your help!

The bodyParser middleware was indeed the issue. In my case, I had it included in my original code, but had neglected to include it in the sample project. The reason it wasn’t working in my original code was because I had it registered after the openapi spec was installed, but before the route definitions. The code here states:

// 2. Set up body parsers for the request body types you expect
//    Must be specified prior to endpoints in 5.

which I think is inaccurate? I found that the validation wouldn’t work correctly unless the bodyParser is registered before the openapi installation.

I also updated my repo with the fix as well as some misc cleanup changes, please feel free to reference it.

0reactions
cdimasciocommented, Aug 28, 2020

On another note, many other have also decided to use 'swagger-ui-express' alongside express-openapi-validator

Would you mind fixing up your repo and perhaps renaming to something like openapi-swagger-ui-example? If you decide to do so. Also, use either the async/await based install or the v4.0.0-alpha.1 install which uses standard connect middleware.

This repo you created provides a a nice simple, example, of how to use express-openapi-validator with swagger-express-ui. Once cleaned up, I may consider referencing it from the swagger-ui FAQ question in the README.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Schema Wrapping – GraphQL Tools
Schema wrapping works by creating a new "gateway" schema that simply delegates all operations to the original subschema. A series of transforms ...
Read more >
Structuring a complex schema — Understanding JSON ...
Schema documents are not required to have an identifier, but you will need one if you want to reference one schema from another....
Read more >
Wrapping multiple similar mongoose schemas into a single ...
If I change the schema with each new Object, recompile it into a model, and create a new instance of that model, will...
Read more >
Multiple Event Types in the Same Kafka Topic - Revisited
Wrapping a oneof with a JSON object won't work with JSON Schema, since a POJO being serialized to JSON doesn't have the requisite...
Read more >
OpenAPI Specification - Version 3.0.3 - Swagger
See also the Reference Object. Schema. In the following description, if a field is not explicitly REQUIRED or described with a MUST or...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found