3

Background

I'm building an API with Fastify and it's my first time using JSON schema validation. The idea is that it will both make the server code more efficient and help our developers as they learn how to consume my API.

Problem

I'm trying to validate a route that allows the client to query kittens by name only. A successful formed query would look /kittens?name=fluffykins.

My schema for this route looks like this:

{
  querystring: {
    type: 'object',
    name: { type: 'string' },
  }
}

Question

How can I make my schema validator accept only queries on name and reject other queries like /kittens?age=1? My preference is for the schema validator to handle it independently of my controller code and for it to also support queries that we may add in the future.

Thanks!

Community
  • 1
  • 1
Mike Fleming
  • 2,593
  • 4
  • 14
  • 24

2 Answers2

6

As is typical of when I post a question to SO, I find an answer myself shortly after. The following is what worked for me but I'm still interested to hear if there are other better ways of doing this!

{
  querystring: {
    type: 'object',
    properties: {
        name: { type: 'string' }
    },
    anyOf: [
      {
        required: [ 'name' ]
      }
    ],
  },
}
Mike Fleming
  • 2,593
  • 4
  • 14
  • 24
3

I'm not quite sure what you are trying to do with the anyOf, so I might be missing something, but I believe this is what you want (if you are using draft-06 or later):

{
    "type": "object",
    "required": ["name"],
    "propertyNames": {"enum": ["name"]},
    "properties": {
        "name": {"type": "string"}
    }
}

The propertyNames ensures that name is the only acceptable property. You can also do this by setting "additoinalProperties": false instead (if you are useing draft-04 you have to do this as it does not support propertyNames). But doing that can cause unexpected problems when you try to combine schemas, so if you can use draft-06 propertyNames is more flexible.

Here's the draft-04 version:

{
    "type": "object",
    "required": ["name"],
    "properties": {
        "name": {"type": "string"}
    },
    "additionalProperties": false
}
Henry Andrews
  • 663
  • 3
  • 6