Topics Validation & Serialization JSON Schema Validation
intermediate 16 min read

JSON Schema Validation

Validate request bodies, query strings, params, and headers using JSON Schema.

JSON Schema Validation

// Fastify uses Ajv (Another JSON Schema Validator) internally\n\napp.post('/users', {\n  schema: {\n    // Validate request body\n    body: {\n      type: 'object',\n      required: ['name', 'email', 'password'],\n      properties: {\n        name: {\n          type: 'string',\n          minLength: 2,\n          maxLength: 100,\n        },\n        email: {\n          type: 'string',\n          format: 'email',\n        },\n        password: {\n          type: 'string',\n          minLength: 8,\n          pattern: '^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)',\n        },\n        age: {\n          type: 'integer',\n          minimum: 18,\n          maximum: 120,\n        },\n      },\n    },\n\n    // Validate query string\n    querystring: {\n      type: 'object',\n      properties: {\n        page: { type: 'integer', default: 1 },\n        limit: { type: 'integer', default: 10, maximum: 100 },\n        sort: { type: 'string', enum: ['asc', 'desc'] },\n      },\n    },\n\n    // Validate URL params\n    params: {\n      type: 'object',\n      required: ['id'],\n      properties: {\n        id: { type: 'integer' },\n      },\n    },\n\n    // Validate headers\n    headers: {\n      type: 'object',\n      properties: {\n        authorization: { type: 'string', pattern: '^Bearer ' },\n      },\n    },\n  },\n}, handler);

Examples

const Fastify = require('fastify');
const app = Fastify({ logger: true });

// Shared schemas for reusability
app.addSchema({
  \$id: 'user',
  type: 'object',
  properties: {
    id: { type: 'integer' },
    name: { type: 'string' },
    email: { type: 'string', format: 'email' },
  },
});

app.addSchema({
  \$id: 'pagination',
  type: 'object',
  properties: {
    page: { type: 'integer', default: 1, minimum: 1 },
    limit: { type: 'integer', default: 10, maximum: 100 },
  },
});

// Use shared schemas with \$ref
app.get('/users/:id', {
  schema: {
    params: {
      type: 'object',
      required: ['id'],
      properties: {
        id: { type: 'integer' },
      },
    },
    querystring: { \$ref: 'pagination#' },
    response: {
      200: {
        type: 'object',
        properties: {
          data: { \$ref: 'user#' },
        },
      },
    },
  },
}, async (request, reply) => {
  const { id } = request.params;
  const { page, limit } = request.query;
  return { data: { id, name: 'Alice', email: '[email protected]' } };
});

app.listen({ port: 3000 });

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.