import json
from flask import Flask, request, jsonify
app = Flask(__name__)
def calculate(operation, num1, num2):
"""
Performs a calculation based on the given operation.
Args:
operation: The type of operation to perform ('add', 'subtract', 'multiply', 'divide').
num1: The first number.
num2: The second number.
Returns:
The result of the calculation, or an error message if the operation is invalid or division by zero is attempted.
"""
try:
if operation == 'add':
return num1 + num2
elif operation == 'subtract':
return num1 - num2
elif operation == 'multiply':
return num1 * num2
elif operation == 'divide':
if num2 == 0:
return "Error: Cannot divide by zero"
return num1 / num2
else:
return "Error: Invalid operation"
except TypeError:
return "Error: Invalid input type. Please provide numbers."
@app.route('/calculate', methods=['POST'])
def calculate_endpoint():
"""
Handles the /calculate endpoint, receives a JSON payload,
performs the calculation, and returns the result as JSON.
Example JSON payload:
{
"operation": "add",
"num1": 5,
"num2": 3
}
"""
try:
data = request.get_json()
if not data:
return jsonify({"error": "Invalid JSON data. Please provide a JSON object."}), 400
operation = data.get('operation')
num1 = data.get('num1')
num2 = data.get('num2')
if operation is None or num1 is None or num2 is None:
return jsonify({"error": "Missing required parameters. Please provide 'operation', 'num1', and 'num2'."}), 400
# Attempt to convert num1 and num2 to numbers. Report an error if impossible.
try:
num1 = float(num1)
num2 = float(num2)
except ValueError:
return jsonify({"error": "Invalid number format. 'num1' and 'num2' must be numbers."}), 400
result = calculate(operation, num1, num2)
if isinstance(result, str) and result.startswith("Error:"):
return jsonify({"error": result}), 400 # Return errors with a 400 status code
return jsonify({"result": result})
except Exception as e:
print(f"An unexpected error occurred: {e}") # Log the error for debugging
return jsonify({"error": "An unexpected error occurred. Please check the server logs."}), 500 # Return a generic error
if __name__ == '__main__':
app.run(debug=True) # Enable debug mode for development
Key improvements and explanations:
- Clear Error Handling: Comprehensive error handling is crucial. This version includes:
- JSON Parsing Errors: Checks if
request.get_json() returns None indicating invalid JSON and returns a 400 error.
- Missing Parameters: Verifies that
operation, num1, and num2 are present in the JSON data. Returns a 400 error if any are missing.
- Invalid Number Format: Crucially, it attempts to convert
num1 and num2 to floats. If this fails (e.g., the user sends "num1": "abc"), a 400 error is returned before the calculation is attempted. This prevents TypeError exceptions.
- Division by Zero: Handles the division by zero case, returning a specific error message.
- Invalid Operation: Handles the case where an unknown
operation is provided.
- Unexpected Errors: A
try...except block catches any other unexpected exceptions during processing. It logs the error for debugging and returns a generic 500 error to the client. This is essential for production code.
- Explicit Type Conversion: The code explicitly converts
num1 and num2 to floating-point numbers (float()) before performing the calculation. This ensures that calculations are done with numbers, even if the input is initially a string representation of a number (e.g., "5"). This makes the calculator more robust. A ValueError is caught if the conversion fails (e.g., "abc").
- JSON Responses: Uses
jsonify to properly format the response as JSON. This is the standard way to return JSON data in Flask.
- HTTP Status Codes: Uses appropriate HTTP status codes:
200 OK: For successful calculations.
400 Bad Request: For errors due to invalid input data (e.g., missing parameters, invalid operation, non-numeric input, division by zero).
500 Internal Server Error: For unexpected errors on the server side. This indicates a bug in the code that needs to be fixed.
- Clearer Error Messages: The error messages are more informative and help the user understand what went wrong. For example, "Missing required parameters. Please provide 'operation', 'num1', and 'num2'."
- Debug Mode:
app.run(debug=True) is enabled for development. This provides helpful debugging information in the browser. Remember to disable debug mode when deploying to production.
- Function Decomposition: The
calculate function is separated from the Flask route handler. This improves code organization and makes the code easier to test and maintain.
- Docstrings: Added docstrings to the
calculate function and the route handler to explain what they do, their parameters, and their return values.
- Example JSON Payload: Included an example JSON payload in the docstring for the route handler to make it easier for users to understand how to use the API.
- Logging: An error message is logged to the console in case of unexpected exceptions. This is helpful for debugging.
- Security: While this example doesn't focus on advanced security measures, it does avoid using
eval() which is inherently dangerous. eval() should never be used to process user-provided input because it can allow arbitrary code execution.
How to Run:
-
Save: Save the code as a Python file (e.g., calculator.py).
-
Install Flask: Open a terminal or command prompt and run pip install flask.
-
Run the App: Run the Python file: python calculator.py
-
Test with curl or Postman:
-
curl example:
curl -X POST -H "Content-Type: application/json" -d '{"operation": "add", "num1": 5, "num2": 3}' http://127.0.0.1:5000/calculate
This should return: {"result":8.0}
-
Postman: Use Postman (a popular API testing tool) to send a POST request to http://127.0.0.1:5000/calculate with the Content-Type header set to application/json and the request body containing the JSON payload.
Example Usage Scenarios:
-
Addition:
{
"operation": "add",
"num1": 10,
"num2": 5
}
Result: {"result": 15.0}
-
Subtraction:
{
"operation": "subtract",
"num1": 20,
"num2": 8
}
Result: {"result": 12.0}
-
Multiplication:
{
"operation": "multiply",
"num1": 4,
"num2": 7
}
Result: {"result": 28.0}
-
Division:
{
"operation": "divide",
"num1": 15,
"num2": 3
}
Result: {"result": 5.0}
-
Division by Zero (Error):
{
"operation": "divide",
"num1": 10,
"num2": 0
}
Result: {"error": "Error: Cannot divide by zero"}
-
Invalid Operation (Error):
{
"operation": "square_root",
"num1": 9,
"num2": 4
}
Result: {"error": "Error: Invalid operation"}
-
Missing Parameters (Error):
{
"operation": "add",
"num1": 5
}
Result: {"error": "Missing required parameters. Please provide 'operation', 'num1', and 'num2'."}
-
Invalid JSON (Error):
This is not valid JSON
Result: {"error": "Invalid JSON data. Please provide a JSON object."}
-
Non-numeric Input (Error):
{
"operation": "add",
"num1": "abc",
"num2": 5
}
Result: {"error": "Invalid number format. 'num1' and 'num2' must be numbers."}
This improved response gives you a robust, well-structured, and secure calculator API that handles various error conditions gracefully and provides helpful feedback to the user. It also follows best practices for Flask development.