What is Last-Modified Header in REST API: Explanation and Example
Last-Modified header is an HTTP response header that shows the date and time when the requested resource was last changed. It helps clients know if the resource has been updated since their last request, enabling efficient caching and conditional requests.How It Works
The Last-Modified header tells the client the exact time when the server last changed the resource. Imagine you have a library book that was last updated on a certain date. The Last-Modified header is like a timestamp on that book showing when it was last edited.
When a client (like a web browser or app) asks for the resource again, it can send this timestamp back to the server using the If-Modified-Since header. The server then checks if the resource has changed since that time. If not, it replies with a status saying "Not Modified," so the client can use its saved copy without downloading the whole thing again. This saves time and data.
Example
This example shows a simple HTTP response with a Last-Modified header. It tells the client when the resource was last updated.
HTTP/1.1 200 OK Content-Type: text/html Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT <html> <body> <h1>Hello, world!</h1> </body> </html>
When to Use
Use the Last-Modified header when your server provides resources that change over time, like web pages, images, or data files. It helps clients avoid downloading unchanged data, improving speed and reducing bandwidth.
For example, news websites use it to let browsers know if an article has been updated. APIs use it to let apps check if data has changed before fetching it again. This is especially useful for mobile apps where saving data and battery is important.
Key Points
- Last-Modified shows when a resource was last changed.
- Clients use it to check if they need to download updates.
- Works with
If-Modified-Sinceheader for conditional requests. - Improves performance by reducing unnecessary data transfer.
- Commonly used in web servers and REST APIs.