官术网_书友最值得收藏!

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:

  1. Import all the libraries we need and create an app instance:
from flask import Flask, request 
app = Flask(__name__)
  1. Create the index page for the RESTful API using the route() decorator:
@app.route('/') 
def hello_world():
return 'This is the Index page'
  1. 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.

主站蜘蛛池模板: 高要市| 辽中县| 高邮市| 台南市| 讷河市| 通州市| 莫力| 奎屯市| 漾濞| 元氏县| 迭部县| 麻江县| 奉节县| 汉寿县| 阿瓦提县| 凤山市| 衡阳市| 米脂县| 邹城市| 大悟县| 赣榆县| 德阳市| 清水河县| 乌兰县| 香港 | 崇阳县| 三原县| 贵定县| 大竹县| 瓮安县| 阿克| 章丘市| 双柏县| 霍邱县| 昭觉县| 淮安市| 兴安县| 思茅市| 昌吉市| 武邑县| 本溪市|