Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 72 ยท Routing and Views

Responses, Status Codes and Headers

Learn everything a Flask view can return: strings, dicts, tuples, make_response, jsonify, redirects, status codes, headers and cookies on the response.

A view function has one job: turn a request into a response. A response is three things: a status code (200 OK, 404 Not Found...), a set of headers (Content-Type, Location, Set-Cookie...), and a body (the HTML or JSON the browser shows).

Flask is generous about how you describe that response. You can return a plain string, a dictionary, a tuple, or a full Response object, and Flask converts whatever you return into a real response. In this lesson you'll see every form, learn when to switch from the short forms to make_response, and send redirects, JSON and cookies.

What Flask does with your return value

flowchart TD
    V["view returns a value"] --> S{"which type?"}
    S -->|str| R1["body = text, status 200,<br/>Content-Type text/html"]
    S -->|"dict or list"| R2["converted with jsonify,<br/>Content-Type application/json"]
    S -->|tuple| R3["(body, status, headers)<br/>in any of the allowed shapes"]
    S -->|Response| R4["used as it is"]
    S -->|None| R5["error: view returned nothing"]

make_response is the function Flask itself calls on the value your view returns.

The tuple forms are (body, status), (body, headers) and (body, status, headers). The body can be any of the other types. Returning None (usually because you forgot a return) raises a TypeError.

Python Return values and what they become

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.

Notice that the dict became compact JSON, and that the explicit Content-Type header in the tuple replaced the default text/html. A view that forgets its return ends up as None, which Flask rejects with a TypeError; a visitor would see a plain 500 page.

Status codes

The status code tells the client what happened, so choose it deliberately. The ones you'll use constantly:

Code Name Typical use
200 OK A normal successful response (Flask's default)
201 Created A POST created a resource
204 No Content Success with nothing to send (such as a DELETE)
301 / 302 / 303 / 307 / 308 Redirects Send the client elsewhere
400 Bad Request The client sent something invalid
401 / 403 Unauthorized / Forbidden Not logged in / not allowed
404 Not Found Nothing lives at this URL
405 Method Not Allowed The URL exists but not for this method
500 Internal Server Error Your code failed

Write the number after the body in a tuple, as in return "", 204. Errors are usually raised rather than returned; see Error Handling and Custom Error Pages.

make_response: build the response, then adjust it

Tuples are perfect while you only set a status or a header or two. As soon as you need to change several things, call make_response(). It converts any of the return forms into a Response object you can modify before returning it. The object has .status_code, .headers, .set_cookie(), .set_data() and more.

Python make_response, headers and cookies

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.

A few details from that example:

  • Headers behave like a dictionary, but names are case-insensitive. Assigning replaces the header; response.headers.add("X-Thing", "a") adds another copy.
  • set_cookie() writes a Set-Cookie header. The cookie attributes (httponly, samesite, secure, max_age) matter for security and are explored in Cookies.
  • Content-Disposition: attachment makes a browser download the body instead of displaying it.

jsonify and JSON responses

Returning a dict or list is the shortest way to answer with JSON. jsonify() does the same and also lets you pass keyword arguments, jsonify(ok=True, count=3), or build the response and then adjust it (for example to set a status). Either way the Content-Type is application/json. JSON APIs, error formats and negotiation are the subject of Building JSON APIs.

Flask can serialize the common types: strings, numbers, booleans, None, dicts, lists, datetime, date, uuid.UUID and decimal.Decimal. For your own classes you need to convert them to dicts first (or customize the app's JSON provider).

Redirects

A redirect is a response with a 3xx status and a Location header. The browser immediately requests the new address. Flask's redirect() builds it, and url_for supplies the target.

Python Redirects and the Location header

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.

Choosing the status code:

  • 302 (the default) is a temporary redirect; the browser may switch a POST into a GET.
  • 303 See Other says explicitly "now fetch this URL with GET". It is the right answer after a form POST (the Post/Redirect/Get pattern from Handling HTML Forms).
  • 301 / 308 are permanent redirects that browsers and search engines cache. Use them only for URLs that have really moved. 308 keeps the original method; 301 historically does not.
  • 307 is a temporary redirect that keeps the method.

Never pass a user-supplied URL straight to redirect() (for example from a ?next= parameter). An attacker can send victims to a malicious site through your domain. Check that the target is a local path first; Web Security Essentials shows how.

Customizing the response class and headers for every response

If every response of an app needs the same extra header, you do not edit each view. Flask lets you register a function that runs after each request and receives the response; that is the topic of Hooks, Application Context and g. You can also set app.response_class to your own Response subclass when you need broader control.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A view returns {'id': 17}, 201. What does the client receive?

    A dict body is turned into JSON automatically, and the second tuple item sets the status code.
  2. 2. Which status code best fits redirecting a browser after a successful form POST?

    303 See Other tells the browser to fetch the new URL with GET, which is the Post/Redirect/Get pattern.
  3. 3. When do you need make_response() instead of a plain tuple?

    make_response gives you a Response object whose headers, cookies and data you can adjust before returning it.
  4. 4. What happens if a view function forgets its return statement?

    Returning None is not a valid response, so Flask raises a TypeError, which becomes a 500 when not in testing mode.

Summary

  • Flask converts the return value into a response: str becomes HTML, dict/list become JSON, tuples add a status and/or headers, and a Response is used as is.
  • Use make_response() when you need to change headers, cookies or the status on the response object.
  • jsonify() and returning a dict both produce application/json.
  • redirect(url_for(...), code=...) sends 3xx responses; use 303 after POSTs and 301/308 only for permanent moves.
  • Headers are case-insensitive; assign to replace and headers.add() to append. Cookies are set with response.set_cookie().
  • Never redirect to an unchecked, user-supplied URL.

Next: The Request Object, reading what the client sent.