Updated April 6, 2023
Ā
Ā
Introduction to Flask get post data.
Flask gets POST data defined as types of HTTP requests, HTTP is the foundational element of data transfer methodology in the worldwide web. HTTP is the acronym for HyperText Transfer Protocol. In todayās world, all web frameworks provide several HTTP methods in their data communication, and Flask is no behind in comparison to the web frameworks. The 2 common methods which are confusing are, GET method which is the most common method that is used for sending data in an unencrypted form to the server, whereas POST request is to send HTML form data to the server and the data returned as a result of POST method is not cached by the server.
Syntax
Before we look at syntax involved in Flask GET and POST, we need to understand that there are various methodologies through which any incoming request is processed in Flask. In this section, we will learn about the handling GET and POST data in a flask from the syntax perspective so that when we learn about the spread of each of the GET and POST request in a generic sense as well as on how to handle āGETā and āPOSTā data, it will be easier to map it back with the syntax learned here for a complete picture of the topic in discussion.
Initializing the POST HTTP method:
@< Flask object >.route('/< end point >,methods = ['POST'])
Initializing the GET HTTP method:
@< Flask object >.route('/< end point >,methods = ['GET'])
Check if the request method is POST or not:
from flask import request
if request.method == 'POST':
Retrieval of data in a request method:
from flask import request
variable = request.args.get('key')
How to get POST data in Flask?
Before we even jump on to getting POST data in Flask, it is very important to know the scope of the commonly mistaken terminologies in the development of web framework so that one can have a clear guideline of the fact that it is the POST method that will follow the explanation in detail, is the correct request method one is looking for on the basis of business requirement.
Genre | GET requests | POST Requests |
Use Case | In case of requesting a resource | In case of creating a resource |
Parameters | Parameters are visible in the URL | Parameters are not visible in the URL |
Caching | Caching is possible in GET | Caching is not possible in POST |
Validity in Browser history | The request remains in the browser history | The request doesnāt remain in the browser history |
Bookmark | The requests can be bookmarked | The requests cannot be bookmarked |
Usage | Not suitable for sensitive data | It can be used for sensitive data |
Limits | Limitations on length | NO Limitations on length |
Just a brief introduction to not dilute the GET request, let us look at the ways we get āGETā data. The reason we look at GET data is that there is a commonality, and hence the confusion. This piece of the article will help in understanding that difference and hence first, the GET method. The data is passed through the URL query string to the web application. These arguments are followed by a question mark (?) character, and each pair are a combination of key and a value pair separated by an equal to (=) sign. Request. args can access the values.get( ) or request.args [ ]. Usage of request.args [ ] is restricted to the key, which should return a bad request error in case it is missing; otherwise, we generally use request.args.get( ).
Now coming to the exciting part of getting POST data in Flask. The very first way of getting POST data is using Form data. this form data is retrieved from a form that is sent as a POST request to a route. In this scenario, the URL doesnāt see the data, and it gets passed to the app from the forms behind the scenes. This request method is mentioned inside a view function. If the method is a GET, we would display the form and allow the user to fill it. And when filled, the form is processed as a POST request, and necessary actions are taken.
Another way of getting POST data is through JSON data. JSON data is the widely used way of constructing the process of the route. Here a JSON object is passed, and it gets translated into a python data structure. An object gets converted into a python dictionary. And array in JSON is converted into a list in Python. Anything in quotes is considered as text, and numbers without quotes as numbers. Once these transformations are done, the necessary handling of data in terms of argument and key is done in Flask.
Examples
Here are the following examples mention below
Example #1
Using Form data for the POST request:
Syntax
from flask import Flask, request
appFlask = Flask(__name__)
@appFlask.route('/post-using-form', methods=['GET', 'POST'])
def form_example():
# handle the POST request
if request.method == 'POST':
name = request.form.get('name')
course = request.form.get('Course')
return '''
<h1>The Student Name is: {}</h1>
<h1>The Course value is: {}</h1>'''.format(name, course)
# otherwise handle the GET request
return '''
<form method="POST">
<div><label>Student Name: <input type="text" name="name"></label></div>
<div><label>Course: <input type="text" name="Course"></label></div>
<input type="submit" value="Submit">
</form>'''
if __name__ == '__main__':
appFlask.run(debug = True)
Output:
After clicking Submit button
Example #2
Using a JSON data for the POST request:
Syntax
from flask import Flask,request
appFlask = Flask(__name__)
@appFlask.route('/post-using-json', methods=['POST'])
def json_example():
request_data = request.get_json()
name = request_data['Student Name']
course = request_data['Course']
python_version = request_data['Test Marks']['Mathematics']
example = request_data['Course Interested'][0]
return '''
The student name is: {}
The course applied for is: {}
The test marks for Mathematics is: {}
The Course student is interested in is: {}'''.format(name, course, python_version, example)
if __name__ == '__main__':
appFlask.run(debug = True)
Output:
The JSON object to the endpoint is sent through POSTMAN.
Conclusion
In conclusion, in this article, we have learned about techniques of getting POST data in Flask and different ways of processing them. POSTMAN generally processes JSON as running the methodās URL on a web browser will lead to 405 methods not allowed error. Now rest is up to readers to experiment with the tutorial tactics we went through here and apply them in real-life scenarios.
Recommended Articles
This is a guide to Flask get post data. Here we discuss the techniques of getting POST data in Flask and different ways of processing them. You may also have a look at the following articles to learn more –