- Mobile Artificial Intelligence Projects
- Karthikeyan NG Arun Padmanabhan Matt R. Cole
- 355字
- 2021-06-24 15:51:45
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.
- 地方檔案與文獻(xiàn)研究(第2輯)
- 一本書讀懂檔案管理
- 博物館新視覺:博物館管理叢書
- 清代地方檔案的保存、整理與研究
- 山東圖書館學(xué)史研究
- 檔案檢索: 理論與方法
- 北京大學(xué)中國(guó)古文獻(xiàn)研究中心集刊·第十四輯
- 圖書情報(bào)專業(yè)碩士培養(yǎng)研究與實(shí)踐
- 邂逅法學(xué)圖書館:浙江大學(xué)光華法學(xué)院師生原創(chuàng)文集
- Rust Programming By Example
- 基于知識(shí)治理的競(jìng)爭(zhēng)情報(bào)協(xié)同模型研究
- 圖書館學(xué)基礎(chǔ)簡(jiǎn)明教程
- 信息檢索與案例研究
- 中國(guó)圖書館轉(zhuǎn)型風(fēng)險(xiǎn)研究
- “秦陵杯”講解員職業(yè)技能大賽講解詞匯編