DEV Community

Huzaifa shoaib
Huzaifa shoaib

Posted on

🚀 Building a RESTful API with Node.js and Express

APIs are the bridges that connect the digital world.

In today’s modern web development, building a reliable and scalable RESTful API is a crucial skill. Node.js and Express.js offer a lightweight and efficient way to create powerful backend services.

🛠️ What is a RESTful API?

REST (Representational State Transfer) is an architectural style that uses HTTP requests to perform CRUD operations:

  • Create → POST
  • Read → GET
  • Update → PUT/PATCH
  • Delete → DELETE

"A great API doesn’t just work — it feels right." — Unknown

⚙️ Setting Up the Project

  1. Initialize Project

bash
mkdir my-api && cd my-api  
npm init -y
Install Dependencies


npm install express cors dotenv
đź§± Creating a Basic Server

const express = require('express');  
const app = express();  
const PORT = process.env.PORT || 5000;  

app.use(express.json());  

app.get('/', (req, res) => {  
  res.send('Welcome to my RESTful API!');  
});  

app.listen(PORT, () => {  
  console.log(`Server running on port ${PORT}`);  
});
📦 Structuring Routes
Let’s add some endpoints to manage users.

js
Copy
Edit
const express = require('express');  
const router = express.Router();  

let users = [  
  { id: 1, name: 'Alice' },  
  { id: 2, name: 'Bob' },  
];  

router.get('/users', (req, res) => res.json(users));  

router.post('/users', (req, res) => {  
  const newUser = { id: Date.now(), ...req.body };  
  users.push(newUser);  
  res.status(201).json(newUser);  
});  

router.put('/users/:id', (req, res) => {  
  const { id } = req.params;  
  users = users.map(user => user.id == id ? { ...user, ...req.body } : user);  
  res.json({ message: 'User updated' });  
});  

router.delete('/users/:id', (req, res) => {  
  users = users.filter(user => user.id != req.params.id);  
  res.json({ message: 'User deleted' });  
});  

module.exports = router;
Then in your main index.js:


const userRoutes = require('./userRoutes');  
app.use('/api', userRoutes);
đź“‹ Good Practices
Use middleware for authentication, logging, etc.

Use dotenv for managing environment variables.

Use Mongoose or Prisma for database connection.

Handle errors gracefully.

âś… Final Thoughts
Creating a RESTful API with Express is fast and scalable. Whether you’re building a small app or a large-scale project, Express keeps things simple.

"Build APIs like you build friendships — predictable, reliable, and honest."
Enter fullscreen mode Exit fullscreen mode

Top comments (0)