Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 39 ยท Projects and Practice

Project: Notes API

Build a complete notes REST API in the Fastify style: routes, JSON schema validation, pagination, search, error handling, plugins and a test suite using inject.

Time to put the pieces together. In this project you design and build a small notes API: create, read, update, delete and search notes, with validation, pagination, consistent errors and tests. You will write it the way a real Fastify project is organized: a buildApp factory, a plugin for the notes routes, schemas next to the routes, and tests that call inject.

Fastify is not installed on this site. The runnable code uses the Fastify-like stand-in from earlier lessons (same get/post/put/delete, addHook, inject shapes) and a hand-written validator. Each section ends with the real Fastify code for the same part, as a read-only snippet, so you can copy the structure into a real project.

What we are building

Notes CRUD Create, read, update, delete.
List and search Pagination and a q filter.
Validation Reject bad input with 400.
Tests Every route, with inject.

Small scope, production habits.

1 / 2

Requirements

Method and path Behavior
POST /notes Create. Body { title, body?, tags? }. Answer 201 with the note and a location header.
GET /notes List. Query page, limit (max 50), q (matches title or body), tag.
GET /notes/:id One note, or 404.
PUT /notes/:id Replace title, body, tags. Update updatedAt.
DELETE /notes/:id 204 with no body, or 404.

Rules: titles are 1 to 80 characters; bodies up to 2,000; at most 5 tags of 1 to 20 characters; unknown fields are rejected; errors have one consistent JSON shape.

Step 1: schemas

In real Fastify you describe input once as JSON Schema and the framework validates it for you (see JSON Schema Basics):

JavaScript
// real Fastify: routes/notes.schemas.js
export const noteBody = {
  type: 'object',
  required: ['title'],
  additionalProperties: false,
  properties: {
    title: { type: 'string', minLength: 1, maxLength: 80 },
    body:  { type: 'string', maxLength: 2000, default: '' },
    tags:  { type: 'array', maxItems: 5, uniqueItems: true, items: { type: 'string', minLength: 1, maxLength: 20 }, default: [] },
  },
};
export const listQuery = {
  type: 'object',
  properties: {
    page:  { type: 'integer', minimum: 1, default: 1 },
    limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 },
    q:     { type: 'string', maxLength: 100 },
    tag:   { type: 'string', maxLength: 20 },
  },
};

The stand-in app below uses a tiny validate function that applies the same rules, so you can run the whole flow.

Step 2: the application

Notice the structure: the store is a dependency passed to the factory (so tests can start with their own data), the routes live in one function that plays the role of a plugin, and the error handler gives every failure the same shape.

Node.js The notes API, ready to call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the code as a checklist of good habits: input is validated before use, ids come from the server, the 404 message is the same shape as every other error, 500 errors hide internal details, and pagination bounds the response size.

Step 3: the real Fastify version

In real Fastify the pieces map one to one:

JavaScript
// src/app.js
import Fastify from 'fastify';
import notesPlugin from './routes/notes.js';

export function buildApp({ store = new Map(), ...options } = {}) {
  const app = Fastify(options);
  app.setErrorHandler((err, request, reply) => {
    const statusCode = err.statusCode ?? 500;
    if (statusCode >= 500) request.log.error(err);
    reply.code(statusCode).send({ statusCode, error: err.code ?? 'Error', message: statusCode >= 500 ? 'Something went wrong' : err.message });
  });
  app.register(notesPlugin, { store, prefix: '/notes' });
  return app;
}

// src/routes/notes.js
export default async function notesPlugin(app, { store }) {
  app.post('/', { schema: { body: noteBody } }, async (request, reply) => { /* ... */ });
  app.get('/', { schema: { querystring: listQuery } }, async (request) => { /* ... */ });
}

With schema.body in place, Fastify returns the 400 itself, so you delete the hand-written parsing. You can add a response schema as well to guarantee the output shape and speed up serialization (Response Serialization and Schemas).

Step 4: tests

A test per rule in the requirements table is the quickest way to be sure the API does what you wrote. These tests use inject, a fresh app per test and a tiny runner (the same pattern as Testing Fastify Apps with inject). The app code is repeated in compact form so the example stays self-contained.

Node.js Test suite for the notes API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Ideas to extend it

  1. Persistence: swap the Map for SQLite (node:sqlite) or PostgreSQL behind the same store interface; tests keep working with the in-memory fake.
  2. Authentication: add the JWT hook from JWT Authentication with Fastify and give each note an ownerId with the ownership check from Authorization, Input Hardening and Secrets.
  3. Rate limiting and security headers from Security Headers, CORS and Rate Limiting.
  4. Caching: an ETag on GET /notes/:id (Caching, ETags and Compression).
  5. Deployment: the Dockerfile and graceful shutdown from Deploying Fastify: Docker, Environments, Shutdown.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the factory receive the store as a parameter?

    Passing dependencies in lets tests start from a known state and later swap the storage for a real database.
  2. 2. Which status and body does a successful DELETE use in this API?

    204 No Content tells the client the deletion worked and there is nothing more to send.
  3. 3. Why return the generic message 'Something went wrong' for 500 errors?

    Clients get a safe message; the real error is logged for developers.
  4. 4. What does the real Fastify schema.body option replace in this project?

    Fastify compiles the schema into a validator and answers 400 for invalid bodies before your handler runs.

Summary

  • Structure the app as buildApp + a routes plugin + schemas + injectable dependencies.
  • Validate every input, reject unknown fields, bound pagination, and keep one error shape.
  • Use proper status codes: 201 with Location, 204 for delete, 400 for bad input, 404 for unknown ids.
  • Test each requirement with inject and a fresh app.

Next: Project: Authenticated Bookmarks API