Error codes help machines understand what went wrong when they talk to a server. They make it easy to fix problems automatically.
0
0
Error codes for machine consumption in Rest API
Introduction
When a client sends bad data and the server needs to say 'something is wrong'.
When a user tries to access something they are not allowed to see.
When the server is busy or down and cannot handle the request.
When a requested item is not found on the server.
When the server successfully processes a request and wants to confirm it.
Syntax
Rest API
HTTP/1.1 404 Not Found Content-Type: application/json { "error_code": 404, "message": "Resource not found" }
The first line is the HTTP status line with a numeric code and a short phrase.
The body usually contains a JSON object with details like error_code and message.
Examples
This means the request worked fine and the server sends back data.
Rest API
HTTP/1.1 200 OK Content-Type: application/json { "status": "success", "data": {...} }
This tells the client that the data sent was wrong or missing something.
Rest API
HTTP/1.1 400 Bad Request Content-Type: application/json { "error_code": 400, "message": "Invalid input data" }
This means the client must log in or provide credentials to continue.
Rest API
HTTP/1.1 401 Unauthorized Content-Type: application/json { "error_code": 401, "message": "Authentication required" }
This shows the server had a problem and could not complete the request.
Rest API
HTTP/1.1 500 Internal Server Error Content-Type: application/json { "error_code": 500, "message": "Server error, try again later" }
Sample Program
This small web server returns an item name if it exists. If not, it sends a 404 error code with a message in JSON. Machines can read this to know the item was missing.
Rest API
from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/item/<int:item_id>') def get_item(item_id): items = {1: 'apple', 2: 'banana'} if item_id not in items: return jsonify({"error_code": 404, "message": "Item not found"}), 404 return jsonify({"item_id": item_id, "name": items[item_id]}), 200 if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Use standard HTTP status codes so machines and developers understand the meaning easily.
Always send error details in JSON for easy parsing by machines.
Keep error messages clear but avoid exposing sensitive information.
Summary
Error codes tell machines what happened during a request.
Use HTTP status codes with JSON messages for clear communication.
Proper error codes help automate fixes and improve user experience.