How to build your first REST API with Fastify
November 2, 2026 · 2 min read
To build a REST API with Fastify, create an app, add a route with app.get(path, handler), and return an object or array from an async handler. Fastify sends it as JSON with status 200.
A GET /products route
In an empty folder, run:
npm init -y
npm pkg set type=module
npm install fastify
Create src/server.ts:
import Fastify from "fastify";
const app = Fastify({ logger: true });
const products = [
{ sku: "ESP-5LB", name: "House Espresso 5 lb", priceCents: 5500 },
{ sku: "MUG-BLUE", name: "Speckled blue mug", priceCents: 1800 },
];
app.get("/products", async () => {
return products;
});
await app.listen({ port: 3000 });
Add a script to package.json:
"scripts": {
"start": "node src/server.ts"
}
This needs Node 22.18 or newer. Start the server, then call it from a second terminal:
npm start
curl http://localhost:3000/products
Output of curl:
[{"sku":"ESP-5LB","name":"House Espresso 5 lb","priceCents":5500},{"sku":"MUG-BLUE","name":"Speckled blue mug","priceCents":1800}]
The server terminal prints Server listening at http://127.0.0.1:3000 inside a JSON log line.
What each part does
Fastify({ logger: true })creates the app and logs each request as one JSON line.app.get("/products", handler)adds a route: a method, a path, and the handler that answers it.- The handler returns the array. You don't call
JSON.stringifyor set a header yourself. app.listen({ port: 3000 })starts the server on localhost.node src/server.tsruns TypeScript directly through Node's type stripping, so you don't need a build step. If you prefer plain JavaScript, name the fileserver.jsand it works the same.
Any path you didn't define, such as /nope, gets a 404 JSON error automatically.
Common mistake
Forgetting "type": "module". Node still runs the file, but prints a MODULE_TYPELESS_PACKAGE_JSON warning and has to re-parse it as ESM, which is slower. Run npm pkg set type=module to remove the warning.
Takeaway
A Fastify route is a path plus an async function, and whatever it returns becomes the JSON response. Wire it to an npm script and you can start your API with npm start.