Creating Flask API with Python — Continuation

In the last blog we looked into how to create a simple flask application with python. To do a recap, we import the library, initialize, annotate, name the method and give the execution condition. Then we can execute the application. A simple sample app will look like this.
import flask
app = flask.Flask(__name__)@app.route(‘/hello_world’, methods=[‘GET’])
def main():
return(“Hello World”)if __name__ == ‘__main__’:
app.run(port=5000)
Now will look into how to do a post request.
To accept a post request we simply have to change the request method to post.
@app.route(‘/hello_world’, methods=[‘POST’])
A post request will contain some post data. We will need to access this data from our application to perform some tasks. So will have a look into how we can access this post data. When we annotate a method as post, we can access all post data from it. We will have to use requests from flask for this task.
We can either import requests so we can use it directly or we can access it through flask itself. Ill show both methods.
from flask import request
Here we imported requests, so we can directly use requests. If not we can access this by
flask.requests
when we need to access it.
Alright. Now we can access the post data using requests. After annotating the method, we can simply access the data by calling the request post data.
data = request.get_json(force=True)
Now the variable data contains the post data. Mostly in API communications, data exchange is done in JSON format. Will look into a sample scenario on how to access a JSON post data like this
{‘string’ : “Hello”,
‘int’ : 2}
in a flask application.
First we will initialize all post data into a variable. In our case, lets assume we have initialized to the variable data. Then we can simply access the key value pair by using key.
string = data[‘string’]
As you can see here, the variable string will be initialized to “Hello”. That is how we access post data in a request when we are using flask.
Also this doesn’t mean we can have only one get or post method in our application. We can have as much as APIs we want as long as we give each a unique url.
Also we can allow this to run threaded so the application can process more than one requests at the same time. We can simply do that by adding the threaded status as true when we declare the execution condition.
if __name__ == ‘__main__’:
app.run(port=5000, threaded=True)
Another important thing we can look into is securing the communication. A flask API serves with http. We can simply change that into https by adding an ssl_context to the application. Will see more about this in the following blogs.
Kudos.