What is Fetch API?
In the example above, lines 1 and 2 are the variable declarations to capture the endpoint and the API method to call. In line 3, we call the fetch method that takes 2 parameters – one is endpoint URL, and the other is the type of method.
The mechanism uses promises to get a response from the API call – this is only available to be used in Lightning Web Components. For this to work, you first need to whitelist the endpoint in the CSP sites setting in setup.
Conclusion on Fetch API
When you need to call an API from the Lightning User Interface in Salesforce, you should use Fetch API instead of writing an Apex Class. As a result, this will make faster developments and you won’t have to worry about writing test classes either.
Interested in more Salesforce Developer posts? Then click the “Salesforce Developer” tag below!
- Salesforce Developers: Difference between fetch API and its method fetch () and directly making a callout from the apex controller in LWC?