0
0
Rest APIprogramming~5 mins

Error response format in Rest API

Choose your learning style9 modes available
Introduction

When something goes wrong in a web service, we need to tell the user clearly what happened. An error response format is a simple way to share this information.

When a user sends wrong data to a web service.
When a requested resource is not found on the server.
When the user is not allowed to access certain information.
When the server has a problem and cannot complete the request.
When the user tries to do something that is not allowed.
Syntax
Rest API
{
  "error": {
    "code": "string",
    "message": "string",
    "details": "string (optional)"
  }
}

The code is a short identifier for the error.

The message explains the error in simple words.

Examples
This means the requested page or data was not found.
Rest API
{
  "error": {
    "code": "404",
    "message": "Resource not found"
  }
}
This tells the user they must log in first.
Rest API
{
  "error": {
    "code": "401",
    "message": "Unauthorized",
    "details": "You need to log in to access this resource."
  }
}
Sample Program

This small web service returns an item by its ID. If the item is missing, it sends a clear error response with code 404 and a message.

Rest API
from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/data/<int:item_id>')
def get_data(item_id):
    data_store = {1: 'apple', 2: 'banana'}
    if item_id not in data_store:
        return jsonify({
            "error": {
                "code": "404",
                "message": "Item not found",
                "details": f"No item with id {item_id} exists."
            }
        }), 404
    return jsonify({"item": data_store[item_id]})

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always use clear and simple messages so users understand the problem.

Include HTTP status codes like 404 or 401 to help developers handle errors properly.

Optional details can give extra info but keep it short.

Summary

Error response format helps communicate problems clearly in web services.

It usually includes a code, a message, and sometimes extra details.

Using standard formats makes it easier for users and developers to understand errors.