Working with RESTful APIs

📘 Express.js 👁 46 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

A RESTful API (Representational State Transfer API) is a way to allow clients (like web or mobile apps) to interact with a server using HTTP methods.
Express.js is widely used to create RESTful APIs because it simplifies routing, middleware, and JSON handling.


1. RESTful API Basics

HTTP MethodPurposeExample Route
GETRetrieve data/users
POSTCreate new resource/users
PUTUpdate an existing resource/users/:id
PATCHPartially update a resource/users/:id
DELETEDelete a resource/users/:id

2. Setting Up Express for REST API

const express = require('express'); const app = express(); const port = 3000; // Middleware to parse JSON bodies app.use(express.json()); // Dummy data let users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ];

3. Creating Routes

GET all users

app.get('/users', (req, res) => { res.json(users); });

GET user by ID

app.get('/users/:id', (req, res) => { const user = users.find(u => u.id === parseInt(req.params.id)); if (!user) return res.status(404).json({ error: 'User not found' }); res.json(user); });

POST create a new user

app.post('/users', (req, res) => { const newUser = { id: users.length + 1, name: req.body.name }; users.push(newUser); res.status(201).json(newUser); });

PUT update a user

app.put('/users/:id', (req, res) => { const user = users.find(u => u.id === parseInt(req.params.id)); if (!user) return res.status(404).json({ error: 'User not found' }); user.name = req.body.name; res.json(user); });

DELETE a user

app.delete('/users/:id', (req, res) => { const index = users.findIndex(u => u.id === parseInt(req.params.id)); if (index === -1) return res.status(404).json({ error: 'User not found' }); const deletedUser = users.splice(index, 1); res.json(deletedUser[0]); });

4. Running the API

  1. Start server:

node app.js
  1. Use tools like Postman, Insomnia, or fetch/axios from a frontend to test endpoints.


5. Best Practices for RESTful APIs

  • Use plural nouns for resources: /users, /posts

  • Return proper HTTP status codes: 200, 201, 400, 404, 500

  • Validate request data before saving/updating

  • Separate routes into modular files using Express Router

  • Handle errors consistently using error-handling middleware


6. Example Project Structure

express-api/ │ ├─ routes/ │ └─ users.js │ ├─ app.js └─ package.json
  • app.js → Main server and middleware

  • routes/users.js → All user-related routes


Express.js makes it easy to build RESTful APIs for both small and large applications. Once you combine this with middleware, authentication, and database integration, you can create full-featured backends.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes