Integrating external APIs into Salesforce using Lightning Web Components (LWC) is a great way to enhance your Salesforce applications. In this post, we will demonstrate how to fetch movie data from an external API (OMDb API) and display the results in a Lightning Web Component.
Why Use an External API in Salesforce?
Salesforce provides a powerful platform, but sometimes, we need to pull real-time data from external sources. APIs allow us to fetch external data and display it within Salesforce applications seamlessly
Steps to Fetch Movie Data Using LWC
We will use the OMDb API, an open movie database API, to fetch movie details based on a user’s search query.
Step 1: Create an Apex Class to Call the API
We need an Apex controller to make HTTP requests to the OMDb API.
Apex Controller (MovieSearchController.cls
)
public with sharing class MovieSearchController {
@AuraEnabled(cacheable=true)
public static String fetchMovies(String query) {
String apiKey = 'YOUR_API_KEY';
String url = 'https://www.omdbapi.com/?apikey=' + apiKey + '&s=' + EncodingUtil.urlEncode(query, 'UTF-8');
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('GET');
Http http = new Http();
HttpResponse res;
try {
res = http.send(req);
if (res.getStatusCode() == 200) {
return res.getBody();
}
} catch (Exception e) {
System.debug('Error: ' + e.getMessage());
}
return null;
}
}
Step 2: Create the LWC Component
The LWC component will handle user input, call the Apex method, and display the movie results.
JavaScript (movieSearch.js
)
import { LightningElement, track } from 'lwc';
import fetchMovies from '@salesforce/apex/MovieSearchController.fetchMovies';
export default class MovieSearch extends LightningElement {
@track searchQuery = '';
@track movies = [];
@track error;
handleInputChange(event) {
this.searchQuery = event.target.value;
}
handleSearch() {
if (this.searchQuery.trim() !== '') {
fetchMovies({ query: this.searchQuery })
.then(result => {
if (result) {
let parsedResult = JSON.parse(result);
this.movies = parsedResult.Search || [];
this.error = undefined;
} else {
this.movies = [];
this.error = 'No results found.';
}
})
.catch(error => {
this.error = 'Error fetching data';
console.error(error);
});
}
}
}
HTML (movieSearch.html
)
<template>
<lightning-card title="Movie Search" icon-name="utility:search">
<div class="slds-m-around_medium">
<lightning-input type="text" label="Search Movie" value={searchQuery}
onchange={handleInputChange}></lightning-input>
<lightning-button label="Search" variant="brand"
onclick={handleSearch}></lightning-button>
</div>
<template if:true={movies}>
<template for:each={movies} for:item="movie">
<div key={movie.imdbID} class="slds-box slds-m-around_small">
<p><strong>{movie.Title}</strong> ({movie.Year})</p>
<img src={movie.Poster} alt="Movie Poster" width="100">
</div>
</template>
</template>
<template if:true={error}>
<p class="slds-text-color_error">{error}</p>
</template>
</lightning-card>
</template>
Step 3: Deploy and Use the Component
- Deploy the Apex class and LWC component to Salesforce.
- Add the
MovieSearch
component to a Lightning Page in your Salesforce App. - Test the component by searching for a movie title.
MovieSearch
component to a Lightning Page in your Salesforce App.
Post a Comment