![Mobile Artificial Intelligence Projects](https://wfqqreader-1252317822.image.myqcloud.com/cover/722/36698722/b_36698722.jpg)
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:
![](https://epubservercos.yuewen.com/0961CC/19470380101497006/epubprivate/OEBPS/Images/77ddebb5-0ed8-49cd-8ae8-66da25492323.jpg?sign=1738933971-OdKn2AajA6eCY6BWDkFRwrCG9LTtSv7G-0-eea17b68053805e9f4c3e2e24044c8cb)
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:
![](https://epubservercos.yuewen.com/0961CC/19470380101497006/epubprivate/OEBPS/Images/43df027c-5e68-4e2e-aa8e-5c3233c7e2be.png?sign=1738933971-RKYLqQzAAOoC0FGxtezsfJWbLCNmAh3O-0-d6ac8a320efc8afbb69e8837d471e1aa)
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:
![](https://epubservercos.yuewen.com/0961CC/19470380101497006/epubprivate/OEBPS/Images/cec53b9e-bbf0-43d0-b2ad-18bfda3a0dab.png?sign=1738933971-koaBUZGyEL1wgwEMNuw4qXHGb1pEJrIy-0-b62a6cfdd28427d3387613cecc396398)
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.