HTTP Request and Response with Flask
What is HTTP?
HTTP (Hypertext Transfer Protocol) is communication protocol between client and server. In web development, we basically should know HTTP request and response.
HTTP request and response
HTTP request is client request to server. HTTP response is sever response back to client. For example, if you type url in web browser and enter, browser create http request containing http method, request url, request headers and request body and send it to web browser through the internet. Server get those request and make http response containing http status code, http header and http body and response back to browser. Finally browser show the result.
Quick Start
- create a folder
- in folder create main.py
- create templates folder(jinja template) and create login.html and success.html
main.py
from flask import Flask, request, render_template, redirect, url_forapp = Flask(__name__)
app.config['ENV'] = 'development'# creating route
@app.route("/")
def login():
return render_template("login.html")@app.route("/success")
def success():
return "this is success"if __name__ == "__main__":
app.run(debug=True)
Form request
HTML login form
login.html
<div class="form_container">
<form class="form_2" method="POST" action={{url_for("login")}}>
<div class="input_fields">
<h1>User Login</h1>
<input type="text" name="email" id="name" placeholder="Name" required>
<input type="password" name="password" id="password" placeholder="Password" required>
</div>
<button type="submit" class="outline_md_btn">
Submit
</button>
</form>
</div>
Flask Request Object
from flask import request
Get Requested Client Data
- request methods,
- request headers,
- request url arguments,
- request form inputs
- request files
- request cookies
1. Get request method
Client requested HTTP method. There are five main HTTP methods.
- GET
- POST
- PATCH
- PUT
- DELETE
Catch client requested method with
request.method
main.py
from flask import request@app.route("/", methods=['GET', 'POST'])
def login():
print(request.method)
return render_template("login.html")
In login route, allow both ‘GET’ request and ‘POST’ request.
If ‘GET’ request, return render login.html (jinja template)
If ‘POST’ request, get form data and redirect to success page
@app.route("/", methods=['GET', 'POST'])
def login():
if request.method == 'POST':
print(request.form['email'])
print(request.form['password'])
return redirect(url_for("success"))
return render_template("login.html")
2. Get form data
request.form[' ']
form request (login.html)
<input type="text" name="email" id="name" placeholder="Name" required>
get form email input data (main.py)
request.form['email']
3. Get Request Header
request.headers
request.headers will show the header of HTTP request. User login or sometime request can be passed with user data in headers and we can check like this.
@app.route("/", methods=['GET', 'POST'])
def login():
if request.method == 'POST':
print(request.headers)
print(request.form['email'])
print(request.form['password'])
return redirect(url_for("success"))
return render_template("login.html")
4. Get files from request
request.files['upload']
5. Get cookies from request
request.cookies.get('auth_token')
6. Get request arguments
Url ➜ http://127.0.0.1:5000/success?email=xawyk%40mailinator.com
@app.route("/success")
def success():
print(request.args['email'])
return render_template("success.html")
you can also pass from login route(main.py)
@app.route("/", methods=['GET', 'POST'])
def login():
if request.method == 'POST':
print(request.headers)
print(request.form['email'])
print(request.form['password'])
return redirect(url_for("success", email=request.form['email']))
return render_template("login.html")
@app.route("/success")
def success():
print(request.args['email'])
return f"<h1>{request.args['email']}</h1>"
Flask Response
RETURN value automatically response with response status code and json data (jsonify) or text or html templates.
return template
@app.route("/", methods=['GET', 'POST'])
def login():
return render_template("login.html")
return text
@app.route("/")
def home():
return "home"
return json
@app.route("/users")
def user():
return jsonify({'name': 'sofia', 'email': 'sofia@gmail.com'})
Make response
If you want to modify response data, you can use make_response() as response.
response = make_response(render_template('home.html'))
response.set_cookie('auth_token', encoded_jwt.decode())
return response, 201