Calling a REST endpoint in LWC is similar to how it is handled in Visualforce or in Lightning Aura Components. We can make the callout within our Apex controller, then parse the result in our client side controller, then display the results back to the user within the lightning component.
Everyone knows about the magic eight ball toy, where you shake an eight ball shaped container, ask a question, and receive an answer. I chose the Magic Eight Ball API because there’s no authentication needed, which makes it a rather simple case to work with.
In order to make callouts to external APIs you will need to add the endpoint to your remote site settings in Salesforce.
The apex controller makes a callout to the endpoint and returns the response:
public with sharing class EightBallController {
@AuraEnabled
public static String askEightBall(String question){
HttpRequest req = new HttpRequest();
req.setEndpoint('https://8ball.delegator.com/magic/JSON/' + question);
req.setMethod('GET');
Http http = new Http();
HttpResponse res = http.send(req);
return res.getBody();
}
}
The Javascript controller handles the response from the rest endpoint, while the setBackgroundColor method sets the text color for the answer returned, based on whether the answer was a positive, neutral, or negative answer.
eightBallLwc.js
import { LightningElement, track, api } from 'lwc';
import askEightBall from '@salesforce/apex/EightBallController.askEightBall';
export default class EightBallLwc extends LightningElement {
@track response;
@track error;
@track question;
@api answer;
@track jsonResponse;
@api backgroundColor;
handleChange(event){
this.question = event.target.value;
}
askQuestion() {
askEightBall({ question: this.question })
.then(result => {
this.response = result;
this.jsonResponse = JSON.parse(this.response);
this.answer = this.jsonResponse.magic.answer;
this.type = this.jsonResponse.magic.type;
this.setBackgroundColor();
this.error = undefined;
})
.catch(error => {
this.error = error;
this.response = undefined;
});
}
setBackgroundColor(){
if(this.type === 'Affirmative'){
this.backgroundColor = 'slds-text-color_success';
}
else if(this.type === 'Neutral'){
this.backgroundColor = 'slds-text-color_weak';
}
else{
this.backgroundColor = 'slds-text-color_error';
}
}
}
eightballLwc.html
<template>
<lightning-card title="Magic Eight Ball" icon-name="custom:custom63">
<div class="slds-m-around_medium">
<p class="slds-m-bottom_small">
<lightning-input label="Question" value={question} onchange={handleChange}></lightning-input>
<lightning-button label="Ask" onclick={askQuestion}></lightning-button>
</p>
<p>
<lightning-formatted-text class={backgroundColor} value={answer}></lightning-formatted-text>
</p>
</div>
</lightning-card>
</template>
Github link: https://github.com/tjkingsbury/EightBall