Rest API Callout Service Example
public class RestAPIDisplayValue {
@AuraEnabled(cacheable=true)
public static String getRestAPI(Integer id){
Http htp = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setHeader('Content-Type', 'application/json');
req.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
HttpResponse res = htp.send(req);
String strReq = '';
if(res.getStatusCode() == 200){
map<String,object> result = (Map<String,object>)JSON.deserializeUntyped(res.getBody());
map<String,object> animals = (Map<String,object>) result.get('animal');
strReq = String.valueOf(animals.get('name'));
System.debug('datadisplaid'+strReq);
}
return strReq;
}
}
RestAPI DisplayedRecords
----------------------------
import { LightningElement,track } from 'lwc';
import getrestapi from '@salesforce/apex/RestAPIDisplayValue.getRestAPI';
export default class RestAPIDetail extends LightningElement {
@track animalId;
@track animalName;
handleInputChange(event){
this.animalId = event.target.value
}
getRestapiDetail(){
getrestapi({
id: this.animalId
})
.then(result => {
console.log('result'+result);
this.animalName = result;
})
.catch(error,{
});
}
}
Displayed we get response
------------------------
<template>
<lightning-card variant="Narrow" title="Animal Locator" icon-name="utility:animal_and_nature">
<div>
<lightning-input label="Enter Animal ID" type="number" value={animalId} onchange={handleInputChange}></lightning-input>
<lightning-button variant="base" label="Get Animal Name" onclick={getRestapiDetail}></lightning-button>
<div if:true={animalName}>
<p>Animal Name: {animalName}</p>
</div>
</div>
</lightning-card>
</template>
No comments:
Post a Comment