Skip to main content

Command Palette

Search for a command to run...

Structuring Your Express Project for Clean API Design

Updated
2 min readView as Markdown
R

CSE Student & a Passionate Coder

Creating a well-structured API is crucial for maintainability and scalability. In this blog post, we will focus on designing a RESTful API using Express.js, specifically targeting a single resource: users. We will cover the essential CRUD (Create, Read, Update, Delete) operations, emphasize the importance of HTTP status codes, and provide a clear response structure.

Understanding RESTful APIs

REST (Representational State Transfer) is an architectural style that uses standard HTTP methods to interact with resources. In our case, the resource is users. The primary HTTP methods we will use are:

  • GET: Retrieve data

  • POST: Create new data

  • PUT: Update existing data

  • DELETE: Remove data

CRUD Operations Mapped to HTTP Methods

OperationHTTP MethodRoute
CreatePOST/users
ReadGET/users
ReadGET/users/:id
UpdatePUT/users/:id
DeleteDELETE/users/:id

Implementing the Users Resource

Now, let's implement the CRUD operations for the users resource.

1. Create a User (POST /users)

app.post('/users', (req, res) => {
    const user = req.body;
    users.push(user);
    res.status(201).json({ message: 'User created', user });
});

2. Retrieve All Users (GET /users)

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

3. Retrieve a User by ID (GET /users/:id)

app.get('/users/:id', (req, res) => {
    const {id}=req.params;
    if (!id) return res.status(404).json({ message: 'Id is invalid' });
    res.status(200).json(user);
});

4. Update a User by ID (PUT /users/:id)

app.put('/users/:id', (req, res) => {
    const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
    if (userIndex === -1) return res.status(404).json({ message: 'User not found' });

    users[userIndex] = { ...users[userIndex], ...req.body };
    res.status(200).json({ message: 'User updated', user: users[userIndex] });
});

5. Delete a User by ID (DELETE /users/:id)

app.delete('/users/:id', (req, res) => {
    const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
    if (userIndex === -1) return res.status(404).json({ message: 'User not found' });

    users.splice(userIndex, 1);
    res.status(204).send(); // No content to send back
});

Emphasizing Status Codes and Response Structure

Using appropriate HTTP status codes is essential for conveying the result of an API request. Here’s a quick overview of the status codes used in our API:

  • 201 Created: When a new resource is created.

  • 200 OK: When a request is successful.

  • 204 No Content: When a resource is deleted successfully.

  • 404 Not Found: When a requested resource does not exist.

  • 500 : Internal Server Error

Response Structure

{
    "message": "User created",
    "user": {
        "id": 1,
        "name": "John Doe",
        "email": "john@example.com"
    }
}

More from this blog

codew_rhp

16 posts