This is a quick tutorial that allows you to learn how to receive data in a Flask Api. If you need this, it’s probably because you use Flask as a back-end service. For this tutorial we assume that the client sends JSON Data to the Flask back-end. In that case, you just need to use request.get_json() and request.args.get(‘param’). Let’s see the below example.
In this section, we will see how to pass data throw a GET request in both next cases:
Params in the url
If you want to get data by havinf a parameter in a the url. you have to do it like this:
from flask import Flask, request app = Flask(__name__) @app.route('/requests/<id>', methods=['GET']) def get_request_by_url(id): return 'id=' + id
When you are receiving data in the url. You have only two things to do. The first one is to name your data in the url by surrounding it with tag (see on line 5), And using the same name in the function parameter (see on line 6)
from flask import Flask, request app = Flask(__name__) @app.route('/requests', methods=['GET']) def get_request_by_query_parameter(): return 'id=' + request.args.get('id')
For this method there is nothing to do except calling ‘request.args.get(PARAMETER_NAME)’.
from flask import Flask, request app = Flask(__name__) @app.route('/requests', methods=['POST']) def post_request(): return str(request.get_json())
This is really easy, you just have to call request.get_json() and you receive a Python dictionary of your JSON data from this function. That’s it! Now you can use the basics of flask for receiving data from client.