MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Response Objects, make_response & Cookies0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
2.1Dynamic URLs & Type Converters2.2Handling HTTP Methods (GET, POST, PUT, DELETE)2.3The Flask Request Object & Data Parsing2.4Response Objects, make_response & Cookies2.5Reverse Routing with url_for, Aborts & Error Handlers
HomeTutorialsFlaskResponse Objects, make_response & Cookies
Reverse Routing with url_for, Aborts & Error Handlers

Response Objects, make_response & Cookies

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Whenever a Flask view function completes execution, its return value is converted into an HTTP response object. Understanding how Flask constructs responses—and how to customize status codes, headers, and cookies using make_response—is critical for building robust web applications.


1. What Can a Flask View Return?

Flask accepts several return types from route handler functions:

  1. 1
    A String: Converted to an HTML response (200 OK, Content-Type: text/html).
  2. 2
    A Dict or List: Automatically serialized to JSON (200 OK, Content-Type: application/json).
  3. 3
    A Tuple (body, status): Sets custom status code: return {"error": "Not Found"}, 404.
  4. 4
    A Tuple (body, status, headers): Sets status code and custom HTTP headers.
  5. 5
    A WSGI Response Object: An instance of flask.Response or created via make_response().
1from flask import Flask, jsonify
2 
3app = Flask(__name__)
4 
5# Returning body + status code tuple
6@app.route("/api/v1/created")
7def created_example():
8 return {"message": "Resource created"}, 201
9 
10# Returning body + status + custom headers tuple
11@app.route("/api/v1/custom-header")
12def custom_header():
13 return "OK", 200, {"X-Custom-Engine": "Flask-MSK", "Cache-Control": "max-age=3600"}

2. Using make_response() for Explicit Control

When you need to mutate response headers, set cookies, or manipulate binary data before transmission, wrap the content in make_response():

1from flask import Flask, make_response, render_template
2 
3app = Flask(__name__)
4 
5@app.route("/download/report.csv")
6def download_csv():
7 csv_data = "id,name,score\n1,Alice,98\n2,Bob,85\n3,Charlie,92"
8
9 # Create explicit response object
10 response = make_response(csv_data)
11 response.headers["Content-Type"] = "text/csv; charset=utf-8"
12 response.headers["Content-Disposition"] = "attachment; filename=report_2026.csv"
13 return response

3. Working with HTTP Cookies

Cookies are small text strings stored by the client browser and transmitted in the Cookie header on subsequent requests.

A. Setting a Cookie (response.set_cookie())

Cookies must be attached to an outgoing response object before returning:

1from datetime import datetime, timedelta
2 
3@app.route("/set-preferences")
4def set_preferences():
5 response = make_response({"status": "Preferences saved"})
6
7 # Set cookie with security attributes
8 response.set_cookie(
9 key="theme",
10 value="dark_mode",
11 max_age=timedelta(days=30), # Cookie lifetime
12 secure=True, # Only sent over HTTPS
13 httponly=True, # Inaccessible to JavaScript (XSS defense)
14 samesite="Lax" # CSRF defense
15 )
16 return response

Cookie Security Attributes:

  • httponly=True: Prevents client-side scripts (document.cookie) from reading the cookie, mitigating cross-site scripting (XSS) attacks.
  • secure=True: Instructs the browser to only transmit the cookie over encrypted TLS/HTTPS connections.
  • samesite="Lax" or "Strict": Restricts cross-site cookie transmission to mitigate CSRF attacks.

B. Reading a Cookie (request.cookies)

1from flask import request
2 
3@app.route("/get-preferences")
4def get_preferences():
5 theme = request.cookies.get("theme", default="light_mode")
6 return f"Current active theme: {theme}"

C. Deleting a Cookie (response.delete_cookie())

Deleting a cookie sets its expiration date to the past:

1@app.route("/clear-preferences")
2def clear_preferences():
3 response = make_response({"status": "Preferences cleared"})
4 response.delete_cookie("theme")
5 return response

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What utility function wraps raw return values into an explicit Flask Response object?
Question 2
Why should sensitive cookies always be configured with httponly=True?
Question 3
What does the secure=True cookie attribute guarantee?
Question 4
How do you return a custom HTTP status code and custom header without make_response()?
Question 5
How is an existing client cookie deleted in Flask?
Next Lesson

Reverse Routing with url_for, Aborts & Error Handlers

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
The Flask Request Object & Data ParsingReverse Routing with url_for, Aborts & Error Handlers

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext