Lesson 4 / 32
Request & Reply Objects
Use the request and reply objects to read params, queries, headers and bodies and send responses.
request and reply
request contains the incoming HTTP request details (URL, headers, body, params, query). reply is an object with methods to send the response—it's pooled for performance.
Reading request data
Access path params, query strings, headers, and body from the request object.
fastify.get('/users/:id', async (request, reply) => {
const { id } = request.params;
const { filter } = request.query;
const token = request.headers.authorization;
return { userId: id, filter, hasToken: !!token };
});Sending replies
Return an object (auto-serialized to JSON) or use reply methods for custom status codes and headers.
fastify.post('/items', async (request, reply) => {
// Auto-JSON serialization
return { id: 1, status: 'created' };
});
fastify.delete('/items/:id', async (request, reply) => {
// Custom status and location header
return reply.status(204).send();
});Return or send, not both
In an async handler, either return the payload or call reply.send(). Doing both logs a warning about the reply being already sent.
Quick check
Quick check: Which sets a status code and sends JSON in one chain?
- `reply.code(201).send({id: 1})`
- `request.code(201)`
- `reply.json(201)`
Answer
`reply.code(201).send({id: 1})` — `reply.code()` returns the reply, so `.send()` chains.