How to make a REST callout from LWC component

4:44 PM

 

Here's some sample code demonstrating a basic REST callout from an LWC component using Apex:

LWC component (lwcMyComponent.js):


Explanation:

  1. We import necessary modules: LightningElement for the component base, api and track for reactive properties, and getDataFromApex from the Apex wrapper class (replace with your actual class name).

  2. The component has two reactive properties: data to store the response from the API and error to handle any errors during the callout.

  3. The handleClick method is triggered on a button click or any user interaction.

  4. Inside handleClick, we call the getDataFromApex method from the Apex wrapper. This method should handle the actual REST callout logic.

  5. The call to getDataFromApex uses .then and .catch for handling successful responses and errors respectively.

  6. On success, the response data is stored in the data property.

  7. In case of errors, the error object is stored in the error property for handling in the component template (e.g., displaying an error message).

Apex Wrapper Class (apexCalloutWrapper.cls):


Explanation:

  1. This Apex class exposes an @AuraEnabled method getDataFromApex accessible from LWC.

  2. The method defines the API endpoint URL (replace with your actual URL).

  3. It uses the Http class to create an HttpRequest object specifying the URL and HTTP method.

  4. The h.send method sends the request and captures the response.

  5. On successful response (status code 200), the response body is parsed as JSON and returned as a Map.

  6. In case of errors, an AuraHandledException is thrown with details for handling in LWC.

Note:

  • Remember to replace the placeholder values (URL, Apex method name) with your specific API details and class name.
  • Configure Remote Site Settings in Salesforce to allow access to the external API endpoint.
  • This is a basic example. You might need to modify it based on your API requirements (headers, request body, etc.).

0 comments