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:
We import necessary modules:
LightningElement
for the component base,api
andtrack
for reactive properties, andgetDataFromApex
from the Apex wrapper class (replace with your actual class name).The component has two reactive properties:
data
to store the response from the API anderror
to handle any errors during the callout.The
handleClick
method is triggered on a button click or any user interaction.Inside
handleClick
, we call thegetDataFromApex
method from the Apex wrapper. This method should handle the actual REST callout logic.The call to
getDataFromApex
uses.then
and.catch
for handling successful responses and errors respectively.On success, the response data is stored in the
data
property.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:
This Apex class exposes an
@AuraEnabled
methodgetDataFromApex
accessible from LWC.The method defines the API endpoint URL (replace with your actual URL).
It uses the
Http
class to create anHttpRequest
object specifying the URL and HTTP method.The
h.send
method sends the request and captures the response.On successful response (status code 200), the response body is parsed as JSON and returned as a Map.
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