0
0
Rest APIprogramming~5 mins

Human-readable error messages in Rest API

Choose your learning style9 modes available
Introduction

Human-readable error messages help users understand what went wrong in simple words. They make fixing problems easier and improve user experience.

When an API request fails and you want to tell the user why.
When validating user input and some data is missing or incorrect.
When a server error happens and you want to explain it clearly.
When a user tries to access something they don't have permission for.
When a resource is not found and you want to inform the user politely.
Syntax
Rest API
{
  "error": {
    "code": "string",
    "message": "string",
    "details": "string (optional)"
  }
}

The code is a short identifier for the error.

The message is a clear, simple explanation for the user.

Examples
This message tells the user their email input is wrong.
Rest API
{
  "error": {
    "code": "INVALID_INPUT",
    "message": "Your email address is not valid."
  }
}
This message explains a missing item with extra details.
Rest API
{
  "error": {
    "code": "NOT_FOUND",
    "message": "The requested item was not found.",
    "details": "Item ID 123 does not exist."
  }
}
Sample Program

This simple API returns a user name by ID. If the user ID is missing, it sends a human-readable error message with a 404 status.

Rest API
from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/user/<int:user_id>')
def get_user(user_id):
    users = {1: 'Alice', 2: 'Bob'}
    if user_id not in users:
        return jsonify({
            "error": {
                "code": "NOT_FOUND",
                "message": f"User with ID {user_id} was not found."
            }
        }), 404
    return jsonify({"user": users[user_id]})

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

Keep messages short and clear, avoiding technical terms.

Use consistent error codes to help developers handle errors easily.

Include extra details only if they help the user fix the problem.

Summary

Human-readable error messages explain problems in simple words.

They improve user experience and help fix issues faster.

Use clear codes and messages in your API responses.