0
0
Rest APIprogramming~5 mins

ETag for conditional requests in Rest API

Choose your learning style9 modes available
Introduction

ETags help servers and clients check if a resource has changed. This saves time and data by avoiding sending the same data again.

When you want to reduce data usage by sending data only if it changed.
When building a web API that needs to tell clients if data is fresh or stale.
When you want faster responses by telling clients to use cached data if possible.
When you want to improve user experience by loading data faster.
When you want to save server resources by not sending unchanged data.
Syntax
Rest API
HTTP/1.1 200 OK
ETag: "unique-resource-version"

{resource data}

Client sends:
If-None-Match: "unique-resource-version"

The server sends an ETag header with a unique value for the resource version.

The client sends If-None-Match with the ETag value to check if the resource changed.

Examples
The server sends the resource with an ETag value "abc123".
Rest API
Server response:
HTTP/1.1 200 OK
ETag: "abc123"

{"name": "Alice"}
The client asks for the resource only if it changed from version "abc123".
Rest API
Client request:
GET /user/1 HTTP/1.1
If-None-Match: "abc123"
The server tells the client the resource is unchanged, so no data is sent.
Rest API
Server response if resource unchanged:
HTTP/1.1 304 Not Modified
Sample Program

This Flask app returns user data with an ETag header. If the client sends the same ETag, it returns 304 Not Modified.

Rest API
from flask import Flask, request, jsonify, make_response

app = Flask(__name__)

# Sample resource data and version
resource_data = {"name": "Alice"}
resource_etag = 'abc123'

@app.route('/user/1')
def get_user():
    client_etag = request.headers.get('If-None-Match')
    if client_etag == resource_etag:
        # Resource not changed
        return '', 304
    # Resource changed or no ETag sent
    response = make_response(jsonify(resource_data))
    response.headers['ETag'] = resource_etag
    return response

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

ETag values should be unique and change whenever the resource changes.

304 Not Modified responses have no body, saving bandwidth.

ETags help browsers and clients cache data efficiently.

Summary

ETags let servers tell clients if data changed.

Clients send ETags back to check freshness.

304 responses avoid sending unchanged data.