Query string validation in Fastify

Query string validation in Fastify

What does the example of query string validation look in the Fastify documentation? Like this:

1
2
3
4
5
6
const schema = {
  querystring: {
    name: { type: 'string' },
    excitement: { type: 'integer' }
  }
}

What is the problem? It is a lie!

The correct way of defining the schema of query parameters in this case (two values: “name” and “excitement”). Looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const querySchema = {
    schema: {
       querystring: {
         type: 'object',
           properties: {
             name: {
               type: 'string'
             },
             excitement: {
               type: 'integer'
             },
         }
     }
  }
}

Additionally, if we want to make the name parameter mandatory, we add it to the array of required parameters:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const querySchema = {
    schema: {
       querystring: {
         type: 'object',
           properties: {
             name: {
               type: 'string'
             },
             excitement: {
               type: 'integer'
             },
         }
         required: ['name']
     }
  }
}

Remember to share on social media!
If you like this text, please share it on Facebook/Twitter/LinkedIn/Reddit or other social media.

If you watch programming live streams, check out my YouTube channel.
You can also follow me on Twitter: @mikulskibartosz

For business inquiries, send me a message on LinkedIn or Twitter.


Bartosz Mikulski
Bartosz Mikulski * data scientist / software engineer * conference speaker * organizer of School of A.I. meetups in Poznań * co-founder of Software Craftsmanship Poznan & Poznan Scala User Group