Response headers like Cache-Control and ETag help browsers and servers work together to save time and data by reusing stored information.
0
0
Response headers (Cache-Control, ETag) in Rest API
Introduction
When you want to make your website load faster by telling browsers to reuse saved pages.
When you want to check if a file on the server has changed before sending it again.
When you want to reduce the amount of data sent over the internet to save bandwidth.
When you want to improve user experience by loading pages quickly.
When you want to control how long browsers keep a copy of your content.
Syntax
Rest API
Cache-Control: max-age=seconds, no-cache, no-store, public, private
ETag: "unique-identifier"Cache-Control tells the browser how long to keep a copy of the response.
ETag is a unique tag that changes when the content changes, helping browsers check if they need to update.
Examples
This tells the browser to keep the response for 1 hour (3600 seconds) before asking again.
Rest API
Cache-Control: max-age=3600This tells the browser to always check with the server before using the cached response.
Rest API
Cache-Control: no-cache
This is a unique tag that the server sends. The browser can send it back to check if the content changed.
Rest API
ETag: "abc123xyz"This means the response is for a single user only, kept for 10 minutes, with a version tag to check changes.
Rest API
Cache-Control: private, max-age=600 ETag: "v1.0-2024"
Sample Program
This small web server sends data with Cache-Control and ETag headers. If the client already has the same ETag, it returns a 304 status to save data.
Rest API
from flask import Flask, request, make_response app = Flask(__name__) @app.route('/data') def data(): content = 'Hello, this is some data.' etag = 'abc123xyz' # Check if client sent ETag if_none_match = request.headers.get('If-None-Match') if if_none_match == etag: # Content not changed response = make_response('', 304) # 304 Not Modified else: # Send content with headers response = make_response(content) response.headers['Cache-Control'] = 'max-age=60' response.headers['ETag'] = etag return response if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Always use ETag with Cache-Control to make caching smarter.
Setting Cache-Control: no-store means the browser should never save the response.
304 status means 'Not Modified' and tells the browser to use its saved copy.
Summary
Cache-Control tells browsers how long to keep data.
ETag helps check if data changed to avoid sending it again.
Using these headers makes websites faster and saves data.