help me write writing end point which do some computation using python rest api
- User
help me write writing end point which do some computation using python rest api
- Assistant
help me write writing end point which do some computation using python rest api
Certainly! Below is an example of how to create a simple REST API using Python with the Flask framework that has an endpoint to perform some computation. In this example, we'll create an endpoint that adds two numbers provided by the client.
First, make sure you have Flask installed. You can install Flask using pip, if you haven't already:
pip install Flask
Now, create a file for your application, let's call it app.py:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return "Welcome to the computation API!"
@app.route('/add', methods=['POST'])
def add_numbers():
# Check if request has JSON data
if not request.is_json:
return jsonify({"error": "Missing JSON in request"}), 400
# Get data from JSON
data = request.get_json()
# Check if the necessary numbers are provided
if 'number1' not in data or 'number2' not in data:
return jsonify({"error": "Please provide 'number1' and 'number2'"}), 400
try:
# Perform computation
number1 = float(data['number1'])
number2 = float(data['number2'])
result = number1 + number2
# Return result in JSON format
return jsonify({"result": result}), 200
except ValueError:
# In case of invalid inputs
return jsonify({"error": "Invalid inputs. Please send two numbers."}), 400
if __name__ == '__main__':
# Run the Flask app
app.run(debug=True)
Here's how this script works:
flask library.Flask class.try-except block checks for errors such as invalid number formats.To use this API, you would run the script, and it will start a server (default is http://127.0.0.1:5000):
python app.py
Once the server is running, you can test the /add endpoint with a tool like curl or use any HTTP client:
Example using curl:
curl --header "Content-Type: application/json" \
--request POST \
--data '{"number1":5,"number2":3}' \
http://localhost:5000/add
This would return a response like:
{"result": 8.0}
Please note that REST APIs in a production environment should handle exceptions, validate input data thoroughly, and implement security measures like authentication and encryption, which are not covered in this simple example.