13 Tweets Jan 31, 2023
How to cache REST API response.
Thread 🧡
Every REST API is supposed to be cacheable as it is one of the REST API constraints.
Caching simply means storing responses in the cache memory to reduce bandwidth and improve API performance.
Whenever a user initiates a request to the server, it passes through the cache to check whether cache memory has a freshly stored response.
If so, it satisfies the request. Else passes to the server.
GET HTTP requests are generally cacheable by default.
POST requests can be made cacheable with the help of `Cache-Control` HTTP header.
DELETE is not a cacheable HTTP request at all.
The HTTP Cache-Control header has several directives.
These directives define the cache conditions, for example, how long it's cached, who can cache it, etc.
Here is each directive explained:
1. Cache-Control: max-age
The max-age directive defines the time it takes for a cached resource to expire. Once expired, a browser must request the resource again from the server.
The time is always defined in seconds. E.g.:
cache-control: max-age=500
2. Cache-Control: no-store
The 'no-store' response directive indicates that the cache should not store this response.
The 'no-store' request directive prevents the server from storing the request or corresponding responses.
3. Cache-Control: no-cache
The browser revalidates the resource against the origin server on every request before caching.
The browser will cache if a 304 status returns (304: no change).
4. Cache-Control: public
The response can be stored in a shared cache.
Even if a page uses HTTP authentication or the HTTP response code is not usually cacheable, it will still be cached using the β€˜public’ header.
5. Cache-Control: private
"private" indicates that a shared cache must not store a response, as it is only intended for a single user. The response can be stored only in a private cache.
This is useful for personal information such as banking details.
6. Cache-Control: must-revalidate
A cache must revalidate stale (expired) resources before returning them to the client.
This directive prevents the use of stale resources.
With that said, that's pretty much it for this thread.
Check out RapidAPI.com for everything related to an API:
β€’ Design
β€’ Develop
β€’ Test
β€’ Publish
β€’ Monitor
β€’ and much more

Loading suggestions...