Caching can be done with the Pro Plugin, which adds a field within each endpoint to easily set the cache time of any endpoint.
How to cache API calls
Start by installing the Pro Plugin and a new Cache Time field will be added to each endpoint within the settings of your API(s). Add your required cache time in seconds and then save the endpoint. Simple as that!
Once caching is setup for an endpoint, the plugin will store the results of your API requests using WordPress transients. Caching will only work for GET requests and it will not cache if there are error messages. It will only cache successful GET requests returned from your API and will also include headers as well as the body in the saved data.
Caching dynamic query variables
Within the Pro plugin, there is the option to use dynamic variables within the query string.
If you set the cache time for an endpoint that is using these dynamic variables, the plugin will dynamically cache the calls to this endpoint. Meaning that a cache will be created for each dynamic variable that is passed to the API. This is important to understand if using this feature and it allows you to continue to use the dynamic variables the way they are intended – to be dynamic – whilst also being able to be cached independently.
A quick example: if you send a query variable such as ?foo=bar and a second query string with ?foo=123, the plugin will pick up that these are different and will create a cache for each one.
Setting the cache time
As mentioned above, the cache time is in seconds. Here are some common times in seconds to help with your caching and to avoid pulling out the calculator:
- Cache for 1 minute = 60 (duh)
- Cache for 2 minutes = 120
- Cache for 5 minutes = 300
- Cache for 10 minutes = 600
- Cache for 15 minutes = 900
- Cache for 30 minutes = 1800
- Cache for 1 hour = 3600
- Cache for 2 hours = 7200
- Cache for 12 hours = 43200
- Cache for 24 hours = 86400