Topics Fastify Fundamentals Routing & Schemas
beginner 16 min read

Routing & Schemas

Define routes with validation schemas, handle parameters, and structure your API.

Route Declaration

app.get('/users/:id', {\n  schema: {\n    params: {\n      type: 'object',\n      properties: { id: { type: 'integer' } },\n      required: ['id'],\n    },\n    response: {\n      200: {\n        type: 'object',\n        properties: {\n          id: { type: 'integer' },\n          name: { type: 'string' },\n        },\n      },\n    },\n  },\n}, async (request, reply) => {\n  const { id } = request.params;\n  return { id, name: 'Alice' };\n});\n\n// Shorthand declarations\napp.post('/users', {\n  schema: {\n    body: {\n      type: 'object',\n      required: ['name', 'email'],\n      properties: {\n        name: { type: 'string', minLength: 2 },\n        email: { type: 'string', format: 'email' },\n        age: { type: 'integer', minimum: 0 },\n      },\n    },\n  },\n}, async (request, reply) => {\n  const user = await createUser(request.body);\n  reply.code(201).send(user);\n});

Route Options

app.route({\n  method: 'GET',\n  url: '/users',\n  schema: { /* ... */ },\n  preHandler: [authenticate],\n  handler: async (request, reply) => { /* ... */ },\n});\n\n// Prefix a group of routes\nconst routes = async (fastify, opts) => {\n  fastify.get('/', async () => ({ status: 'ok' }));\n};\napp.register(routes, { prefix: '/api/v1' });

Examples

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

// Route with validation schema
app.get('/users/:id', {
  schema: {
    params: {
      type: 'object',
      properties: {
        id: { type: 'integer' },
      },
      required: ['id'],
    },
    response: {
      200: {
        type: 'object',
        properties: {
          id: { type: 'integer' },
          name: { type: 'string' },
          email: { type: 'string', format: 'email' },
        },
      },
      404: {
        type: 'object',
        properties: {
          error: { type: 'string' },
        },
      },
    },
  },
}, async (request, reply) => {
  const users = {
    1: { id: 1, name: 'Alice', email: '[email protected]' },
    2: { id: 2, name: 'Bob', email: '[email protected]' },
  };

  const user = users[request.params.id];
  if (!user) {
    reply.code(404);
    return { error: 'User not found' };
  }

  return user;
});

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.