0
0
Rest APIprogramming~5 mins

If-None-Match and 304 responses in Rest API

Choose your learning style9 modes available
Introduction

These help your app avoid downloading data again if it hasn't changed. This saves time and internet data.

When your app asks a server for a file but wants to check if it changed first.
When you want to make your website faster by not reloading images or data if they are the same.
When you build a mobile app that should save battery and data by not downloading repeated info.
When you want to reduce server load by letting it skip sending unchanged data.
When you want to keep your app data fresh but avoid unnecessary downloads.
Syntax
Rest API
Client sends header: If-None-Match: "etag_value"
Server responds:
- 304 Not Modified if data is unchanged
- 200 OK with data if changed

The If-None-Match header contains an ETag value, which is like a fingerprint of the data.

A 304 Not Modified response means the client can use its cached copy.

Examples
The client asks for image.png but only if it has changed since the version with ETag abc123etag.
Rest API
GET /image.png HTTP/1.1
Host: example.com
If-None-Match: "abc123etag"
The server says the image is the same, so the client should use its cached copy.
Rest API
HTTP/1.1 304 Not Modified
The server sends the new image with a new ETag because it has changed.
Rest API
HTTP/1.1 200 OK
ETag: "def456etag"
Content-Type: image/png

(binary image data)
Sample Program

This program makes two requests to a server that supports ETag. The second request uses If-None-Match with the ETag from the first response. If the resource is unchanged, the server replies with 304, telling the client to use cached data.

Rest API
import requests

url = 'https://httpbin.org/etag/abc123etag'

# First request to get the resource and ETag
response1 = requests.get(url)
print('First request status:', response1.status_code)
print('ETag received:', response1.headers.get('ETag'))

# Second request with If-None-Match header
etag = response1.headers.get('ETag')
headers = {'If-None-Match': etag}
response2 = requests.get(url, headers=headers)
print('Second request status:', response2.status_code)
if response2.status_code == 304:
    print('Resource not modified, use cached data')
else:
    print('Resource changed, new data received')
OutputSuccess
Important Notes

ETags are usually strings that uniquely identify a version of a resource.

Not all servers support ETags or 304 responses, so check your API documentation.

Using If-None-Match helps reduce data usage and speeds up your app.

Summary

If-None-Match lets clients ask if data changed by sending an ETag.

304 Not Modified means the data is the same and the client can use its cached copy.

This mechanism saves time, data, and server work by avoiding unnecessary downloads.