Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a $ref property as readOnly in OpenAPI (Swagger)?

I am trying to add a read-only field for 'House' in this example. The house is another model that I want to be read-only.

In this example, the array of Dogs can be set to readOnly without an error, but when I set the single definition of House to readOnly I get the following warning in the Swagger Editor:

Sibling values are not allowed alongside $refs

I understand that this is because everything in the model is inherited here. So how do I define that the write API calls cannot define a 'House' in this endpoint whilst also allowing House to be created and updated in another API endpoints?

Pets:
  properties:
    id:
      type: string
      example: AAAAE12-1123AEF-1122312123
      readOnly: true
    name:
      type: string
      example: My Default Name
    text:
      type: string
      example: My Default Text
  Dogs:
    type: array
    readOnly: true
    items:
      $ref: '#/definitions/Dog'    
  House:
    readOnly: true
    $ref: '#/definitions/House'
like image 894
Mark Hayward Avatar asked Jul 18 '18 12:07

Mark Hayward


People also ask

What is readOnly in swagger?

According to documentation Swagger Doc : readOnly properties are included in responses but not in requests. But this filed in Swagger UI is included in the request body and I can see it in example sections in Swagger UI of POST request. I can send POST request with readonly filed and no exception is thrown.

What is $ref in OpenAPI?

With OpenAPI 3.0, you can reference a definition hosted on any location. It can be the same server, or another one – for example, GitHub, SwaggerHub, and so on. To reference a definition, use the $ref keyword: $ref: 'reference to definition'

Is OpenAPI the same as Swagger?

Although the terms once referred to the same thing, they can no longer be used interchangeably…even though some people still do. In 2021, OpenAPI refers to the industry-standard specification for RESTful API design. Swagger refers to a set of SmartBear tools.


1 Answers

OpenAPI 3.1

In OAS 3.1, schema definitions support sibling keywords alongside $ref:

House:
  $ref: '#/components/schemas/House'
  readOnly: true

OpenAPI 3.0 and 2.0

Sibling keywords alongside $ref are ignored. The workaround is to use allOf to combine a $ref with other attributes:

  House:
    readOnly: true
    allOf:
      - $ref: '#/definitions/House'
like image 136
Helen Avatar answered Sep 27 '22 19:09

Helen