Predictive Hacks

How to Process Requests in Flask

deploy a flask api

The most common payload of incoming data are the query strings, the form data and the JSON objects. Let’s provide some examples of these three types.

Query Strings

A query string is of the form example.com?arg1=value1&arg2=value2 where the query starts after the question mark (?) and the key-values pairs are separated by the ampersand (&) symbol, where each key-value item is separated by the equals sign (=) like arg1=value1.

# import main Flask class and request object
from flask import Flask, request

# create the Flask app
app = Flask(__name__)

@app.route('/query-example')
def query_example():
    # if key doesn't exist, returns None
    language = request.args.get('language')

    # if key doesn't exist, returns a 400, bad request error
    framework = request.args['framework']

    # if key doesn't exist, returns None
    website = request.args.get('website')

    return '''
              <h1>The language value is: {}</h1>
              <h1>The framework value is: {}</h1>
              <h1>The website value is: {}'''.format(language, framework, website)


if __name__ == '__main__':
    # run app in debug mode on port 5000
    app.run(debug=True, port=5000)

You can run the app by using the URL:

http://127.0.0.1:5000/query-example?language=Python&framework=Flask&website=PredictiveHacks

And you should see on the browser following output:


The language value is: Python
The framework value is: Flask
The website value is: PredictiveHacks

Form Data

The form data are POST requests.

# import main Flask class and request object
from flask import Flask, request

# create the Flask app
app = Flask(__name__)

# allow both GET and POST requests
@app.route('/form-example', methods=['GET', 'POST'])
def form_example():
    # handle the POST request
    if request.method == 'POST':
        language = request.form.get('language')
        framework = request.form.get('framework')
        return '''
                  <h1>The language value is: {}</h1>
                  <h1>The framework value is: {}</h1>'''.format(language, framework)

    # otherwise handle the GET request
    return '''
           <form method="POST">
               <div><label>Language: <input type="text" name="language"></label></div>
               <div><label>Framework: <input type="text" name="framework"></label></div>
               <input type="submit" value="Submit">
           </form>'''

if __name__ == '__main__':
    # run app in debug mode on port 5000
    app.run(debug=True, port=5000)

Now we can run the app using the URL:

http://127.0.0.1:5000/form-example

The browser should display a form with two input fields – one for language and one for framework – and a submit button. The language and framework are the names of the inputs. By filling the language field with SQL and the framework field with the value of Flask and pressing the Submit button you will get”

The language value is: SQL
The framework value is: Flask

JSON Data

JSON is the most common form, especially in the Data Science world. Assuming that our JSON data are the following:

{
    "language" : "Python",
    "framework" : "Flask",
    "website" : "Scotch",
    "version_info" : {
        "python" : "3.9.0",
        "flask" : "1.1.2"
    },
    "examples" : ["query", "form", "json"],
    "boolean_test" : true
}

And our Flask API:

# import main Flask class and request object
from flask import Flask, request

# create the Flask app
app = Flask(__name__)

# GET requests will be blocked
@app.route('/json-example', methods=['POST'])
def json_example():
    request_data = request.get_json()

    language = request_data['language']
    framework = request_data['framework']

    # two keys are needed because of the nested object
    python_version = request_data['version_info']['python']

    # an index is needed because of the array
    example = request_data['examples'][0]

    boolean_test = request_data['boolean_test']

    return '''
           The language value is: {}
           The framework value is: {}
           The Python version is: {}
           The item at index 0 in the example list is: {}
           The boolean value is: {}'''.format(language, framework, python_version, example, boolean_test)

if __name__ == '__main__':
    # run app in debug mode on port 5000
    app.run(debug=True, port=5000)

For this request, we will need to use Postman to send the requests. In Postman, add the URL http://127.0.0.1:5000/json-example and change the type to POST. On the body tab, change to raw and select JSON from the drop-down and copy-paste the JSON data above into the text input.

Reference

[1] Digital Ocean

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

snowflake
Miscellaneous

How to Schedule Tasks in Snowflake

We have started a series of Snowflake tutorials, like How to Get Data from Snowflake using Python, How to Load