function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ptepperptepper 

Best practices for caching data (JSON) retrieved via web service callout from Apex?

Hi,

 

I have some code that gets some JSON data from a web service callout, then parses it into a collection (map) or object. I'm wondering if there's a best practice or method people are using to then cache this data for some amount of time so that it's not being retrieved and parsed everytime it is needed.

 

I'm thinking I can create an custom object for this and store the data there, either in a structured format, or serialize it to a JSON string and then store the whole string. I'd store it with a timestamp so that I know when to refresh it.

 

Is there a better way to do this? And by better I mean recommended or faster?

 

thanks

Best Answer chosen by Admin (Salesforce Developers) 
joshbirkjoshbirk

The concept you have laid it seems sound to me.  I would create a custom object which can store the JSON, as well as much meta information to control it logically.  So the timestamp on when the data was retrieved, and perhaps any parameters that might need to be known to recreate the request.

 

After that, you can just do a SELECT for the latest based on timestamp, compare it to the current datetime and either use the existing JSON or call the WS again (replicating params if needed).

 

You could also leverage batch/scheduled Apex to clean up old JSON data if needed.

All Answers

joshbirkjoshbirk

The concept you have laid it seems sound to me.  I would create a custom object which can store the JSON, as well as much meta information to control it logically.  So the timestamp on when the data was retrieved, and perhaps any parameters that might need to be known to recreate the request.

 

After that, you can just do a SELECT for the latest based on timestamp, compare it to the current datetime and either use the existing JSON or call the WS again (replicating params if needed).

 

You could also leverage batch/scheduled Apex to clean up old JSON data if needed.

This was selected as the best answer
ptepperptepper

Thanks