Reading this post (see: 3 How to use a single definition when...) about describing a REST API using OpenAPI (Swagger) specification you can note how to keep a single resource representation for adding/updating and getting resource using readOnly property instead of having one representation for getting (GET a collection item) and other one for adding (POST to a collection). For example, in the following User single representation, the id is a read-only property which mean that it won't be sent in the representation when a user is created, it will be there when a user is retrieved.
"User":
{
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64",
"readOnly": true
},
"company_data": {
"type": "object",
"properties": {
.
.
.
},
"readOnly": false
}
}
}
It is really clean and nice to keep the list of resource representation as short as possible so I want to keep the single resource representation approach but the problem I am facing to do that is: how to manage required when a property is mandatory for input only? Suppose I need to set company_data as required when the user is created (POST /users/) but non-required when an user is retrieved (GET /users/{user_id}). There are any way in OpenAPI specification to satisfy this need without lost the single resource representation?
From the Swagger-OpenAPI 2.0 spec,
readonly
is defined as follows:Since the specification says that a read-only property should not be required, there are no defined semantics for what
readonly
+required
should mean.(It might have been reasonable to say that
readonly
+required
means it's required in the response, but still excluded from the request. In fact there is an open issue to make this change, and it looks like it's under consideration for OpenAPI 3.0.)Unfortunately there is no way for a single schema to make properties required in the request, but optional (or disallowed) in the response.
(Again, there's an open issue proposing a "write-only" modifier, possibly under consideration for the next release.)
For now, you would need to create different schemas for these different cases. As described here, you might be able to make these schemas a bit more DRY using
allOf
composition.