Make HTTP Callout Request in LWC Salesforce

by Rijwan Mohmmed
0 comment
make-http-callout-request-in-lwc-salesforce-techdicer

Hello friends, today we will discuss Make HTTP Callout Request in LWC Salesforce. Get Weather Info in LWC fetch method. Weather info is a very necessary thing right now so we can check the temperature, pressure, humidity, etc. There are paid/non-paid multiple APIs for Weather info on the internet. So we can easily get info by putting city information.

Also, check this: Filter Search in LWC Lightning Datatable

make-http-callout-request-in-lwc-salesforce-output-techdicer

Key Highlights :

  1. Lightning web component for set and displaying weather info.
  2. Rest API callout in LWC Fetch API .
  3. Validation on the LWC field before submitting.

Process & Code :

Step 1: In this step, we set up OpenWeatherMap account. You can log in via Gmail. After creating an account go to your profile name and click API Keys. Set and copy the API key for further.

Step 2: Set up the CSP Trusted Sites of this Endpoint URL GO Setup > CSP Trusted Sites > Click New Trusted Site and create new records by filling in Endpoint and name. EndPoint ==>

https://api.openweathermap.org/data/2.5/weather

Step 3: In this step, we will create a Lightning Web Component so we can feed the data of city zip code and Country and show it on the same page after submitting. We also show an error message toast if the country code or zip code is wrong. Here we have to fetch the method to submit our HTTP Callout and get data.

WeatherLwcComponent.Html :

<template>
    <!-- loader -->
    <div if:true={showSpinner}>
        <lightning-spinner
            alternative-text="Loading..." variant="brand">
        </lightning-spinner>
    </div>
    <!------------->
 
    <div class="slds-tabs_card">
        <div class="slds-page-header">
            <div class="slds-page-header__row">
                <div class="slds-page-header__col-title">
                    <div class="slds-media">
                        <div class="slds-media__figure">
                            <span class="slds-icon_container slds-icon-standard-opportunity">
                                 <lightning-icon icon-name="standard:recipe" alternative-text="recipe" title="recipe"></lightning-icon>
                            </span>
                        </div>
                        <div class="slds-media__body">
                            <div class="slds-page-header__name">
                                <div class="slds-page-header__name-title">
                                    <h1>
                                        <span>Call Parent Method From Child Component LWC</span>
                                        <span class="slds-page-header__title slds-truncate" title="Recently Viewed">TechDicer</span>
                                    </h1>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div> <br/>
 
    <lightning-card title="City Info to Fetch Weather" icon-name="standard:address">
        <div class="slds-var-p-around_small">
            <lightning-layout multiple-rows>
                <lightning-layout-item padding="around-small" size="12" medium-device-size="12" large-device-size="12">
                    <lightning-combobox name="country" class="fieldvalidate"
                                        label="Country Code" options={countryOptions} required>
                    </lightning-combobox>
                    <lightning-input name="pincode" class="fieldvalidate" type="number"
                                     label="Pin/Zip Code" min="1000" max="999999"
                                     message-when-range-overflow="Please enter a correct pincode"
                                     message-when-range-underflow="Please enter a correct pincode/Zipcode" required>
                    </lightning-input>
                </lightning-layout-item>
                <lightning-layout-item size="12" class="slds-var-p-top_small">
                    <lightning-button class="slds-align_absolute-center" variant="brand" label="Submit"
                        onclick={handleValidation}></lightning-button>
                </lightning-layout-item>
            </lightning-layout>
        </div>
    </lightning-card><br/>
    <lightning-card title="City Weather Info" icon-name="utility:salesforce1">
        <div class="slds-var-p-around_small">
            <div class="slds-p-horizontal_small">
                <div class="slds-form" role="list">
                    <div class="slds-form__row">
                        <div class="slds-form__item" role="listitem">
                            <div
                                class="slds-form-element slds-form-element_edit slds-form-element_readonly slds-form-element_stacked slds-hint-parent">
                                <span class="slds-form-element__label">City Name</span>
                                <div class="slds-form-element__control">
                                    <div class="slds-form-element__static">
                                        {result.name}
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="slds-form__item" role="listitem">
                            <div
                                class="slds-form-element slds-form-element_edit slds-form-element_readonly slds-form-element_stacked slds-hint-parent">
                                <span class="slds-form-element__label">City Temperature</span>
                                <div class="slds-form-element__control">
                                    <div class="slds-form-element__static">
                                        {result.temp} celsius
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
 
                    <div class="slds-form__row">
                        <div class="slds-form__item" role="listitem">
                            <div
                                class="slds-form-element slds-form-element_edit slds-form-element_readonly slds-form-element_stacked slds-hint-parent">
                                <span class="slds-form-element__label">Sunrise</span>
                                <div class="slds-form-element__control">
                                    <div class="slds-form-element__static">
                                        {result.sunrise}
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="slds-form__item" role="listitem">
                            <div
                                class="slds-form-element slds-form-element_edit slds-form-element_readonly slds-form-element_stacked slds-hint-parent">
                                <span class="slds-form-element__label">Sunset</span>
                                <div class="slds-form-element__control">
                                    <div class="slds-form-element__static">
                                        {result.sunset}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
 
                    <div class="slds-form__row">
                        <div class="slds-form__item" role="listitem">
                            <div
                                class="slds-form-element slds-form-element_edit slds-form-element_readonly slds-form-element_stacked slds-hint-parent">
                                <span class="slds-form-element__label">Pressure</span>
                                <div class="slds-form-element__control">
                                    <div class="slds-form-element__static">
                                        {result.pressure}
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="slds-form__item" role="listitem">
                            <div
                                class="slds-form-element slds-form-element_edit slds-form-element_readonly slds-form-element_stacked slds-hint-parent">
                                <span class="slds-form-element__label">Humidity</span>
                                <div class="slds-form-element__control">
                                    <div class="slds-form-element__static">
                                        {result.humidity}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </lightning-card>
</template>

WeatherLwcComponent.JS :

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class WeatherLwcComponent extends LightningElement {
    countryOptions = [
        { "label": "India", "value": "IN" },
        { "label": "USA", "value": "US" },
        { "label": "Turkey", "value": "TR" },
        { "label": "Australia", "value": "AU" }
    ];

    countryCode;
    zipCode;
    showSpinner = false;
    result = {};
    //check field validation
    handleCheckValidation() {
        let isValid = true;
        let inputFields = this.template.querySelectorAll('.fieldvalidate');
        inputFields.forEach(inputField => {
            if(!inputField.checkValidity()) {
                inputField.reportValidity();
                isValid = false;
            }

            if(inputField.name == "country"){
                this.countryCode = inputField.value;
            } else if(inputField.name == "pincode"){
                this.zipCode = inputField.value;
            }
        });
        return isValid;
    }

    handleValidation(event) {
        if(this.handleCheckValidation()) {
            this.handleSpinner();
            this.fetchWeatherInfo();
        }
    }

    fetchWeatherInfo(){
        let APIKey = 'a0044bd100890XXXXXXXXXXXXXXX';
        var endPoint = 'https://api.openweathermap.org/data/2.5/weather?zip=' + this.zipCode + ',' + this.countryCode +'&appid=' +APIKey;
        //get request
        fetch(endPoint)
            .then((response) => {
                if (!response.ok) {
                    this.error = response;
                }
                return response.json();
            })
            .then((jsonResponse) => {
                console.log(jsonResponse);
                
                
                this.result.name = jsonResponse.name;
                this.result.sunset = this.convertUnixToTime(jsonResponse.sys.sunset);
                this.result.sunrise = this.convertUnixToTime(jsonResponse.sys.sunrise);
                this.result.pressure = jsonResponse.main.pressure;
                this.result.humidity = jsonResponse.main.humidity;
                this.result.temp = (jsonResponse.main.temp - 274.15).toFixed(2);

                this.handleSpinner();
            })
            .catch((error) => {
                console.log(error);
                this.error = error;
                this.handleSpinner();
            });
    }


    convertUnixToTime(unixtimestamp){
        console.log(unixtimestamp);
        var dt = unixtimestamp * 1000;
        var myDate = new Date(dt);
        console.log(myDate);
        return(myDate.toLocaleString());
    }

    handleSpinner(){
        this.showSpinner = !this.showSpinner;
    }
}

WeatherLwcComponent.JS-meta.xml :

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Output :

make-http-callout-request-in-lwc-salesforce-output-techdicer
make-http-callout-request-in-lwc-salesforce-output-techdicer

Reference :

  1. LWC
  2. Fetch API
What’s your Reaction?
+1
3
+1
1
+1
0
+1
0
+1
0
+1
0

You may also like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.