Junior — Middle
What response code should be used in HTTP when the requested data is not found in the database?
sobes.tech AI
Answer from AI
If the requested data is not present in the database, the HTTP status 404 Not Found is usually returned. This code indicates that the server cannot find the requested resource.
Example in Python using Flask:
from flask import Flask, jsonify
app = Flask(__name__)
data = {"1": "item1", "2": "item2"}
@app.route('/items/<item_id>')
def get_item(item_id):
item = data.get(item_id)
if item is None:
return jsonify({"error": "Item not found"}), 404
return jsonify({"item": item})
if __name__ == '__main__':
app.run()
Thus, if the item is not found, the client will receive a response with code 404.