Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 72 ยท Routing and Views

The Request Object

Learn how to read everything a client sends to a Flask view: query strings, form fields, JSON bodies, headers, cookies, uploaded files, and how the request context works.

A response is only half of the conversation. Before your view can answer, it needs to know what was asked: which page of results, which search term, what the user typed into a form, which JSON the mobile app posted. Flask gathers all of that into one object, flask.request.

You import it like a normal variable (from flask import request), yet it holds different data for every visitor. That works because request is a proxy to the request that is currently being handled. This lesson walks through each place data can hide in a request, then explains the context machinery that makes the proxy safe.

Where data lives in a request

flowchart LR
    C["Client request"] --> L["Request line<br/>method + path + query"]
    C --> H["Headers<br/>cookies, content type, ..."]
    C --> B["Body<br/>form, JSON or files"]
    L --> A1["request.method<br/>request.path<br/>request.args"]
    H --> A2["request.headers<br/>request.cookies"]
    B --> A3["request.form<br/>request.get_json()<br/>request.files"]

Each part of an HTTP request has its own attribute on request.

Attribute What it holds
request.method "GET", "POST" and so on
request.path, request.url The path, or the full URL
request.args The query string (?page=2&tag=a&tag=b)
request.form Fields from an HTML form body
request.get_json() A parsed JSON body
request.files Uploaded files
request.headers All request headers
request.cookies Cookies the browser sent back

Query strings: request.args

request.args is a read-only, dictionary-like object (a MultiDict) built from the part of the URL after the ?. Everything in it is a string, so convert and give defaults at the point of reading. args.get(name, default, type=...) does both in one call and falls back to the default if the conversion fails.

Python Query strings, form fields and headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three habits to take from this:

  • Use .get() instead of request.args["q"]. Indexing a missing key raises BadRequestKeyError, which Flask turns into a 400 response. That is sometimes what you want, but it should be a decision.
  • A name can appear several times. .get() returns the first value and .getlist() returns all of them.
  • request.form and request.args are different dictionaries. A POST to /search?q=hello carries q in the URL and name in the body.

Form handling gets a complete treatment in Handling HTML Forms.

JSON bodies

APIs post application/json. request.get_json() parses the body and returns a Python object. By default, if the Content-Type is not JSON, Flask answers with 415 Unsupported Media Type, and if the body is malformed it answers 400 Bad Request. Two options soften that: silent=True returns None instead of raising, and force=True ignores the content type.

Python Reading JSON, cookies and files

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The test client mirrors what a browser does: json= sends a JSON body with the right header, data={...} sends a form, and a (file_object, filename) tuple makes a file upload. We use this style in every example, because it needs no server. File handling (saving, size limits, safe names) is in File Uploads.

request.json is a shortcut for request.get_json() that raises the same errors. Prefer the method call in new code; it makes the options (silent, force) easy to add.

Headers and other metadata

request.headers is case-insensitive, so request.headers["content-type"] and request.headers["Content-Type"] are the same. A few more attributes that come up often:

  • request.host and request.scheme for the address the client used.
  • request.remote_addr for the client address. Behind a proxy this is the proxy's address unless you configure ProxyFix (see Deployment).
  • request.content_type, request.content_length, request.mimetype.
  • request.accept_languages and request.accept_mimetypes, for content negotiation.
  • request.is_json, request.is_secure.
  • request.view_args and request.endpoint, the matched URL variables and endpoint name.

Never trust any of these values blindly: headers and cookies are sent by the client and can be forged.

The request context

If request is a global, how do two simultaneous visitors not see each other's data? Flask pushes a request context when it begins handling a request and pops it when the response is done. The request and session names are proxies that look up the context belonging to the current thread, greenlet or async task.

sequenceDiagram
    participant S as WSGI server
    participant F as Flask
    participant V as Your view
    S->>F: call app with environ
    F->>F: push app context + request context
    F->>V: dispatch to matching view
    V-->>F: return value
    F->>F: build response, pop contexts
    F-->>S: response

The proxies only work between "push" and "pop".

Outside that window request has no value to point at. You can see this, and you can fake a request with test_request_context():

Python The request context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

test_request_context is also handy in the Python shell and in unit tests for helper functions that read request. When you want to run a whole request through the app including routing, use the test client instead. The relationship between the two contexts (app and request) is the subject of How a Request Flows Through Flask.

Do not store request or anything derived from a lazy proxy in a background thread or a long-lived object. Copy out the plain values you need (for example request.args.get("q")) before handing work elsewhere.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which expression safely reads ?page=2 as an integer with a default of 1?

    args.get with a default and a type converts the value and falls back to the default if it is missing or invalid.
  2. 2. A client posts a form to /save?draft=1. Where do the form fields and draft appear?

    The query string goes into request.args and the body into request.form.
  3. 3. What does request.get_json() do by default when the Content-Type is not JSON?

    Use silent=True to get None instead, or force=True to ignore the content type.
  4. 4. Why can request be a global variable without mixing up visitors?

    Request contexts are tracked per thread, greenlet or task, and the proxy resolves to the active one.

Summary

  • request is a context-bound proxy; it exists only while a request is being handled (or inside test_request_context).
  • Query string: request.args. Form body: request.form. JSON: request.get_json(). Files: request.files. Headers and cookies: request.headers, request.cookies.
  • Prefer .get() with defaults and type= over indexing; use .getlist() for repeated names.
  • get_json() returns 415 for the wrong content type and 400 for malformed JSON unless you pass silent=True or force=True.
  • Everything in a request comes from the client; validate it before you use it.
  • The test client builds requests for you with data=, json=, headers= and set_cookie.

Next: Error Handling and Custom Error Pages, what to do when something goes wrong.