In OpenAPI, how to make some fields of a referenced schema required?

Viewed 511

I have defined model A which has two fields, field1 is required.

A:
 type: object
 required:
  - field1
 properties:
  field1:
    type: string
  field2:
    type: string

I want to create a new schema B, which has the same fields as A, but both fields are required.

Could I write it like this?

B:
  allOf:
   - $ref: '#/components/schemas/A'
   - type: object
     required:
     - field2

1 Answers

Yes, that's exactly how you do this. Note that you don't need to specify type: object in schema B because the type is already defined in the "parent" schema A.

B:
  allOf:
   - $ref: '#/components/schemas/A'
   - required:
     - field2

required can also be placed alongside allOf instead of as a subschema:

B:
  allOf:
   - $ref: '#/components/schemas/A'
  required:
   - field2

In OpenAPI 3.1, $ref in schemas allow sibling keywords, so the following will work:

B:
  $ref: '#/components/schemas/A'
  required:
   - field2
Related