0
0
Rest APIprogramming~5 mins

Error response structure in Rest API

Choose your learning style9 modes available
Introduction

When something goes wrong in a web service, we need a clear way to tell the user what happened. An error response structure helps us send this information in a simple, organized way.

When a user sends wrong data to a web service.
When a requested resource is not found.
When the server has a problem and cannot complete the request.
When the user is not allowed to access certain information.
When the request format is incorrect or missing required parts.
Syntax
Rest API
{
  "error": {
    "code": "string",
    "message": "string",
    "details": "string (optional)"
  }
}

The code is a short identifier for the error type.

The message explains the error in simple words.

Examples
This shows a simple error when something is not found.
Rest API
{
  "error": {
    "code": "404",
    "message": "Resource not found"
  }
}
This error tells the user that some input is wrong and gives extra details.
Rest API
{
  "error": {
    "code": "400",
    "message": "Invalid input",
    "details": "The 'email' field is missing"
  }
}
Sample Program

This small web service returns a user name by ID. If the user ID is not found, it sends an error response with code 404 and a message.

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": "404",
                "message": "User not found"
            }
        }), 404
    return jsonify({"user": users[user_id]})

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

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

Include an error code to help developers handle errors programmatically.

Optional details can give more context but keep it short.

Summary

An error response structure helps communicate problems clearly.

It usually contains a code and a message.

Use it whenever your API needs to tell the user something went wrong.