Reject extra fields in an API request body

Posted on Nov 24, 2020

Intro

How do I reject a request to my API if the body has extra items/fields/data? I spent too much time searching for this answer.

Here’s the answer

Use the additionalProperties: false setting when defining your schema model. Here’s a snippet of an example I used with OpenAPI. It’s not a complete spec but it shows the reference to the schema I’m using.

paths:
  /example:
    patch:
      description: Example
      responses:
        "200":
          description: Request OK
        "400":
          description: Bad request
        "500":
          description: Internal server error
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/Update"
components:
  schemas:
    Update:
      title: UpdateExample
      type: object
      required:
        - last_updated
      additionalProperties: false
      properties:
        example:
          type: string
          description: Example
        last_updated:
          type: string
          example: "2020-10-28"

A body like this will succeed:

{
    "example": "string123",
    "last_updated": "2020-01-20"
}

A body like this will fail with an Invalid request body error:

{
    "example": "string123",
    "last_updated": "2020-01-20",
    "extra_field": "shouldn't be here"
}

Notes

(1) This is described (kind of poorly) by the OpenAPI spec in the Schema object section.

(2) I finally understood this option after reading this GitHub issue comment.

(3) AWS notes in their docs that additionalProperties isn’t supported with REST APIs when you use it in their API Gateway model JSON spec, but that’s how I’m using it and it works fine. It might be because I imported my OpenAPI spec file instead of writing the model in AWS directly?

See ya

If this helped you, let me know! Happy developing.