0
0
Rest APIprogramming~5 mins

Expiration-based caching in Rest API

Choose your learning style9 modes available
Introduction

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.

When you want to speed up repeated requests for the same data in a web app.
When you want to reduce server load by not fetching unchanged data too often.
When you want to make sure users see updated information after a certain time.
When you want to save bandwidth by avoiding unnecessary data transfers.
When you want to improve user experience by showing cached content instantly.
Syntax
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.

Examples
Cache the response for 60 seconds before it expires.
Rest API
Cache-Control: max-age=60
Do not cache the response; always check with the server.
Rest API
Cache-Control: max-age=0, no-cache
Cache the response for 1 hour and allow shared caches (like proxies) to store it.
Rest API
Cache-Control: max-age=3600, public
Sample Program

This 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.

Rest API
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)
OutputSuccess
Important Notes

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.

Summary

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.