app.post()
Registers a route handling HTTP POST requests, typically with a body schema.
Syntax
app.post(url, options?, handler) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
url | string | No | The route path. |
options | RouteShorthandOptions | No | Optional schema (body/response), hooks, and config. |
handler | Function | No | Async handler receiving (request, reply). |
Returns
FastifyInstance — The instance, for chaining.
Examples
import Fastify from 'fastify';
const app = Fastify();
const bodySchema = {
type: 'object',
required: ['name'],
properties: { name: { type: 'string', minLength: 1 } },
} as const;
app.post<{ Body: { name: string } }>(
'/cats',
{ schema: { body: bodySchema } },
async (req, reply) => {
reply.code(201);
return { created: req.body.name };
},
);
Notes
Define a `body` JSON Schema so invalid payloads are rejected with a 400
before the handler runs. Set the status with reply.code(201) for created
resources.