Skip to content

"must be equal to constant": a value that const does not allow

Last checked and updated

The schema at the pointer says const: <value>, meaning exactly that value and nothing else, and the payload has a different one. The message is the Ajv validator's wording. The expected value is in the schema; the message itself does not print it.

A minimal case

kind:
  const: item
$ curl -X POST http://127.0.0.1:4632/items -H 'content-type: application/json' \
    -d '{"name":"a","status":"draft","quantity":2,"kind":"thing"}'
HTTP/1.1 422 Unprocessable Entity

{"errors":[{"in":"body","pointer":"/kind","message":"must be equal to constant"}],
 "type":"https://apigit.com/mock/problems/invalid-request",
 "title":"The request does not match the API description","status":422, ...}

pointer names the property: /kind. Comparison is exact: "Item" is not "item", and the string "1" is not the number 1.

Where it usually comes from: oneOf variants

const is how the variants of a oneOf are told apart, each fixing its type:

Card:
  properties:
    type: { const: card }
BankTransfer:
  properties:
    type: { const: bank_transfer }

Send {"type":"card"} without its other fields and the validator reports every variant's complaint:

{"errors":[
  {"in":"body","pointer":"","message":"must have required property 'number'"},
  {"in":"body","pointer":"","message":"must have required property 'iban'"},
  {"in":"body","pointer":"/type","message":"must be equal to constant"},
  {"in":"body","pointer":"","message":"must match exactly one schema in oneOf"}], ...}

The const line here belongs to the bank transfer variant, which rejects type: card. It does not mean card is a wrong value. The real problem is the first line: the card variant wants a number. When this message sits in a list with others under a oneOf, work out which variant each line belongs to before changing anything.

Fixes

CauseFix
The client sends another valueSend the value in the schema's const
Case or type differs ("Card", 1 against "1")Match it exactly
The line belongs to a oneOf variant you did not intendIgnore it; fix the lines of the variant you meant
The field should allow several valuesUse enum, not const
The file is OpenAPI 3.0const is not supported there; write enum: [value]

More on telling variants apart: the OpenAPI discriminator.

Sources

Related pages

Try it with your own API

Create a free workspace, add an OpenAPI file, and publish its documentation and a mock server from the same repository.

Free for individuals. No credit card.

$ npm install -g @apigit/cli$ apigit auth login$ apigit doc publish