HTTP status codes tell the client if the API request worked or if there was a problem. They help both the server and client understand what happened.
HTTP status codes for APIs in Flask
from flask import Flask, jsonify app = Flask(__name__) @app.route('/example') def example(): data = {'message': 'Success!'} return jsonify(data), 200
The status code is returned as the second value in the return statement.
Common status codes include 200 (OK), 201 (Created), 400 (Bad Request), 404 (Not Found), 500 (Internal Server Error).
return jsonify({'message': 'Created'}), 201
return jsonify({'error': 'Bad request'}), 400
return jsonify({'error': 'Not found'}), 404
return jsonify({'error': 'Server error'}), 500
This Flask app has two routes: one to get an item by ID and one to create a new item.
It uses HTTP status codes to tell the client if the request was successful or if there was an error like not found or bad request.
from flask import Flask, jsonify, request app = Flask(__name__) items = {'1': 'apple', '2': 'banana'} @app.route('/items/<item_id>', methods=['GET']) def get_item(item_id): if item_id in items: return jsonify({'item': items[item_id]}), 200 else: return jsonify({'error': 'Item not found'}), 404 @app.route('/items', methods=['POST']) def create_item(): data = request.get_json() if not data or 'id' not in data or 'name' not in data: return jsonify({'error': 'Bad request, id and name required'}), 400 if data['id'] in items: return jsonify({'error': 'Item already exists'}), 400 items[data['id']] = data['name'] return jsonify({'message': 'Item created'}), 201 if __name__ == '__main__': app.run(debug=True)
Always return the correct status code to help clients handle responses properly.
Use 2xx codes for success, 4xx for client errors, and 5xx for server errors.
Flask lets you return status codes easily by returning a tuple with the response and code.
HTTP status codes communicate the result of an API request.
Use Flask's return syntax to send both data and status codes.
Common codes: 200 (OK), 201 (Created), 400 (Bad Request), 404 (Not Found), 500 (Internal Server Error).