0
0
Rest APIprogramming~5 mins

Validation-based caching in Rest API

Choose your learning style9 modes available
Introduction

Validation-based caching helps your app save time and data by checking if information has changed before downloading it again.

When you want to avoid downloading the same data again if it hasn't changed.
When your app talks to a server and you want to save internet data.
When you want your app to load faster by using saved data if possible.
When you want to reduce the load on the server by not asking for data too often.
Syntax
Rest API
GET /resource HTTP/1.1
Host: example.com
If-None-Match: "etag_value"

Response:
HTTP/1.1 304 Not Modified

or
HTTP/1.1 200 OK
Content-Type: application/json
ETag: "etag_value"

{...data...}

The client sends an If-None-Match header with the ETag value it has.

The server replies with 304 Not Modified if data is unchanged, or 200 OK with new data and a new ETag if changed.

Examples
The client asks for user 123 but only if the data changed since ETag "abc123".
Rest API
GET /users/123 HTTP/1.1
Host: api.example.com
If-None-Match: "abc123"
The server says the data is the same, so the client can use its saved copy.
Rest API
HTTP/1.1 304 Not Modified

The server sends new data with a new ETag "def456" because the data changed.
Rest API
HTTP/1.1 200 OK
Content-Type: application/json
ETag: "def456"

{"name": "Alice", "age": 30}
Sample Program

This program first gets data from the server and saves the ETag. Then it asks again with the ETag to see if data changed. If not, it uses cached data.

Rest API
import requests

url = 'https://api.example.com/data'

# First request, no ETag yet
response = requests.get(url)
print('Status:', response.status_code)
print('Data:', response.text)

# Save ETag from response
etag = response.headers.get('ETag')

# Second request with ETag to check if data changed
headers = {'If-None-Match': etag} if etag else {}
response2 = requests.get(url, headers=headers)
print('Status:', response2.status_code)
if response2.status_code == 304:
    print('Data not changed, use cached data')
else:
    print('New data:', response2.text)
OutputSuccess
Important Notes

ETag is a unique identifier for the version of the data.

304 means 'Not Modified' and tells the client to use its saved data.

Validation-based caching saves bandwidth and speeds up apps.

Summary

Validation-based caching checks if data changed before downloading again.

Clients send ETag with If-None-Match header to ask if data is new.

Servers reply with 304 if data is unchanged, or 200 with new data and ETag if changed.