API Development and Integration

Master RESTful API design, GraphQL, API security, documentation, and integration patterns.

advanced Backend Development 6 hours

Chapter 3: HTTP Methods and Status Codes

Chapter 3 of 14

Chapter 3: HTTP Methods and Status Codes

3.1 HTTP Methods

HTTP methods indicate the desired action to be performed on a resource.

GET - Retrieve Data:

// GET requests should be idempotent and safe
app.get('/api/users/:id', async (req, res) => {
    const user = await User.findById(req.params.id);
    if (!user) {
        return res.status(404).json({ error: 'User not found' });
    }
    res.json(user);
});

POST - Create Data:

// POST creates new resources
app.post('/api/users', async (req, res) => {
    const user = await User.create(req.body);
    res.status(201).json(user);
});

PUT - Full Update:

// PUT replaces entire resource
app.put('/api/users/:id', async (req, res) => {
    const user = await User.findByIdAndUpdate(
        req.params.id,
        req.body,
        { new: true, runValidators: true }
    );
    res.json(user);
});

PATCH - Partial Update:

// PATCH updates specific fields
app.patch('/api/users/:id', async (req, res) => {
    const user = await User.findByIdAndUpdate(
        req.params.id,
        { $set: req.body },
        { new: true }
    );
    res.json(user);
});

DELETE - Remove Data:

// DELETE removes resource
app.delete('/api/users/:id', async (req, res) => {
    await User.findByIdAndDelete(req.params.id);
    res.status(204).send();
});

3.2 Status Code Best Practices

// Always return appropriate status codes
app.get('/api/users/:id', async (req, res) => {
    try {
        const user = await User.findById(req.params.id);
        if (!user) {
            return res.status(404).json({ error: 'Not found' });
        }
        res.status(200).json(user);
    } catch (error) {
        res.status(500).json({ error: 'Internal server error' });
    }
});