python-backend
/

Flask Request & Response – Handling Web Traffic

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

python-backend

Flask Request & Response – Handling Web Traffic

The Flask Request-Response Cycle

In Flask, every time a client visits a URL, Flask creates a Request object containing all the information sent by the browser. Once your function processes the logic, it must return a Response object. Understanding how to extract data from the request and format the response is the core of API development.

  1. The Request Object

The request object is global within the context of a function call. It allows you to access URL parameters, form data, JSON payloads, and HTTP headers.

PythonRead-only
1
from flask import request

@app.route('/login', methods=['POST'])
def login():
    # Get JSON data from a POST request
    data = request.get_json()
    username = data.get('username')

    # Get Query Parameters from URL (?source=mobile)
    source = request.args.get('source')

    # Access Headers
    user_agent = request.headers.get('User-Agent')

    return f"Hello {username} from {source}"

  1. Creating a Response

By default, if you return a string or a dictionary, Flask automatically converts it into a response with a 200 OK status. However, for APIs, you often need to set custom status codes or headers using make_response or by returning a tuple.

PythonRead-only
1
from flask import make_response, jsonify

@app.route('/error')
def custom_error():
    # Option A: Simple Tuple (Body, Status, Headers)
    # return jsonify({"error": "Not Found"}), 404, {"X-Custom-Header": "Value"}

    # Option B: make_response for more control
    res = make_response(jsonify({"msg": "Auth Failed"}))
    res.status_code = 401
    res.headers['WWW-Authenticate'] = 'Basic realm="Login Required"'
    return res

Common Request Attributes

AttributeDescriptionExample Use Case
request.argsURL Query parametersFiltering search results (?q=python)
request.formForm data from POSTTraditional HTML form submissions
request.jsonParsed JSON bodyModern REST API payloads
request.filesUploaded filesHandling profile picture uploads
request.methodHTTP MethodChecking if request is GET or POST
request.cookiesBrowser cookiesReading session IDs

Visualizing the Flow

The flow starts at the client, passes through Flask's routing middleware, hits your view function, and returns through the response pipeline.

Test Your Knowledge

Q1
of 3

Which object is used to access the JSON data sent in a POST request?

A
request.json
B
response.json
C
flask.data
D
request.query
Q2
of 3

How do you return a 201 Created status code with a JSON response?

A
return jsonify(data).status(201)
B
return jsonify(data), 201
C
return 201, jsonify(data)
D
make_response(201, data)
Q3
of 3

Where are URL parameters like ?id=5 stored in the request object?

A
request.form
B
request.params
C
request.args
D
request.values

Frequently Asked Questions

What is the difference between request.args and request.form?

request.args contains parameters from the URL (query string). request.form contains data sent in the body of a POST request via an HTML form.

How do I set a cookie in the response?

You must use make_response() to get a response object, then call res.set_cookie('key', 'value') before returning it.

What happens if I don't return anything from a route?

Flask will raise a TypeError. A route must always return a string, a dictionary, a tuple, or a valid Response object.

Previous

flask templates

Next

flask rest api

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.