How to Return Error Response in REST API Correctly
To return an error response in a
REST API, send an HTTP status code indicating the error (like 400 or 404) along with a message in the response body. This helps clients understand what went wrong and how to fix it.Syntax
Returning an error response in a REST API usually involves setting the HTTP status code and sending a message in the response body. The status code shows the type of error, and the message explains it.
- Status Code: A number like
400(bad request),401(unauthorized),404(not found), or500(server error). - Response Body: Usually JSON with an error message or details.
http
HTTP/1.1 404 Not Found Content-Type: application/json { "error": "Resource not found" }
Example
This example shows a simple REST API endpoint in Node.js using Express that returns a 404 error response when a requested item is not found.
javascript
import express from 'express'; const app = express(); app.get('/items/:id', (req, res) => { const itemId = req.params.id; const items = { '1': 'Apple', '2': 'Banana' }; if (!items[itemId]) { return res.status(404).json({ error: `Item with id ${itemId} not found` }); } res.json({ id: itemId, name: items[itemId] }); }); app.listen(3000, () => console.log('Server running on port 3000'));
Common Pitfalls
Common mistakes when returning error responses include:
- Not setting the correct HTTP status code, which confuses clients.
- Sending error messages without a clear structure or in plain text instead of JSON.
- Returning success status codes (like 200) even when there is an error.
Always use proper status codes and consistent JSON error formats.
javascript
/* Wrong way: returns 200 OK even on error */ res.json({ error: 'User not found' }); /* Right way: returns 404 Not Found with JSON error */ res.status(404).json({ error: 'User not found' });
Quick Reference
Here are common HTTP status codes for error responses:
| Status Code | Meaning | When to Use |
|---|---|---|
| 400 | Bad Request | Client sent invalid data |
| 401 | Unauthorized | Authentication required or failed |
| 403 | Forbidden | Client not allowed to access resource |
| 404 | Not Found | Resource does not exist |
| 500 | Internal Server Error | Server encountered an error |
Key Takeaways
Always set the correct HTTP status code to indicate the error type.
Send error details in a clear JSON format for easy client parsing.
Avoid returning success codes like 200 when an error occurs.
Use standard status codes like 400, 401, 404, and 500 for common errors.
Consistent error responses improve API usability and debugging.