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:
LightningElementfor the component base,apiandtrackfor reactive properties, andgetDataFromApexfrom the Apex wrapper class (replace with your actual class name).The component has two reactive properties:
datato store the response from the API anderrorto handle any errors during the callout.The
handleClickmethod is triggered on a button click or any user interaction.Inside
handleClick, we call thegetDataFromApexmethod from the Apex wrapper. This method should handle the actual REST callout logic.The call to
getDataFromApexuses.thenand.catchfor handling successful responses and errors respectively.On success, the response data is stored in the
dataproperty.In case of errors, the error object is stored in the
errorproperty for handling in the component template (e.g., displaying an error message).
Apex Wrapper Class (apexCalloutWrapper.cls):
Explanation:
This Apex class exposes an
@AuraEnabledmethodgetDataFromApexaccessible from LWC.The method defines the API endpoint URL (replace with your actual URL).
It uses the
Httpclass to create anHttpRequestobject specifying the URL and HTTP method.The
h.sendmethod 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
AuraHandledExceptionis 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.).





