Hello Trailblazers,
In this post, we're going to learn how we can call an External System API from a Lightning Web Component. We're going to use Fetch API which provides an interface for fetching resources. You can consider it as an advanced version of XMLHttpRequest. This API is more powerful and easy to use. The Fetch Web API provides a global fetch() method which can be used in JavaScript to perform any kind of callout to an external system across the network and get the data.
The Promise returned from fetch() method won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, the Promise will resolve normally. The ok property of the response is set to true if the callout is successful and it's set to false if the response isn’t in the range 200–299 and it will only reject on network failure or if anything prevented the request from completing.
Tutorial Video
To learn about fetch(), we're going to create a lwc component to get the details of a user from GitHub as shown below:
Let's have a look at the below code snippets of this component along with the explanation:
githubInfo.html
<template> <lightning-card title="Show Github Stats"> <div class="slds-var-m-around_large"> <!-- * Input Username --> <lightning-layout vertical-align="end"> <lightning-layout-item flexibility="grow"> <lightning-input type="search" value={username} onchange={updateUsername} label="Enter Username"></lightning-input> </lightning-layout-item> <lightning-layout-item class="slds-var-p-left_small"> <lightning-button label="Search" variant="brand" onclick={getGithubStats}></lightning-button> </lightning-layout-item> </lightning-layout> <br /> <!-- * Display User Details --> <div if:true={userPopulated}> <img src={user.image} height="200" width="200" /> <div class="slds-var-p-vertical_xxx-small slds-text-heading_large">{user.name}</div> <br /> <div class="slds-var-p-vertical_xxx-small slds-text-heading_small"><b>Github Profile:</b><a href={githubURL} target="_blank"> {githubURL}</a></div> <div class="slds-var-p-vertical_xxx-small slds-text-heading_small"><b>Website:</b><a href={user.blog} target="_blank"> {user.blog}</a></div> <div class="slds-var-p-vertical_xxx-small slds-text-heading_small"><b>About:</b> {user.about}</div> <div class="slds-var-p-vertical_xxx-small slds-text-heading_small"><b>Repos:</b> {user.repos}</div> <div class="slds-var-p-vertical_xxx-small slds-text-heading_small"><b>Gists:</b> {user.gists}</div> <div class="slds-var-p-vertical_xxx-small slds-text-heading_small"><b>Followers:</b> {user.followers}</div> </div> </div> </lightning-card> </template>
githubInfo.js
import { LightningElement } from 'lwc'; // * GitHub API Base URL const GITHUB_URL = 'https://api.github.com/users/'; export default class GithubInfo extends LightningElement { username; user = {}; // * This method will return if the user object is populated or not get userPopulated() { return this.user && this.user.id; } // * This method will return the github url for the searched user get githubURL() { return 'https://www.github.com/' + this.username; } // * This method will set the username as the user is typing the text in the input field updateUsername(event) { this.username = event.target.value; } // * This method is used to call GitHub API using fetch method and get the user details getGithubStats() { if(this.username) { this.user = {}; fetch(GITHUB_URL + this.username) .then(response => { console.log(response); if(response.ok) { return response.json(); } else { throw Error(response); } }) .then(githubUser => { this.user = { id: githubUser.id, name: githubUser.name, image: githubUser.avatar_url, blog: githubUser.blog, about: githubUser.bio, repos: githubUser.public_repos, gists: githubUser.public_gists, followers: githubUser.followers }; }) .catch(error => console.log(error)) } else { alert('Please specify a username'); } } }
{ "login": "rahulmalhotra", "id": 16497903, "node_id": "MDQ6VXNlcjE2NDk3OTAz", "avatar_url": "https://avatars.githubusercontent.com/u/16497903?v=4", "gravatar_id": "", "url": "https://api.github.com/users/rahulmalhotra", "html_url": "https://github.com/rahulmalhotra", "followers_url": "https://api.github.com/users/rahulmalhotra/followers", "following_url": "https://api.github.com/users/rahulmalhotra/following{/other_user}", "gists_url": "https://api.github.com/users/rahulmalhotra/gists{/gist_id}", "starred_url": "https://api.github.com/users/rahulmalhotra/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/rahulmalhotra/subscriptions", "organizations_url": "https://api.github.com/users/rahulmalhotra/orgs", "repos_url": "https://api.github.com/users/rahulmalhotra/repos", "events_url": "https://api.github.com/users/rahulmalhotra/events{/privacy}", "received_events_url": "https://api.github.com/users/rahulmalhotra/received_events", "type": "User", "site_admin": false, "name": "Rahul Malhotra", "company": null, "blog": "https://rahulmalhotra.github.io/", "location": null, "email": null, "hireable": true, "bio": "I am a developer and I love to Code. I am an independent Salesforce Consultant. Blogger and YouTuber at SFDC Stop (https://www.sfdcstop.com/)", "twitter_username": "rahulcoder", "public_repos": 58, "public_gists": 101, "followers": 71, "following": 2, "created_at": "2015-12-31T07:03:03Z", "updated_at": "2021-07-23T11:30:20Z" }
.then(githubUser => { this.user = { id: githubUser.id, name: githubUser.name, image: githubUser.avatar_url, blog: githubUser.blog, about: githubUser.bio, repos: githubUser.public_repos, gists: githubUser.public_gists, followers: githubUser.followers }; })
githubInfo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> <apiVersion>52.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__HomePage</target> </targets> </LightningComponentBundle>We've exposed this component by setting up isExposed as true and added a single target named as: lightning__HomePage as we want to embed this component in the home page.
Setting up CSP Trusted Sites
Conclusion
fetch('<request-url>', {
method: '<method-name>', // * Like: GET, POST
headers: {
'Content-Type': '<content-type-passed-in-body>' // * Like: application/json, application/x-www-form-urlencoded
},
body: JSON.stringify(data) // * Please note that body data type must match "Content-Type" header
});
No comments:
Post a Comment