Fastify routes and schemas
Framework lane: Fastify 5.x, documentation lane 5.6.x. Exact supported patch, dependency lock, advisory review and execution are NOT RUN. The framework code is a static candidate; do not install dependencies or expose a server automatically. The local companion uses Node.js 22.16.0 and requires no third-party packages.
Framework example — staged
import Fastify from 'fastify';const app = Fastify({ ajv: { customOptions: { coerceTypes: false } } });app.post('/orders', { schema: { body: { type:'object', required:['quantity'], properties:{quantity:{type:'integer',minimum:1,maximum:20}} }, response: { 201: { type:'object', properties:{quantity:{type:'integer'}} } }}}, async (req, reply) => reply.code(201).send({quantity:req.body.quantity, internal:'demo'}));try { const result = await app.inject({method:'POST',url:'/orders',payload:{quantity:2}}); console.log(result.statusCode, result.body);} finally { await app.close(); }Expected behavior (not observed): Expected 201 and {"quantity":2}; internal is omitted by the declared response schema. Quantity 0 or a string should fail the specified validation.
How it works
Fastify 5 uses complete JSON Schema objects for route schemas. Body schemas apply to parsed input; default validation can coerce types, so strict policies need explicit validator options. Response schemas control serialization for matching status codes, but do not establish authorization. Schemas are trusted application configuration, not arbitrary user-provided programs.
Practice the underlying idea without dependencies
const publicOrder = order => ({quantity:order.quantity});console.log(JSON.stringify(publicOrder({quantity:2,internal:'demo'})));Run node main.mjs in a disposable directory. Expected output:
{"quantity":2}This tests the illustrated JavaScript behavior only, not the framework.
Common mistake
A response schema does not decide which records a caller may see. Apply authorization before serialization, and verify exact coercion and additional-property settings for the selected validator.
Apply it yourself
Extend the body contract with an item ID, and define tests for absent and invalid IDs without accepting arbitrary schemas from clients.
Further reading
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Fastify routes and schemas — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
What does a response schema control?
Why set coerceTypes false in this fixture?
Who should define the route schema?