As I have mention in the first section, the are many type of HTTP request. So far, we use only one type which is "GET" command. In this section let's try another commonly used command in REST API, that is "POST"
For "POST" command, our client now can send some input data to the server. Let's see how can we archive that.
1. First we need another package form flask called: request this package will handle the post data sent from client.
from flask import request
2. Next we need setup a location that we going to receive and Post command and a method to execute.
@app.route('/heyJson_addThisTwoNumber',methods=['POST'])
you can see that our @app here's is slightly different, it has another parameter which is methods.
this parameter tell us that what type of HTTP request this method will be accept. The default value is:
methods=['GET']. It can also receive multiple type i.e., methods= ['GET','POST']
and here's let's try to do some basic function;
def addTwoNumber(): isJson = request.is_json print(request.is_json) if not(request.is_json): return "the request parameter is not json" dataDict = request.get_json() a = dataDict["a"] b = dataDict["b"] dataDict["result"] = a + b return jsonify(dataDict)
Nothing fancy here we let's the user send us two variable a and b and we add them up and send it back
Done below is the full code.
from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/') def hello_world(): return "hello world" @app.route('/helloJson') def hello_Json(): jsonData = { "field1_str":"value1", "field2_boolean": True, "field3_json": { "f3_field1_str":"subJson" } } return jsonify(jsonData) @app.route('/heyJson_addThisTwoNumber',methods=['POST']) def addTwoNumber(): # check if the data sent is in the right format isJson = request.is_json if not(request.is_json): return "the request parameter is not json" #get json will also covert it into dictionary dataDict = request.get_json() a = dataDict["a"] b = dataDict["b"] #add the result to the dict dataDict["result"] = a + b #send everything back in json format return jsonify(dataDict) if __name__ =="__main__": app.run(debug=True)
next let's try to check it our code running correctly.
the question is how?
there's an app called Postman, which can be used to send and receive message using REST API. It can be download as a chrome extension so I think it's quite convenience.
after finish install and sign up then pleas do the following
- HTTP request choose POST
- input localhost and sub directory toward our new service
- Test type choose JSON
- input our json
see below on how it should look like;
then click send we should able to get the response as shown below;
And we done 😏. Happy coding everyone!
No comments:
Post a Comment