0
0
Rest-apiHow-ToBeginner ยท 3 min read

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), or 500 (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 CodeMeaningWhen to Use
400Bad RequestClient sent invalid data
401UnauthorizedAuthentication required or failed
403ForbiddenClient not allowed to access resource
404Not FoundResource does not exist
500Internal Server ErrorServer 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.