Creating a High-Performance REST API With Fastify and PostgreSQL

Creating a High-Performance REST API With Fastify and PostgreSQL When building scalable back-end services in Node.js, Fastify offers blazing-fast HTTP performance with a developer-friendly interface. In this guide, we’ll build a simple REST API connected to a PostgreSQL database using pg. Why Fastify? Fastify is a modern web framework for Node.js that prioritizes performance and low overhead. It supports JSON Schema validation, automatic Swagger documentation, hooks, and more. Step 1: Initialize Your Project npm init -y npm install fastify pg fastify-plugin Step 2: Set Up Fastify and Register the Database // db.js const fp = require('fastify-plugin'); const { Pool } = require('pg'); async function dbConnector(fastify, options) { const pool = new Pool({ user: 'postgres', host: 'localhost', database: 'fastifydb', password: 'password', port: 5432, }); fastify.decorate('pg', pool); } module.exports = fp(dbConnector); Step 3: Define the API Routes // routes/user.js async function userRoutes(fastify, options) { fastify.get('/users', async (request, reply) => { const result = await fastify.pg.query('SELECT * FROM users'); return result.rows; }); fastify.post('/users', async (request, reply) => { const { name, email } = request.body; const result = await fastify.pg.query( 'INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *', [name, email] ); return result.rows[0]; }); } module.exports = userRoutes; Step 4: Start the Server // index.js const fastify = require('fastify')({ logger: true }); const dbConnector = require('./db'); const userRoutes = require('./routes/user'); fastify.register(dbConnector); fastify.register(userRoutes); const start = async () => { try { await fastify.listen({ port: 3000 }); } catch (err) { fastify.log.error(err); process.exit(1); } }; start(); Step 5: Test Your API Make sure PostgreSQL is running and a users table exists. You can now test endpoints using tools like Postman or cURL: curl http://localhost:3000/users Conclusion Fastify is a fantastic choice for building REST APIs in Node.js when speed and scalability are critical. Pairing it with PostgreSQL provides a powerful, production-ready backend stack. If this post helped you, consider supporting me: buymeacoffee.com/hexshift

Apr 13, 2025 - 21:03
 0
Creating a High-Performance REST API With Fastify and PostgreSQL

Creating a High-Performance REST API With Fastify and PostgreSQL

When building scalable back-end services in Node.js, Fastify offers blazing-fast HTTP performance with a developer-friendly interface. In this guide, we’ll build a simple REST API connected to a PostgreSQL database using pg.

Why Fastify?

Fastify is a modern web framework for Node.js that prioritizes performance and low overhead. It supports JSON Schema validation, automatic Swagger documentation, hooks, and more.

Step 1: Initialize Your Project

npm init -y
npm install fastify pg fastify-plugin

Step 2: Set Up Fastify and Register the Database

// db.js
const fp = require('fastify-plugin');
const { Pool } = require('pg');

async function dbConnector(fastify, options) {
  const pool = new Pool({
    user: 'postgres',
    host: 'localhost',
    database: 'fastifydb',
    password: 'password',
    port: 5432,
  });

  fastify.decorate('pg', pool);
}

module.exports = fp(dbConnector);

Step 3: Define the API Routes

// routes/user.js
async function userRoutes(fastify, options) {
  fastify.get('/users', async (request, reply) => {
    const result = await fastify.pg.query('SELECT * FROM users');
    return result.rows;
  });

  fastify.post('/users', async (request, reply) => {
    const { name, email } = request.body;
    const result = await fastify.pg.query(
      'INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *',
      [name, email]
    );
    return result.rows[0];
  });
}

module.exports = userRoutes;

Step 4: Start the Server

// index.js
const fastify = require('fastify')({ logger: true });
const dbConnector = require('./db');
const userRoutes = require('./routes/user');

fastify.register(dbConnector);
fastify.register(userRoutes);

const start = async () => {
  try {
    await fastify.listen({ port: 3000 });
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

start();

Step 5: Test Your API

Make sure PostgreSQL is running and a users table exists. You can now test endpoints using tools like Postman or cURL:

curl http://localhost:3000/users

Conclusion

Fastify is a fantastic choice for building REST APIs in Node.js when speed and scalability are critical. Pairing it with PostgreSQL provides a powerful, production-ready backend stack.

If this post helped you, consider supporting me: buymeacoffee.com/hexshift