Search code examples
swaggeropenapi

OpenAPI: mix of mandatory fields, optional fields and unspecified fields


I need to specify that my endpoint has a mandatory field, an optional field and open to any number of fields(which can be sent without validation).

For e.g. for an endpoint /user

user_id: str, mandatory
timestamp_utc: timestamp, optional
..*accept_any_extra_fields**..

So if someone sends the following json to my endpoint, the endpoint should accept it

{ "user_id": 1,
  "name": "Sam",
  "location": "USA"
}

but it fails if the following json is sent as it does not contain user_id.

{ "name": "Sam",
  "location": "USA"
}

it should fail.

I'm new to OpenAPI/Swagger. I know I can send the extra data. But how do I describe this as documentation on OpenAPI so a person(or a program) knows that they can send any field (e.g. name, location) along with user_id


Solution

  • The additionalProperties keyword allows a schema to have extra properties besides those listed in the properties section.

    MyModel:
      type: object
      required:
        - user_id
      properties:
        user_id:
          type: string
        timestamp_utc:
          type: string
      additionalProperties: true   # OpenAPI 3.x
      # or
      # additionalProperties: {}   # OpenAPI 2.0
    

    Actually OpenAPI schemas are open to extension by default, in the absence of the additionalProperties keyword. However, some tools consider the absence of additionalProperties as "additional properties NOT allowed", so it's best to add additionalProperties: true / additionalProperties: {} explicitly just in case.

    If the extra properties are limited to a specific data type, e.g. string, use

     additionalProperties:
       type: string