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

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.

主站蜘蛛池模板: 遵义市| 全州县| 天等县| 乐东| 平阳县| 汤阴县| 阆中市| 平乡县| 华亭县| 甘南县| 平湖市| 齐齐哈尔市| 海口市| 渝中区| 桓台县| 南京市| 莒南县| 贺兰县| 岫岩| 山丹县| 陕西省| 孝感市| 绥宁县| 鱼台县| 鸡东县| 庆阳市| 沂源县| 土默特左旗| 敖汉旗| 南开区| 灵台县| 浦北县| 工布江达县| 陆河县| 正定县| 诸暨市| 泌阳县| 澎湖县| 长汀县| 剑川县| 廊坊市|