SolvedOpenAPI Specification Defining constant value in response

In order to specify that the response for an API call is always a certain given value, I would like to create this this feature request.

If the client wants to get the details of a non-existing pet of a pet store then the server should say

{
    "status": "ERROR",
    "error_message": "ERROR__PET_NOT_FOUND"
}

The best way I found for describing this is to use enums with only one element, like this:

    schema:
        type: object
        properties:
            result: 
                type: string
                enum: [ERROR]
            error_code: 
                type: string
                enum: [ERROR__PET_NOT_FOUND]

Instead of this, an exact value should be defined with an implicit type detection. So,

    schema:
        type: object
        properties:
            result: 
                value: "ERROR"
            error_code: 
                value: "ERROR__PET_NOT_FOUND"

should mean the same as the previous declaration.
The following scalar types should be auto-detected:

  • type = string, if the value is surrounded by " symbols
  • type = integer, if the value contains only digits and sign
  • type = float, if the value contains digits, sign AND decimal point

Moreover, the new value declaration should work one level above as well:

    schema:
        type: object
        properties:
            value: 
                result: "ERROR"
                error_code: "ERROR__PET_NOT_FOUND"

This specification should mean a structure that has the two fields with these two constant values.

One more step would be the following notation:

    schema:
        value: 
            result: "ERROR"
            error_code: "ERROR__PET_NOT_FOUND"

This would determine the type to be an objects and the properties as above.

This notation would be much more dense and easier to both write and understand.

23 Answers

✔️Accepted Answer

Having a constant could be interesting for the Inheritance and Polymorphism case (when a discriminator and a mapping are defined in a oneOf schema). Take this example from the guide:

components:
  responses:
    sampleObjectResponse:
      content:
        application/json:
          schema:
            oneOf:
              - $ref: '#/components/schemas/Object1'
              - $ref: '#/components/schemas/Object2'
            discriminator:
              propertyName: objectType
              mapping:
                obj1: '#/components/schemas/Object1'
		obj2: '#/components/schemas/Object2'
  
  schemas:
    Object1:
      type: object
      required:
        - objectType
      properties:
        objectType:
          type: string
      
    Object2:
      type: object
      required:
        - objectType
      properties:
        objectType:
          type: string
      

In this case, objectType defined in #/components/schemas/Object1 and in #/components/schemas/Object2 is just present for the discriminator mapping, it would be much nicer to have it defined as constant.

Other Answers:

@gvdmarck JSON Schema 2019-09 (formerly known as draft-08) has now been published.

PR #1977 in this repository updates OpenAPI's Schema Object for OAS 3.1 to use JSON Schema 2019-09, which includes the const keyword (added back in draft-06). Assuming that PR is eventually accepted, it will solve this problem in OAS 3.1.

@halmai Taking my OAI hat off for the moment, because this is purely a personal opinion. Also, this comment isn't directed specifically at you, it is just that your assertion reflects a common belief that I feel needs to be addressed.

You said,

it makes the client development easier because the client doesn't have to interpret all the http status codes

I believe that this is incorrect. Moving the error description into the response body "for consistency" does help map HTTP APIs to a client side RPC signature. It allows HTTP APIs to be presented in a way that client developers are more familiar with. However, it is definitely not easier than using the HTTP status codes as they were intended to be used.

In your example, you already know that the response is a 404. Having a client understand that HTTP Status code 404 means "not found" is not only simple, it is consistent across all HTTP API implementations. Requiring a client developer to have to read a payload of some media type, that has some custom error payload structure, that then has some custom enum that repeats the error "not found" is not easier.

Client libraries do not have to interpret ALL of the HTTP status codes. It needs to understand 200, 300, 400, and 500 plus optionally any extra codes that the client wants to do special handling for. The HTTP spec says that if you receive a status code that you don't understand, round it down to the nearest hundred and treat it as that.

It can be useful to have payloads for response bodies that have additional details. However, there is a standard for that https://tools.ietf.org/html/rfc7807 which has existing implementations. These things should not be reinvented over and over again.

Finally, your original request was the ability to define a schema for a constant value. OpenAPI bases it's schema on JSON Schema, and JSON schema doesn't support what you are trying to do. If you want JSON Schema to change, then I would suggest talking to them, we don't have that authority.

Is there any update on this ? If you want a clear use-case, just think json:api :

GET /articles/

response:

{
  "data": [
    {
    "type": "articles",
    "id": "1",
    ...
   },
   {
    "type": "articles",
    "id": "2",
    ...
   },
   {
    "type": "articles",
    "id": "3",
    ...
   }, ...]
}

The current workaround (enum with one value) is so hacky I don't understand how it is sufficient/reasonable for everyone.

I'd like to register my interest in what @halmai originally requested. My use case is that in our responses there are some generic properties for making the response a bit more self-describing. For example, every response has a "kind" property that allows identifying what kind of stuff it contains.

We currently follow what @halmai found, namely to define an enum with one value. For example, the definition of an error response states that "kind" must be "error" as follows:

components:
  responses:
    error:
      content:
        application/json:
          schema:
            properties:
              kind:
                type: string
                enum: [error]
              ... (more properties) ...

In the Swagger 3.x editor, the Model view of the response shows that property as:

Enum:
   > Array [ 1 ]

When opening the > twistie, the enumeration shows its one value:

Enum:
   v [ error ]

That is quite inconvenient, and a const definition for such a fixed value would allow the editor to show the value right away.

Plus, stating a required fixed value via a construct such as "const" is semantically really much more to the point of what the interface wants to express in such a case., compared to defining an enum with one value.

I'm looking forward to see OpenAPI 3.1 embrace this feature from the JSON schema.

Related Issues:

43
OpenAPI Specification Defining constant value in response
Having a constant could be interesting for the Inheritance and Polymorphism case (when a discriminat...
22
kong how to let kong start automatically
you can use systemd for Control kong service First create kong.service file : and then put this line...
11
n8n Reverse Proxy
Forget that found a helpful thread on server-sent events and nginx I added proxy_buffering off; prox...
4
kong request-transformer plugin fails if multipart/form-data contains file
@arvileino that's really valuable Summary When request-transformer plugin enabled multipart/form-dat...
86
swagger ui How to disable 'Try it out' in 3.x
As there is no any other communication channel with you dev guys CC: #3544 Q A Bug or feature reques...
50
swagger ui Ability to disable TopbarPlugin via SwaggerUIBundle parameter
Drop it here since it may help I managed to remove the top bar on the latest version by simply doing...
34
swagger ui Add JWT authorization header in Swagger v3
After quite some time spent trying to figure it out I found a workaround to do what I wanted Basical...
28
swagger ui Any guidance on rendering Swagger-UI in a react app?
I'd also be extremely interested in learning if there is a recommended way to consume SwaggerUI in a...
24
swagger ui How to resolve the Cross Domain with swagger-ui?
It is not a feature is a bug: curl -X GET http://myAPI/param is runing but the same at swagger-ui NO...
17
swagger ui Examples referenced with $ref are not rendered correctly
I would like add another argument to the case for resolution Is the current behavior for schemas As ...
4
swagger ui Unable to initialize SwaggerUIBundle in Angular 4 project
Hello @asakalou I found a solution if you want to integrate swagger-ui on Angular 4 (Thanks to @shoc...
189
springfox @ApiModelProperty throwing NumberFormatException if example value is not set
Hi everybody I solved this issue removing old swagger version (1.5.20) and add new one In pom.xml ...
121
springfox Swagger ui stuck on unable to infer base url
I had the same problem using Spring Boot 2.0.0.M4 + Spring Security This solved my issue: I don't kn...
105
springfox Issue when using Swagger latest version 2.9.2 with Spring boot 2.2.0
Added this to dependency and it worked for me. Hi ...
96
fastapi WARNING: Unsupported upgrade request.
This error is not part of the FastAPI codebase When attempting to run this (using UviCorn) it starts...
64
fastapi [QUESTION] How to bridge Pydantic models with SQLAlchemy?
I just finished integrating Pydantic ORM mode into FastAPI it is released as version 0.30.0 🎉 The n...
52
swag cannot find type definition: gorm.Model
I am having the same issue: 2020/10/28 13:52:34 ParseComment error in file **/file/path/.go :cannot ...
52
fastapi [QUESTION] How to send 204 response?
Instead of returning None and instead of injecting the response just return a newly created response...
46
swag Version 1.6.9 - cannot find type definition
For those who need a quick solution: go get -u github.com/swaggo/swag/cmd/swag@v1.6.7 ...
44
grpc gateway google/protobuf/descriptor.proto: File not found
I also encountered the same problem! Does anyone know how to solve it? google/protobuf/descriptor.pr...
43
springfox Swagger-UI authorization headers stopped being sent in 2.8.0
A lot of the examples posted here and in the Springfox documentation felt too complicated for our us...
42
fastapi OpenAPI UI not working properly when using automatic swagger-ui CDN (swagger-ui-3.30.1)
Thanks for reporting it and for all the discussion here everyone! 🚀 ☕ Indeed it's a bug in Swagger ...
41
springfox Springfox swagger-ui.html not loading using version 3.0.0-SNAPSHOT
In spring boot it works by simply adding this In our project we are using 3.0.0-SNAPSHOT of swagger ...
39
L5 Swagger oauth2 + passport = Bearer <token>
Sharing my solution in case it might help This is I how made it to work with Passport using password...
34
fastapi [QUESTION] Is this the correct way to save an uploaded file ?
@classywhetten FastAPI has almost no custom logic related to UploadFile -- most of it is coming from...
34
fastapi [QUESTION] Storing object instances in the app context
@ebarlas you're 100% right Description In Flask ...
31
api platform normalization context don't work on symfony v5.1.99
Try to run ./bin/console cache:clear API Platform version(s) affected: x.y.z Description when i make...
31
springdoc openapi using https
I fixed this with this: Given that the current url for swagger-ui uses https Then the generated serv...
30
fastapi [QUESTION] aiohttp integration best practice
That is one way if you want create a new session for every request You can also use a singleton appr...
27
connexion ImportError: cannot import name 'FileStorage' from 'werkzeug'
We were using connexion==2.2.0 and started getting this error Using connexion==2.6.0 (without specif...
26
loopback next Feature parity with LoopBack 3.x (and the lack of it)
Some of the big hitters here that are blocking us from migrating from LB3 to LB4 would be: Polymorph...
26
fastapi logs with FastAPI and Uvicorn
Doing : is exactly what I was looking for ! Thank you dbanty. Hello Thanks for FastAPI easy to use i...
25
loopback next The key controller.current.ctor was not bound to any value.
I have the same issue here and I solved it in other way Description / Steps to reproduce / Feature p...
25
springfox Swagger support for Spring Boot 2 / Spring 5?
@dilipkrish - Got it working Something broke the config in Spring 5 / Spring Boot I had to add confi...
22
fastapi [QUESTION] Client Credentials Flow openAPI UI
I think I found the solution for others looking to implement the code - tiangolo has already enabled...
21
fastapi FastAPI 0.65.2 POST request fails with "value is not a valid dict" when using the Requests library; 0.65.1 works (with a caveat)
Can confirm this still happens! We solved it by adding a -H Content-Type: application/json to the cu...
19
springfox @Api(hidden = true) does not hide controller operations
After digging a bit it appears that it works if I put a @ApiIgnore on the controller ...
19
fastapi [QUESTION] Using pydantic models for GET request query params? Currently not possible, have to use dataclasses or normal classes.
@LasseGravesen You would do it like this: Check the docs here: https://fastapi.tiangolo.com/tutorial...
18
jsonschema Package version mechanism incompatible with AWS Lambda
@Julian Perhaps a blurb can be added to the docs related to deploying this library using Serverless?...
18
api platform Custom GET item without to have to specify id
Even if it doesn't respect the REST philosophy I'm trying to create a custom action which could be c...
18
fastapi [QUESTION] about threads issue with fastapi.
Hello Hi I have a question about the threads issue with fastapi ...
17
springfox How to properly annotate and present a Map type request body?
This is the exact use-case I am trying to solve for: http://stackoverflow.com/questions/41861164/how...
16
L5 Swagger API documentation is not shown (show blank page)
@matriphe Adding try_files to the block in Nginx config worked for me. I used fresh Laravel 5.4.28 a...
16
springfox Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway
Maybe Help I found that the Springboot Application Class need to add @EnableSwagger2 annotation. ...
15
openapi generator Investigate multiple schema case (different mime types) in ModelUtils
Any status of this? In ModelUtils those two methods return a single Schema for a RequestBody or a Ap...
15
springfox 404 when use swagger2-ui with spring-boot-1.5.6
@ihappyk config class pom.xml swagger class config put it spring run class same directory ...
15
springfox How to serve swagger-ui.html at more convenient URL?
My server does not allow anything to be requested directly under /* See https://stackoverflow.com/qu...
15
fastapi [FEATURE] support for rate-limit
I've taken a stab at adapting flask-limiter to starlette and FastAPI Is your feature request related...
14
springfox Allow to set up the base path in the Docket configuration (Springfox 3.0.0-SNAPSHOT)
My simple workaround but I really hope 3.0.0 will released soon ;) Version 3.0.0-SNAPSHOT Feature Re...
14
springfox How to configure BasicAuth for Swagger UI?
I found the solution also using SpringFox v 2.9.2 hope it helps. Using SpringFox v 2.9.2 and Spring ...