# How do Lightning Web Components integrate with external APIs using native fetch and Apex controllers?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, LWC Integration, Fetch API

Read it on the site: https://www.forcechallenges.com/interview-questions/how-do-lightning-web-components-integrate-with-external-apis-using-native-fetch-and-apex-controllers

## Answer

**Basics:** LWC runs in the browser, so it can use `fetch()`, but Salesforce's Content Security Policy only allows connections to approved origins. Apex runs on the server, can store credentials safely, and is not subject to CORS.

**How it works:**
- **Apex route (preferred):** `@AuraEnabled` method does the `Http` callout using `callout:Named_Credential`, returns data; the LWC calls it imperatively or via `@wire` for cacheable reads.
- **Direct fetch route:** add the external origin under Setup > CSP Trusted Sites (directive `connect-src`), and the external server must return proper CORS headers allowing your Salesforce origin. Suitable only for public, non-secret APIs.
- Long-running callouts can use `Continuation` (up to 3 callouts per continuation, timeout up to 120 seconds).

**Advanced / deep dive:** Named Credentials keep secrets and OAuth flows out of code and support per-user or named-principal identity (External Credentials in current versions). `@AuraEnabled(cacheable=true)` methods can perform callouts but cannot do DML; cached responses may be stale, so use `refreshApex`. Limits still apply: 100 callouts per transaction, 120 s cumulative timeout, 6 MB sync heap. A callout cannot occur after uncommitted DML in the same transaction. LWS/Locker restrict some browser APIs. For read-heavy third-party data, consider caching in Platform Cache or storing in custom objects, or use External Objects (OData/Salesforce Connect) to avoid custom code.

**Code / config example:**
```apex
public with sharing class WeatherController {
    @AuraEnabled(cacheable=true)
    public static String getForecast(String city) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:Weather_API/forecast?city=' + EncodingUtil.urlEncode(city, 'UTF-8'));
        req.setMethod('GET');
        req.setTimeout(20000);
        HttpResponse res = new Http().send(req);
        if (res.getStatusCode() != 200) throw new AuraHandledException('Weather service error ' + res.getStatusCode());
        return res.getBody();
    }
}
```
```javascript
import getForecast from '@salesforce/apex/WeatherController.getForecast';
// inside an async method
const data = JSON.parse(await getForecast({ city: this.city }));
```

**Hidden gotchas & must-remember points:**
- CSP Trusted Sites do not fix CORS; the external server must also allow the origin.
- Secrets in LWC JavaScript are visible to every user.
- Cacheable Apex cannot perform DML.
- Callouts must be mocked in tests with `HttpCalloutMock`.
- Remote Site Settings are needed for non-Named-Credential Apex callouts.
- Throw `AuraHandledException` to give the UI a readable message.

**Best practice:** Use Apex plus Named Credentials for anything authenticated; reserve direct fetch for public APIs on trusted sites.

---
Source: ForceChallenges · last updated 2026-11-02
