Learn Extraqube
Tutorials

Building REST APIs with Node.js and Express

Learn how to build scalable and secure REST APIs using Node.js, Express, and modern best practices.

AAdmin 2
Jan 15, 202612 min read3435 views

Building REST APIs with Node.js and Express

Creating robust APIs is essential for modern web applications. Let's build one step by step.

Project Setup

mkdir api-project
cd api-project
npm init -y
npm install express cors helmet
npm install -D typescript @types/express @types/node

Basic Express Server

import express from 'express';
import cors from 'cors';
import helmet from 'helmet';

const app = express();

app.use(helmet());
app.use(cors());
app.use(express.json());

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok' });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Creating Routes

// routes/users.ts
import { Router } from 'express';

const router = Router();

router.get('/', async (req, res) => {
  const users = await getUsers();
  res.json(users);
});

router.post('/', async (req, res) => {
  const user = await createUser(req.body);
  res.status(201).json(user);
});

export default router;

Error Handling

Always implement proper error handling middleware for production APIs.

Next Steps

  • Add authentication with JWT
  • Implement rate limiting
  • Add request validation
  • Set up logging
Share this article:

Related Articles