I have an endpoint to create an address and one to update it. Describing this in an OpenAPI spec I'd like to use a component for the address so that I don't have to specify the address twice. Now the problem is, that the address object used for updating should include a property "id", but the one used for creating doesn't.
So basically, I'm looking for a way to describe the full address (incl. the id property) in the components section and then reference to the create endpoint, but excluding the "id" property there.
You can accomplish this using the readOnly keyword, which provides a standardized method to achieve the desired outcome.
You can use the
readOnlyand writeOnly keywords to mark specific properties as read-only or write-only. This is useful, for example, whenGETreturns more properties than used inPOST– you can use the same schema in bothGETandPOSTand mark the extra properties as readOnly.readOnlyproperties are included in responses but not in requests, andwriteOnlyproperties may be sent in requests but not in responses.
example:
type: object
properties:
id:
# Returned by GET, not used in POST/PUT/PATCH
type: integer
readOnly: true
username:
type: string
password:
# Used in POST/PUT/PATCH, not returned by GET
type: string
writeOnly: true
If a
readOnlyorwriteOnlyproperty is included in the required list, required affects just the relevant scope – responses only or requests only. That is, read-only required properties apply to responses only, and write-only required properties – to requests only.
See documentation: documentation
Notice that we use the same model for both the payload and response. However, the id property is excluded from the payload due to its readOnly attribute being set to true.
...
Pet:
required:
- name
- photoUrls
type: object
properties:
id:
type: integer
format: int64
example: 10
readOnly: true
...


You can extend another type using the allOf keyword, as documented here
In the example below, creationType has only a name property, but updateType has all the properties of creationType as well as an id property.
Example:
components:
schemas:
creationType:
type: object
properties:
name:
type: string
updateType:
allOf:
- $ref: '#/components/schemas/creationType'
- type: object
required:
- id
properties:
id:
type: string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With