Building a simple API to add two numbers
Now we will build a very simple API to get a grip on the Flask library and framework. This API will accept a JSON object with two numbers and return the sum of the numbers as a response.
Open a new notebook from your Jupyter home page:
- Import all the libraries we need and create an app instance:
from flask import Flask, request
app = Flask(__name__)
- Create the index page for the RESTful API using the route() decorator:
@app.route('/')
def hello_world():
return 'This is the Index page'
- Create a POST API to add two numbers using the route() decorator. This API accepts a JSON object with the numbers to be added:
@app.route('/add', methods=['POST'])
def add():
req_data = request.get_json()
number_1 = req_data['number_1']
number_2 = req_data['number_2']
return str(int(number_1)+int(number_2))
Save the Python notebook and use the File menu to download the notebook as a Python file. Place the Python file in the same directory as the model file.
Start a new command terminal and traverse to the folder with this Python file and the model. Make sure to activate the conda environment and run the following to start a server running the simple API:
- If you are using Windows, enter the following:
set FLASK_APP=simple_api
- If you aren't using Windows, enter this:
export FLASK_APP=simple_api
Then type the following:
flask run
You should see the following output when the server starts:
Open the browser and paste this address in the URL bar to go to the index page: http://127.0.0.1:5000/. Here is the output:
Next, we will use curl to access the POST API that adds two numbers. Open a new terminal and enter the following curl command to test the /add API. The numbers to add in this example are 1 and 2, and this is passed as a JSON object:
curl -i -X POST -H "Content-Type: application/json" -d "{\"number_1\":\"1\",\"number_2\":\"2\"}" http://127.0.0.1:5000/add
We will get a response with the sum of the numbers if there are no errors:
The complete code for the simple API is available as a Python notebook named simple_api.ipynb and as a Python file named simple_api.py.