Skip to main content

Building REST APIs with Node.js

Create robust and scalable REST APIs using Node.js and Express.

Cover image for: Building REST APIs with Node.js

Building REST APIs with Node.js

Learn how to create production-ready REST APIs.

Setup

Initialize your project:

npm init -y
npm install express cors helmet dotenv
npm install -D nodemon typescript @types/node @types/express

Basic 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');
});

RESTful Routes

// GET all items
app.get('/api/items', async (req, res) => {
  const items = await Item.find();
  res.json(items);
});

// POST create item
app.post('/api/items', async (req, res) => {
  const item = await Item.create(req.body);
  res.status(201).json(item);
});

Error Handling

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Something went wrong!' });
});

Conclusion

Building REST APIs with Node.js is straightforward with Express.

Share this article :