In this blog post, I’ll guide you through integrating a Weather API with Salesforce to retrieve and display the current weather based on a user’s search string. Whether you’re building a custom solution or simply want to enhance your Salesforce app with real-time weather data, this integration will be useful. Let’s dive into the step-by-step process!
Why Integrate a Weather API?
Integrating a weather API into Salesforce allows users to fetch real-time weather data based on a city or location, which can be used in various industries, including travel, logistics, or outdoor event management. By combining this data with Salesforce, you can enable users to access critical weather information directly within your app.
Prerequisites
- Salesforce Developer Edition Account – If you don’t have one, create a free account here.
- Weather API Key – We’ll use the OpenWeatherMap API for this tutorial. You can sign up and get an API key from OpenWeatherMap.
- Basic Knowledge of Apex and Lightning Web Components (LWC) – You should be familiar with Apex for server-side logic and LWC for UI.
Step 1: Create a Weather API Account and Obtain an API Key
- Sign up for a free API key on OpenWeatherMap.
- After creating an account, go to your dashboard and copy the API key provided.
Step 2: Create an Apex Class to Call the Weather API
In Salesforce, we’ll use an Apex class to handle the API request and return the weather data to the front end.
Apex Class: WeatherController
/**
* @File Name : WeatherController.cls
* @Description :
* @Author :
* @Last Modified By :
* @Last Modified On : September 4, 2024
* @Modification Log :
*==============================================================================
* Ver | Date | Author | Modification
*==============================================================================
* 1.0 | September 4, 2024 | | Initial Version
**/
public with sharing class WeatherController {
@AuraEnabled(cacheable=true)
public static String getWeather(String location) {
String apiKey = '';
String apiUrl = 'https://api.openweathermap.org/data/2.5/weather?q=' + location + '&appid=' + apiKey;
system.debug(apiUrl);
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint(apiUrl);
request.setMethod('GET');
HttpResponse response = http.send(request);
if (response.getStatusCode() == 200) {
system.debug(response.getBody());
return response.getBody();
} else {
throw new AuraHandledException('Error retrieving weather information: ' + response.getBody());
}
}
}
Step 3: Set Up Remote Site Settings
Since we are calling an external API, Salesforce requires you to add the API domain to the Remote Site Settings.
- Go to Setup in Salesforce.
- In the Quick Find box, search for “Remote Site Settings.”
- Click New Remote Site.
- Enter the following details:
- Remote Site Name: OpenWeatherMap
- Remote Site URL:
https://api.openweathermap.org
- Click Save.
Step 4: Create a Lightning Web Component (LWC) for the UI
Now, we will create an LWC to allow users to enter a city name and display the weather information.
LWC HTML: WeatherApp
.html
<template>
<div class="slds-card">
<div class="slds-card__header slds-grid slds-grid_align-spread slds-m-bottom_medium">
<h1 class="slds-text-heading_medium slds-truncate slds-text-title_bold slds-text-color_success">Weather App</h1>
</div>
<div class="slds-card__body">
<div class="slds-grid slds-wrap">
<div class="slds-col slds-size_8-of-12">
<lightning-input label="Enter Location" value={location} onchange={handleLocationChange} placeholder="e.g. London, Paris" variant="label-hidden" class="slds-size_1-of-1 slds-p-left_small"></lightning-input>
</div>
<div class="slds-col slds-size_4-of-12">
<lightning-button label="Get Weather" variant="brand" onclick={handleGetWeather} class="slds-m-top_small slds-m-left_small slds-size_1-of-1"></lightning-button>
</div>
</div>
</div>
<div class="slds-grid slds-wrap slds-m-top_large">
<template if:true={currentWeather}>
<div class="slds-col slds-size_1-of-1 slds-p-left_small">
<h2>Current Weather</h2>
<div class="slds-grid slds-wrap">
<div class="slds-col slds-size_1-of-2"><strong>City:</strong> {city}</div>
<div class="slds-col slds-size_1-of-2"><strong>Description:</strong> {description}</div>
<div class="slds-col slds-size_1-of-2"><strong>Temperature:</strong> {temperature}℃</div>
<div class="slds-col slds-size_1-of-2"><strong>Humidity:</strong> {humidity}%</div>
</div>
</div>
</template>
<template if:false={currentWeather}>
<div class="slds-col slds-size_1-of-1">
<div class="slds-notify slds-notify_alert slds-theme_alert-texture slds-m-vertical_medium" role="alert">
<span class="slds-assistive-text">Info</span>
No current weather data available.
</div>
</div>
</template>
</div>
</div>
</template>
LWC JavaScript: WeatherApp
.js
import { LightningElement, track } from 'lwc';
import getCurrentWeather from '@salesforce/apex/WeatherAPIService.getCurrentWeather';
export default class WeatherComponent extends LightningElement {
@track cityName = '';
@track weatherData;
// Handle input change for city name
handleInputChange(event) {
this.cityName = event.target.value;
}
// Call Apex to get the weather data based on the city name
getWeather() {
getCurrentWeather({ cityName: this.cityName })
.then(result => {
this.weatherData = JSON.parse(result);
})
.catch(error => {
console.error('Error fetching weather data: ', error);
});
}
}
Step 5: Deploy and Test the Integration
- Save and deploy your Apex class and LWC to your Salesforce org.
- Add the
weatherComponent
LWC to a Lightning App or Record Page. - Enter a city name in the input field and click Get Weather to fetch the weather data.
Conclusion
Congratulations! You’ve successfully integrated a weather API with Salesforce using Apex and LWC. Now users can search for real-time weather information by entering a city name. This simple integration can be expanded to handle more advanced use cases like storing weather data or automating actions based on weather conditions.
Additional Resources
If you’re interested in learning more about integrations in Salesforce, here are two useful resources to expand your knowledge:
- Twilio Integration with Salesforce: Learn how to integrate Twilio with Salesforce to send SMS, make phone calls, or track communication using Twilio’s services directly within your Salesforce environment.
- Integrating Salesforce with Postman: A step-by-step guide on how to integrate Salesforce with Postman for testing Salesforce APIs, making API requests, and performing operations on Salesforce records.
By exploring these resources, you can continue enhancing your Salesforce integration skills for many use cases!
Feel free to customize this solution for your specific business needs, and don’t forget to share your thoughts or questions in the comments below!