Schemas — Validate & Serialize

JSON Schema Is Fastify's Killer Feature

Schemas — Validate & Serialize

Attach a JSON Schema to a route and Fastify validates incoming requests with Ajv and serializes outgoing responses with fast-json-stringify.

4 min read Level 2/5 #fastify#schemas#validation
What you'll learn
  • Recognize the schema parts — body, params, querystring, response
  • Validate request fields automatically
  • Serialize response fields for both speed and safety

A Fastify schema is just a JSON Schema document attached to a route. It powers four things at once: input validation, output serialization, OpenAPI generation, and TypeScript types (with a provider).

The Four Sections

app.post('/posts', {
  schema: {
    body: {
      type: 'object',
      required: ['title'],
      properties: {
        title: { type: 'string', minLength: 1 },
        published: { type: 'boolean', default: false },
      },
    },
    params: {
      type: 'object',
      properties: { id: { type: 'integer' } },
    },
    querystring: {
      type: 'object',
      properties: { draft: { type: 'boolean' } },
    },
    response: {
      201: {
        type: 'object',
        properties: {
          id: { type: 'integer' },
          title: { type: 'string' },
        },
      },
    },
  },
  handler: async (req, reply) => {
    const post = await db.posts.create(req.body);
    reply.code(201);
    return post;
  },
});

What You Get For Free

If a client posts an empty title, Fastify replies 400 Bad Request with a JSON error before your handler ever runs. If your DB row leaks a passwordHash column, the response schema strips it before sending — only the declared fields are serialized.

fast-json-stringify precompiles the response schema into a specialized serializer that runs roughly 3x faster than JSON.stringify on the same payload.

Schema Tips

Keep schemas in their own files when they grow. Reference shared definitions with $ref and a shared JSON Schema you register via app.addSchema(...). The next four lessons drill into each section in detail.

Body Schemas →