Fetch API in Lightning Web Components

By in
2492
Fetch API in Lightning Web Components

What is Fetch API?

Fetch API is used to make callouts using Javascript in Salesforce. Ideally, for backend processing, Apex Callouts are used to handle the response in the background. But when it comes to making API calls from the front end, Fetch API is the way to go.

 

Syntax

 

Explanation

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!

 

Additional Resources

Cover Photo by Jacob Vizek on Unsplash

Leave a reply

Your email address will not be published. Required fields are marked *