# JSON Schema & Validation — Fastify: Building High-Performance Node.js APIs

Source: https://www.skillbyai.com/en/fastify/ff-json-schema

> Validate request bodies, queries and params with JSON Schema, and reject invalid input automatically.

## Schema-driven validation

Fastify uses JSON Schema to validate request bodies, query strings, and URL parameters. Invalid requests are rejected with 400 Bad Request automatically.

## Defining a schema

Pass a `schema` object in route options. It can validate body, querystring, params, and response.

```javascript
const createItemSchema = {
  body: {
    type: 'object',
    required: ['name', 'price'],
    properties: {
      name: { type: 'string' },
      price: { type: 'number', minimum: 0 },
    },
  },
};

fastify.post('/items', { schema: createItemSchema }, async (req) => {
  // req.body is guaranteed to have name and price
  return { id: 1, ...req.body };
});
```

## Query and params schemas

Validate URL parameters and query strings the same way.

```javascript
const listSchema = {
  querystring: {
    type: 'object',
    properties: {
      page: { type: 'integer', minimum: 1 },
      limit: { type: 'integer', minimum: 1, maximum: 100 },
    },
  },
  params: {
    type: 'object',
    required: ['userId'],
    properties: {
      userId: { type: 'string' },
    },
  },
};

fastify.get('/users/:userId/items', { schema: listSchema }, async (req) => {
  return [];
});
```

## Validating a body with schema

Fastify compiles the schema with Ajv at startup.

- `required` rejects missing fields.
- Invalid input gets `400` before your handler runs.

```js
const fastify = require('fastify')();

fastify.post('/user', {
  schema: {
    body: {
      type: 'object',
      required: ['name'],
      properties: { name: { type: 'string', minLength: 2 } }
    }
  }
}, async (req) => ({ hello: req.body.name }));

fastify.listen({ port: 3000 });
```

Quick check

**Quiz:** Why does a response schema make Fastify faster?

- [ ] It caches the database
- [x] It compiles a specialised serializer instead of generic JSON.stringify
- [ ] It disables logging

*Answer:* It compiles a specialised serializer instead of generic JSON.stringify. fast-json-stringify generates serialization code from the schema, and it also drops undeclared fields.
