Skip to content

Express: User Management

Develop a basic Express.js application that simulates a simple user management system. The application should define a /users route that allows interaction through different HTTP methods. Begin by initializing an in-memory array to hold user objects, where each object includes three properties: id, name, and email.

  • Implement functionality to return all users using the GET method on /users.

  • Allow new users to be added via the POST method to the same route. Each new user should receive a unique ID that increments sequentially.

  • Implement the DELETE method on /users/:id to remove a specific user by ID.

  • Ensure that the application uses express.json() middleware to parse incoming JSON request bodies and returns appropriate JSON responses for each action. Include basic error handling to display a clear message when attempting to delete a user that does not exist.

app.js

js
import express from 'express';

const app = express();
const PORT = 3000;

// Middleware to parse JSON bodies
app.use(express.json());

// In-memory data store
let users = [
    { id: 1, name: 'Alice Johnson', email: 'alice@example.com' },
    { id: 2, name: 'Bob Smith', email: 'bob@example.com' }
];

// --- Routes ---

// GET /users - Retrieve all users
app.get('/users', (req, res) => {
    res.json(users);
});
	
// POST /users - Add a new user
let nextId = 3;
app.post('/users', (req, res) => {
    const { name, email } = req.body;
	
	if (!name || !email){
		return res.status(400).json({message: "Both needed"});
	}
    const newUser = { 
	    id: nextId++, 
	    name, 
	    email };
	    
    users.push(newUser);
    res.status(201).json(newUser);
});
	
// DELETE /users/:id - Remove a user by ID
app.delete('/users/:id', (req, res) => {
    const userId = parseInt(req.params.id, 10);
    const userIndex = users.findIndex(user => user.id === userId);
	
    if (userIndex === -1) {
        return res.status(404).json({ message: 'User not found' });
    }
	
    users.splice(userIndex, 1);
    res.json({ message: 'User deleted successfully' });
});

// Start the server
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Run and Test

bash
npm init -y
npm install express

Ensure package.json includes "type": "module".

bash
node app.js

Test the API (using curl):

  • Get all users: curl http://localhost:3000/users

  • Add a new user:

bash
curl -X POST -H "Content-Type: application/json" -d '{"name":"Charlie Brown","email":"charlie@example.com"}' http://localhost:3000/users
  • Delete a user: curl -X DELETE http://localhost:3000/users/1

  • Attempt to delete a non-existent user: curl -X DELETE http://localhost:3000/users/99

Test API with Postman

Get all users (GET)

  1. Open Postman and create a new request.

  2. Set the method to GET.

  3. Enter the URL: http://localhost:3000/users.

  4. Click Send. You will see the array of users in the response body.

Add a new user (POST)

  1. Create a new request.

  2. Set the method to POST.

  3. Enter the URL: http://localhost:3000/users.

  4. Go to the Body tab, select raw, and choose JSON from the dropdown.

  5. In the text area, enter the new user's data:

json
{
	"name": "Charlie Brown",
	"email": "charlie@example.com"
}
  1. Click Send. You will get the newly created user object back with its ID.

Delete a user (DELETE)

  1. Create a new request.

  2. Set the method to DELETE.

  3. Enter the URL for a specific user, for example: http://localhost:3000/users/1.

  4. Click Send. You will receive a success message.

Attempt to delete a non-existent user (DELETE)

  1. In the previous DELETE request, change the URL to an ID that doesn't exist, like: http://localhost:3000/users/99.

  2. Click Send. The API will correctly return a 404 Not Found status with the message "User not found".

Made with ❤️ for students, by a fellow learner.