Imagine you are retrieving an API key/Bearer token from an external system to make a new callout to another external system. But there is one issue: you cannot determine when the new callout will take place, so you need to store the token value somewhere in your org for later use. Probably you will be thinking of storing it in your custom object or custom metadata. But creating a separate object/metadata for such a case may not be an efficient way. Then what? I think this is where Platform Cache helps you. Platform Cache provides temporary storage for such data in such cases. You can set up your platform cache by following the steps outlined in this trailhead. Here, I will explain how you can use the platform cache for this use case: I expect that you have already configured your platform cache in your dev org. Now suppose, you receive a bearer token from one API to pass into another callout after sometime, so you can store that access token in the Platform cache and avoid the hassle of creating a separate custom object/metadata or Custom Setting (Although you cannot update a Custom Metadata/Setting using Apex code).
The Trailhead referenced in this article is crucial for understanding and setting up the platform cache. If you have not gone through the trailhead, then stop here and complete the trailhead first.
How to Use Platform Cache to Fetch a Bearer Token
How to fetch a bearer token and save it into the Platform cache using Apex:
Now, you can fetch the bearer token from the Platform cache and use it in your next callout with the following code:
Remember, Platform Cache provides temporary storage, and data can be evicted from it because of memory pressure. Platform Cache does not guarantee the determined lifetime of the value stored; therefore, it is better not to store any value with an extended validity or sensitive information.
Although platform cache is used to improve performance by evading unnecessary repeated API calls, there are a few concerns about using the Platform cache.
When Not to Use Platform Cache
- If the value contains sensitive information
- If the value has to be stored for the long term
- If you need environment-specific secret management
References
External System used: https://www.reqres.in
Technology used: Salesforce
Source: Read MoreÂ