0
0
Rest APIprogramming~5 mins

Cache-Control header directives in Rest API

Choose your learning style9 modes available
Introduction

The Cache-Control header tells browsers and servers how to store and reuse web data. It helps make websites faster and saves internet data.

You want to make sure a webpage updates immediately when changed.
You want to let browsers keep a copy of images or files to load faster next time.
You want to prevent sensitive data from being saved in cache.
You want to control how long data stays fresh before checking for updates.
You want to improve website speed by reducing repeated downloads.
Syntax
Rest API
Cache-Control: directive1, directive2, ...

Directives are instructions like no-cache or max-age=3600.

Multiple directives are separated by commas.

Examples
Tells the browser to always check with the server before using cached data.
Rest API
Cache-Control: no-cache
Allows the browser to use cached data for 3600 seconds (1 hour) without checking the server.
Rest API
Cache-Control: max-age=3600
Prevents the browser and any caches from storing the response at all.
Rest API
Cache-Control: no-store
Marks the response as public and cacheable for 24 hours.
Rest API
Cache-Control: public, max-age=86400
Sample Program

This simple web server sends a Cache-Control header telling browsers to keep the page for 60 seconds before checking for updates.

Rest API
from flask import Flask, make_response

app = Flask(__name__)

@app.route('/')
def home():
    response = make_response('Hello, world!')
    response.headers['Cache-Control'] = 'public, max-age=60'
    return response

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

no-cache means "check with server before using cached data" but still stores it.

no-store means "do not save this data anywhere" for privacy or security.

max-age sets how many seconds the data is fresh and can be reused without checking.

Summary

Cache-Control header controls how browsers and servers save and reuse web data.

Use directives like no-cache, no-store, and max-age to set caching rules.

Proper caching makes websites faster and saves data.