Documentation Index
Fetch the complete documentation index at: https://mintlify.com/trailheadapps/lwc-recipes/llms.txt
Use this file to discover all available pages before exploring further.
Overview
ThemiscRestApiCall component demonstrates how to call external REST APIs using the browser’s native Fetch API. This example queries the Google Books API to search for books.
Source Component
- miscRestApiCall - Makes REST API calls using fetch()
Key Features
- Native Fetch API usage
- Async/await error handling
- Loading state management
- CSP trusted sites configuration
Implementation
Basic REST Call
Use the Fetch API with async/await:CSP Configuration
Before making external API calls, you must add the base URL to CSP Trusted Sites in Salesforce Setup. Navigate to Setup > Security > CSP Trusted Sites and add the domain (e.g.,
https://www.googleapis.com/).Adding a Trusted Site
- Go to Setup > Security > CSP Trusted Sites
- Click New Trusted Site
- Enter the base URL (e.g.,
https://www.googleapis.com) - Enable the appropriate directives (Connect, Font, Img, Media, Style)
- Save
Error Handling
The Fetch API doesn’t automatically throw errors for HTTP error responses. Always check theok property:
Try-Catch-Finally Pattern
Loading States
Display a spinner while waiting for the API response:POST Requests
Make POST requests by adding options to fetch():Headers and Authentication
Add custom headers for authentication:For Salesforce API calls, use Apex methods with
@AuraEnabled(cacheable=true) instead of direct REST calls. The Fetch API is best for external third-party APIs.Best Practices
- Always add external domains to CSP Trusted Sites
- Check
response.okbefore processing data - Use try-catch-finally for proper error handling
- Manage loading states for better UX
- Clean up state in the
finallyblock - Use Apex for Salesforce data operations
Source Files
force-app/main/default/lwc/miscRestApiCall/
