Lesson 10 / 30
JSON Schema & Validation
Define and enforce strict data contracts with JSON Schema.
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.
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.
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 [];
});