open-api icon indicating copy to clipboard operation
open-api copied to clipboard

Add `Accept` header validator feature

Open medfreeman opened this issue 6 years ago • 1 comments

This is a proposition to add Accept header validation, useful for content negotiation. Using the internal frameworks Accept header validation functions (ctx.accepts in koa and req.accepts in express). It will be expressed as a middleware, that'll first validate that the requested Accept header has at least one type that corresponds to a route's declared response types for all status codes, then assign an object having all declared statusCode from schema as keys and all declared schema content types in weighted order (according to Accept header's type order / q values) to ctx.state.responseContentTypes. Which can then be used to send the appropriate content-type header and content in application logic, depending on the response status code.

As said previously, it's really useful in a content negotation context, where i personally plan to have clients requesting different content types based on usage scenarios.

Furthermore, it can be later easily expanded / duplicated to support the other accept headers, Accept-encoding, Accept-charset and Accept-language.

I have a PR implementing the feature in complete conformance to this repo / libraries style, hat's just missing the express part, and that just needs updating for the latest versions of this libraries (currently targeting koa-openapi 3.13.0).

Let me know if you'd be interested on adding this feature.

OpenAPI reference (example requesting json:api and allowing to send back either json:api or jwt responses).

/devices:
    get:
      tags:
        - devices
      summary: Get all devices
      description: Get a list of all devices.
      parameters:
        - name: accept
          in: header
          required: true
          description: The HTTP `accept` header
          schema:
            type: string
            enum:
              - application/vnd.api+json
              - application/jwt
      requestBody:
        content:
          application/vnd.api+json:
            schema:
              $ref: '#/components/schemas/devicesCollectionRequest'
      responses:
        '200':
          description: successful operation
          content:
            application/vnd.api+json:
              schema:
                $ref: '#/components/schemas/devicesCollectionResponse'
            application/jwt:
              schema:
                type: string

medfreeman avatar Sep 18 '19 23:09 medfreeman

Please submit a pr

jsdevel avatar Sep 19 '19 03:09 jsdevel