Lesson 7 / 30

Basic Routing

Define routes for HTTP verbs and resource patterns.

HTTP methods

Fastify exposes fastify.get(), fastify.post(), fastify.put(), fastify.delete(), fastify.patch(), and fastify.head() for each HTTP verb.

RESTful resource routes

Typical CRUD patterns map to standard HTTP verbs.

// List all
fastify.get('/items', async () => []);

// Create one
fastify.post('/items', async (req, reply) => {
  return { id: 1, created: true };
});

// Read one
fastify.get('/items/:id', async (req) => {
  return { id: req.params.id };
});

// Update one
fastify.put('/items/:id', async (req) => {
  return { id: req.params.id, updated: true };
});

// Delete one
fastify.delete('/items/:id', async (req, reply) => {
  return reply.status(204).send();
});

Quick check: Which HTTP method is used to partially update a resource?

  • PUT
  • PATCH
  • POST
Answer

PATCH — PATCH is for partial updates; PUT replaces the entire resource.