Updated April 10, 2023
Introduction to Flask POST request
Flask POST request is defined as an HTTP protocol method that enables users to send HTML form data to server. The HTTP protocol is the foundation of data communication and is basically defined as an application layer for collaborative, distributed, hypermedia information systems. The reason we call HTTP as hypertext is because in the world wide web, the hypertext documents are hyperlinks to other resources that can be easily accessed by the user. A POST request is one of the HTTP methods which enables users to send the data for any update or creation of a resource. The request body of the HTTP request contains the data that is been sent to the server using POST method.
Syntax of Flask POST request
Given below are the syntaxes of Flask POST request:
1. Configure the method in the decorator.
appConfig = Flask(__name__)
appConfig.route('/<API end point>', methods = ['POST'])
2. Retrieve parameter from form.
Non-compulsory key:
variable_name = request.form.get('<key name>')
Compulsory key:
variable_name = request.form['<key name>']
3. Retrieve parameter from query.
Non-compulsory key:
variable_name = request.args.get('<key name>')
Compulsory key:
variable_name = request.args['<key name>']
4. Retrieve parameter from JSON.
variable_name = request.get_json( )
key_variable = variable_name ['<key name>']
How POST Request Work in Flask?
- As we have, by now, understood that POST is one of the HTTP protocol methods, that enables users to send form data to the server. The data, when received by the POST method, is not cached by the server when it is received. In this description, we have encountered a lot of new terminologies, and then look at how we can put them together in respective places and look at the bigger picture.
- A form in the HTTP request is like an interface that allows users to compile set of key and value pairs from user input and enables a way to construct the key and value pairs to represent form fields and their values. Now, POST is a method that allows this set of key and value pairs to be sent to the server and is set by method attribute that specifies how a form data is sent. The action attribute in the HTTP template directs the submission of the form data to the location specified in the attribute. Next, when we enter the function defined for an endpoint, we encounter request context. It is now time to understand the working of request context so that we complete the full circle of post request work.
- Request context is information about the HTTP request that keeps a track of the data at the request level. Instead of passing the request object itself, the request proxies are accessed instead. Any flask application, while handling a request, creates a Request object. This object created is dependent on the environment as received by the WSGI server. A worker is able to handle only one request at a time. As the request is made, the flask application automatically pushes a request context during the course. Functions, error handlers are able to access the proxy during the request. Now we know on what role does request context play in a POST request.
Example:
Code:
from flask import Flask, redirect, url_for, render_template, request, session
from datetime import timedelta
appFlask = Flask(__name__)
appFlask.secret_key = "27eduCBA09"
@appFlask.route("/login", methods = ['POST','GET'])
def login():
if request.method == 'POST':
studentName = request.form['studentName']
website = request.form.get('website')
return 'Submitted!'
return '''<form method = "post">
<p>Enter Name:</p>
<p><input type = "text" name = "studentName" /></p>
<p>Enter Website:</p>
<p><input type = "text" name = "website" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>'''
if __name__ == "__main__":
appFlask.run(debug=True)
- At the very first we import all the required modules for running the flask application. Next, we create the flask application object which will contain all the details or characteristics of Flask application. Now it is time to assign the endpoint in the decorator. When the URL is posted, the corresponding decorator is searched for and the corresponding function is activated. The reason we put both the methods in the decorator is that there are circumstances when the endpoint in itself is where the form gets submitted. If only POST method is mentioned, it will lead to a situation mentioning that a certain method is not allowed. In short, the endpoint acts as POST and GET method, and hence the need to mention both.
- Now the code will search for any HTTP request, and at the start since it doesn’t get any POST request, it will return the content present in the last return (outside the if loop). Now once the user enters the data and clicks on “Submit” button, the if loop gets activated, and leads to execution of the commands inside the same. The request context helps in getting the argument.
Examples of Flask POST request
Given below are the examples of Flask POST request:
Example #1
Retrieve parameter from form.
Syntax:
Compulsory key:
studentName = request.form['studentName']
Non-compulsory key:
website = request.form.get('website')
Output:
When we provide both keys:
When compulsory key is wrongly used:
When the non-compulsory key is wrongly used:
Example #2
Retrieve parameter from query.
Syntax:
Compulsory key:
studentName = request.form['studentName']
Non-compulsory key:
website = request.form.get('website')
Output:
When we provide both keys:
When compulsory key is wrongly used: (Carefully notice that studentName is misspelled to studentNames)
When non-compulsory key is wrongly used: (Carefully notice that website is misspelled to websites)
Conclusion
In this article we have got to know about the details of what POST request is and also the difference between the compulsory and non-compulsory key. One needs to be careful on using while handling compulsory key, else might lead to API break. The JSON is left to the readers to try and experiment on the same lines as form and query.
Recommended Articles
This is a guide to Flask POST requests. Here we discuss the introduction, how POST requests work in flask? and examples respectively. You may also have a look at the following articles to learn more –