Expiration-based caching helps store data temporarily so your app can use it quickly without asking the server every time. It automatically removes old data after a set time to keep things fresh.
Expiration-based caching in Rest API
Cache-Control: max-age=<seconds>
This header tells the browser or client how long to keep the cached data before asking the server again.
max-age is the number of seconds the data is fresh.
Cache-Control: max-age=60Cache-Control: max-age=0, no-cacheCache-Control: max-age=3600, publicThis simple Flask app returns JSON data with a Cache-Control header telling clients to cache the response for 10 seconds. If you request the endpoint multiple times within 10 seconds, the client can use the cached data instead of asking the server again.
from flask import Flask, jsonify, make_response import time app = Flask(__name__) @app.route('/data') def data(): response = make_response(jsonify({'message': 'Hello, world!', 'time': time.time()})) response.headers['Cache-Control'] = 'max-age=10' return response if __name__ == '__main__': app.run(debug=False)
Expiration-based caching works best when data changes predictably or infrequently.
Clients may ignore caching headers, so always validate important data on the server.
Use short expiration times for fast-changing data to avoid showing stale info.
Expiration-based caching stores data temporarily to speed up repeated requests.
Use the Cache-Control: max-age header to set how long data stays fresh.
This method helps reduce server load and improve user experience by avoiding unnecessary data fetching.