This question relates to Open API spec 3 and writing API specifications.
I have been trying to work out how to set fields as required for a specific method requestBody when I am using a "oneOf" in a schema object.
I know how to set required fields of a referenced object, but when you try set the required properties of oneOf objects the same way, it does not work.
I also know that I can set the required fields in the schema object itself, however I do not want to do this as the required fields differ on each method (i.e all fields required for a post, but only some required for a patch).
So essentially, how do I set the required fields in a request body of a schema used in oneOf?
I have created an example below, in it, I want to:
Set the fields Bird - wingSpan and beakLength as required in the Post method
Set the fields Cat - tailLength as required in the Post method
Not have any required fields for Bird and Cat in the Patch method.
openapi: 3.0.3
servers:
- description: SwaggerHub API Auto Mocking
url: https://virtserver.swaggerhub.com/Enable-Networks/TroubleTicket/1.0.0
info:
title: Pet API
version: 1.0.0
paths:
/pet:
patch:
summary: Update a pet
requestBody:
required: true
content:
application/json:
schema:
allOf:
- $ref: "#/components/schemas/Pet"
- type: object
required:
- age
responses:
"204":
description: The request was a success and the pet was successfully created.
post:
summary: Create a pet
requestBody:
required: true
content:
application/json:
schema:
allOf:
- $ref: "#/components/schemas/Pet"
- type: object
required:
- name
- age
- species
properties:
species:
type: object
required:
- ???
responses:
"204":
description: The request was a success and the pet was successfully created.
components:
schemas:
Cat:
type: object
properties:
tailLength:
type: integer
whiskerLength:
type: integer
Bird:
type: object
properties:
wingSpan:
type: integer
beakLength:
type: integer
highestAltitude:
type: integer
Pet:
type: object
properties:
name:
type: string
age:
type: string
species:
oneOf:
- $ref: '#/components/schemas/Cat'
- $ref: '#/components/schemas/Bird'
Any help on this would be appreciated!
I have read the documentation 10x, tried everything from discriminators to not using refs.
I have tried many different combinations of the below and still nothing works.
requestBody:
required: true
content:
application/json:
schema:
allOf:
- $ref: "#/components/schemas/Pet"
- type: object
required:
- name
- age
- species
properties:
species:
type: object
required:
- ???
I am learning OpenAPI recently, and would like to know the best practices.
Let's say I have a resource called Person, and it is defined in components/schemas as follows:
Person:
type: object
required:
- id
- name
- age
properties:
id:
readOnly: true
type: integer
name:
type: string
age:
type: integer
I've made id readOnly because when I do post or patch, the ID will be passed as part of the URL. See https://swagger.io/docs/specification/data-models/data-types/
name and age must present when the client tries to create a new person using post method, or get a person, therefore they are defined as required.
My question is about patch: what if I only want to update a person's age or name independently? Ideally I would like to do something like
PATCH /person/1
{"age": 40}
However, since I've defined name as required, I can't do it. I can think of several solutions, but they all have flaws:
Remove the required restriction. But if I do that, I lose the validation on post and get.
Use a separate schema for patch, e.g. PersonUpdate, with required removed. Apparently that leads to redundancy.
When I do patch, I do pass all the fields, but for the ones I don't want to update, I pass an invalid value, e.g.
PATCH /Person/1
{"age": 40, "name": null}
And make all the fields nullable, and let the server ignore these values. But what if I do want to set name to null in DB?
I use PUT for update, and always pass all the required fields. But what if my data is outdated? E.g. when I do
PUT /Person/1
{"age": 40, "name": "Old Name"}
Some other client has already changed name to "New Name", and I am overriding it.
Like method 3, but I pass additional fields when doing patch to indicate the fields the server should care, whether using query parameters like ?fields=age, or add it to the JSON body. So I can change the requestBody to something like
requestBody:
content:
application/json:
schema:
allOf:
- $ref: '#/components/schemas/Person'
- type: object
properties:
_fields:
type: array
items:
type: string
Then I can do this
PATCH /Person/1
{"age": 40, "name": null, _fields: ["age"]}
In this way, I can update name to null as well
PATCH /Person/1
{"age": 40, "name": null, _fields: ["age", "name"]}
This method seems can work, but is there a better or widely accepted practice?
I came up with the following solution:
Person:
type: object
allOf:
- $ref: '#/components/schemas/PersonProperties'
- required:
- id
- name
- age
UpdatePerson:
type: object
allOf:
- $ref: '#/components/schemas/PersonProperties'
PersonProperties:
type: object
properties:
id:
readOnly: true
type: integer
name:
type: string
age:
type: integer
PersonProperties acts as a simple collection of properties which make up a the person model. It doesn't specify any required fields.
Person re-uses all properties of PersonProperties and, in addition, specifies which one are required. PersonUpdate re-uses all properties of PersonProperties and allows for partial updates.
This solution still feels hacky. Also, it doesn't work for partial updates of nested objects and nullable properties.
(In fact, since the id is readOnly, you could also add required: [id] on PersonProperties and remove id from the required list on Person)
By splitting the schemas up into multiple, composable schemas, we can layer the schemas on top of one another without repeating ourselves. We can even support removal of properties via PATCH by making optional properties nullable.
Example OpenAPI definition allowing partial updates via PATCH endpoints (validated):
openapi: 3.0.0
info:
title: Sample API with reusable schemas and partial updates (PATCH)
version: 1.0.0
paths:
/customers:
post:
tags:
- Customer
requestBody:
$ref: '#/components/requestBodies/CreateCustomer'
responses:
201:
description: Created
content:
application/json:
schema:
$ref: '#/components/schemas/CustomerId'
get:
tags:
- Customer
responses:
200:
description: OK
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Customer'
/customers/{CustomerId}:
get:
tags:
- Customer
parameters:
- $ref: '#/components/parameters/CustomerId'
responses:
200:
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/Customer'
put:
tags:
- Customer
requestBody:
$ref: '#/components/requestBodies/CreateCustomer'
parameters:
- $ref: '#/components/parameters/CustomerId'
responses:
204:
description: Updated
patch:
tags:
- Customer
requestBody:
description: Update customer with properties to be changed
content:
application/json:
schema:
allOf:
- $ref: '#/components/schemas/CustomerProperties'
- type: object
properties:
Segment:
nullable: true
parameters:
- $ref: '#/components/parameters/CustomerId'
responses:
204:
description: Updated
components:
schemas:
CustomerProperties:
type: object
properties:
FirstName:
type: string
LastName:
type: string
DOB:
type: string
format: date-time
Segment:
type: string
enum:
- Young
- MiddleAged
- Old
- Moribund
CustomerRequiredProperties:
type: object
required:
- FirstName
- LastName
- DOB
Id:
type: integer
CustomerId:
type: object
properties:
Id:
$ref: '#/components/schemas/Id'
Customer:
allOf:
- $ref: '#/components/schemas/CustomerId'
- $ref: '#/components/schemas/CustomerProperties'
- $ref: '#/components/schemas/CustomerRequiredProperties'
parameters:
CustomerId:
name: CustomerId
in: path
required: true
schema:
$ref: '#/components/schemas/Id'
requestBodies:
CreateCustomer:
description: Create a new customer
content:
application/json:
schema:
allOf:
- $ref: '#/components/schemas/CustomerProperties'
- $ref: '#/components/schemas/CustomerRequiredProperties'
Adapted from: https://stoplight.io/blog/reuse-openapi-descriptions/
It's weird to talk about the OpenAPI / Json schema structure because it tells you something about what you are sending, but not about the meaning of the properties.
To do what you want, you need to come up with a format with a set of rules that can make these kind of modifications.
One (more complex) example is JSON Patch.
Once you figured out what your rules around patching JSON is going to be, that's when a good time might be to define specific cases for this (like the case for Person).
I understand that a POST method in openapi 3.0.2 is supposed to create a new entity, and return the id of that entity. When I add an additional route to GET or DELETE that entity by ID, I get a 404 error. I don't quite know why that might be.
Here are my post and get methods:
/api/globalorderdays:
post:
tags:
- Setup Global Order Days
summary: Allows user to add order days and holidays to multiple
sessions.
requestBody:
required: true
description: put text here
content:
application/json:
schema:
$ref: '#/components/schemas/GlobalOrderSetupInfo'
responses:
201:
description: Created
400:
description: Bad request
401:
description: Unauthorized
/api/globalorderdays/{Id}:
get:
tags:
- Setup Global Order Days
summary: put text here
parameters:
- in: path
name: Id
required: true
description: put text here
schema:
type: integer
example:
responses:
200:
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/GlobalOrderSetupInfo'
400:
description: Bad request
401:
description: Unauthorized
/api/globalorderdays/{Id}:
delete:
tags:
- Setup Global Order Days
summary: Allows user to delete added order days
parameters:
- in: path
name: Id
required: true
description: put text here
schema:
type: integer
example:
responses:
204:
description: Deleted
400:
description: Bad request
401:
description: Unauthorized
Here are the components:
GlobalOrderSetupInfo:
description: 'Put Text Here'
type: object
properties:
Id:
type: integer
nullable: true
AvailableHolidayList:
type: string
nullable: true
SelectedOrderHolidays:
type: string
nullable: true
SelectedHolidays:
type: string
nullable: true
OrderDays:
type: string
nullable: true
NoOrderDays:
type: string
nullable: true
AllSessionList:
uniqueItems: false
type: array
items:
$ref: '#/components/schemas/SessionInfoList'
SessionIdString:
type: string
nullable: true
SessionInfoList:
description: 'Put Text Here'
type: object
properties:
Id:
type: integer
nullable: true
SessionID:
type: integer
nullable: true
Name:
type: string
nullable: true
Type:
type: string
GroupName:
type: string
IsChecked:
type: boolean
default: false
SetupID:
type: string
nullable: true
I expect to be able to retrieve/delete the entity by Id, but I return 404 errors
There are several issues with your spec.
The /api/globalorderdays/{Id} path is repeated several times. This is not valid.
# Incorrect
/api/globalorderdays/{Id}:
get:
...
/api/globalorderdays/{Id}:
delete:
...
Instead, specify the path once and list all of its HTTP methods below it, like so:
/api/globalorderdays/{Id}:
get:
...
delete:
...
Parameter examples are missing the value:
schema:
type: integer
example: # <-----
A missing value in YAML is an equivalent of null, but null is not a valid example for an integer schema. Either add a proper integer example, such as example: 1, or remove the example keyword from those schemas.
Once these issues are fixed, the mocks for GET and DELETE will work properly.
I'm building a REST service with JAX-RS, Microprofile and Payara 5. My method returns an object of type Response. The response itself contains a List of MyClass. The implementation looks like this:
import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
import org.eclipse.microprofile.openapi.annotations.media.Content;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
#GET
#Path("/{a}/{b}/{c}")
#APIResponse(content = #Content(schema = #Schema(type = SchemaType.ARRAY, implementation = MyClass.class)))
public Response getMyClass(#PathParam("a") String a,
#PathParam("b") String b,
#PathParam("c") String c) {
return Response
.ok()
.entity(new ArrayList<>())
.build();
}
The generated OpenAPI definition looks like this:
/api/translations/{a}/{b}/{c}:
get:
operationId: getMyClass
parameters:
- name: a
in: path
required: true
style: simple
schema:
type: string
- [...]
responses:
default:
description: Default Response.
content:
'*/*':
schema:
type: array
items: {}
As you can see, the definition of MyClass.class is missing in the response type. How can I add that type to the definition? Is the #ApiResponse annotation the correct way to achieve this?
I tested this today with the newest payara 5.191 and it did not worked for me too.
It seems that there is a bug in the current payara implementation, because I checked the example on this page guide-microprofile-openapi
The same implementation has 2 different openapi generations (Payara and OpenLiberty)
Payara:
openapi: 3.0.0
info:
title: Deployed Resources
version: 1.0.0
servers:
- url: https://10.0.0.72:8080/ipma
description: Default Server.
paths:
/resources/server:
get:
summary: List servers.
description: 'Returns all servers '
operationId: getServers
responses:
default:
description: Special description
content:
application/json:
schema:
type: array
/resources/server/{id}:
get:
summary: get server by id.
description: 'return one server with the specified id'
operationId: getServerById
parameters:
- name: id
in: query
style: simple
schema:
type: number
responses:
default:
description: Special description
content:
application/json:
schema:
$ref: '#/components/schemas/Server'
components:
schemas:
Server:
properties:
name:
type: string
example: test
id:
type: number
example: "0"
description: foo
OpenLiberty:
openapi: 3.0.0
info:
title: Deployed APIs
version: 1.0.0
servers:
- url: http://localhost:9080
paths:
/resources/server/{id}:
get:
summary: get server by id.
description: 'return one server with the specified id'
operationId: getServerById
parameters:
- name: id
in: query
schema:
type: integer
format: int64
responses:
default:
description: Special description
content:
application/json:
schema:
$ref: '#/components/schemas/Server'
/resources/server:
get:
summary: List servers.
description: 'Returns all servers '
operationId: getServers
responses:
default:
description: Special description
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Server'
components:
schemas:
Server:
required:
- id
- name
type: object
properties:
id:
type: integer
format: int64
example: 0
name:
type: string
example: test
description: foo
I'm defining a resource that you POST to with a non-JSON body. It's just a string like form parameters. Something like what happens with OAuth:
grant_type=&code=&redirect_uri=
How can I document that on Swagger? Do I have to use formParam format instead of body? Everything I put into body it converts to JSON examples.
TokenRequest:
properties:
grant_type:
type: string
description: OAuth Grant Type
enum:
- authorization_code
- refresh
code:
type: string
description: Authorization Code obtained from /authorize required if grant_type = au
redirect_uri:
type: string
description: Defined Redirect URI Example - https://example.com/callback
refresh_token:
type: string
description: Required if grant_type = refresh
Here is an example on how to document the form data:
post:
tags:
- pet
summary: Updates a pet in the store with form data
description: ''
operationId: updatePetWithForm
consumes:
- application/x-www-form-urlencoded
produces:
- application/xml
- application/json
parameters:
- name: petId
in: path
description: ID of pet that needs to be updated
required: true
type: integer
format: int64
- name: name
in: formData
description: Updated name of the pet
required: false
type: string
- name: status
in: formData
description: Updated status of the pet
required: false
type: string
responses:
'405':
description: Invalid input
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
But in your case, it seems you want to define OAuth setting so please refer to Swagger Spec 2.0 for more information. Here is an example for PetStore:
securityDefinitions:
petstore_auth:
type: oauth2
authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog'
flow: implicit
scopes:
'write:pets': modify pets in your account
'read:pets': read your pets
api_key:
type: apiKey
name: api_key
in: header