Close Menu

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    What's Hot

    Building a Weather Integration in Salesforce using Visualforce, Apex Callouts, Named Credentials, and Wrapper Classes

    March 16, 2026

    How Agentforce Is Changing the Role of Salesforce Marketers

    March 13, 2026

    50 Salesforce CRM Analytics Interview Questions & Detailed Answers

    March 11, 2026
    Facebook X (Twitter) Instagram
    Facebook Instagram LinkedIn WhatsApp Telegram
    Salesforce TrailSalesforce Trail
    • Home
    • Insights & Trends
    • Salesforce News
    • Specialized Career Content
      • Salesforce
      • Administrator
      • Salesforce AI
      • Developer
      • Consultant
      • Architect
      • Designer
    • About Us
    • Contact Us
    Salesforce TrailSalesforce Trail
    Home - Developer - Building a Weather Integration in Salesforce using Visualforce, Apex Callouts, Named Credentials, and Wrapper Classes
    Developer

    Building a Weather Integration in Salesforce using Visualforce, Apex Callouts, Named Credentials, and Wrapper Classes

    Kiran Sreeram PrathiBy Kiran Sreeram PrathiMarch 16, 20265 Mins Read
    Facebook LinkedIn Telegram WhatsApp
    Building a Weather Integration in Salesforce
    Share
    Facebook LinkedIn Email Telegram WhatsApp Copy Link Twitter

    External integrations are one of the most common requirements in Salesforce applications. In this article, we will build a Weather Information Viewer using Salesforce technologies such as Visualforce, Apex, Named Credentials, Custom Metadata, and Wrapper Classes.

    This project demonstrates how Salesforce can interact with external APIs and display real-time data inside a Salesforce UI. By the end of this guide, you will have a responsive Visualforce weather dashboard where a user can enter a city name and retrieve current weather information.

    Table of Contents

    What We Are Building

    We will build a weather lookup application that allows users to:

    • Enter a city name
    • Click the Get Weather button
    • Fetch real-time weather data from an external API
    • Display weather details in a clean Visualforce interface

    The weather data is fetched from:

    https://api.weatherapi.com/v1/current.json

    Example API request: 

    				
    					https://api.weatherapi.com/v1/current.json?key=API_KEY&q=Chennai&aqi=no
    				
    			

    Architecture Overview

    Our solution follows Salesforce integration best practices by avoiding hardcoded values and separating logic properly. The key components are:

    ComponentTechnologyPurpose
    FrontendVisualforce PageUser interface for city search and weather display
    ControllerApex ClassHTTP callout logic and data binding
    API ConfigNamed CredentialsSecure external endpoint management
    API KeyCustom MetadataConfigurable key storage outside code
    Data ModelWrapper ClassJSON response deserialization

    🔍 Read More: How to Build a Clean Apex Trigger Framework: Step-by-Step Guide

    Named Credentials

    Instead of hardcoding the API endpoint in Apex, we configure a Named Credential for security and maintainability.

    Navigate to: Setup → Named Credentials, then configure:

    • Name: weather_Api
    • URL: http://api.weatherapi.com

    This allows our Apex callout to reference the endpoint safely:

    				
    					callout:weather_Api
    				
    			

    Custom Metadata for API Key

    We store the API key in Custom Metadata instead of hardcoding it in Apex. This allows us to update the configuration without changing any code.

    Custom Metadata Type:

    				
    					Weather_Config__mdt
    				
    			

    Field:

    				
    					ApiKey__c
    				
    			

    Record:

    				
    					DeveloperName: weather_Api_Key
    				
    			

    What is a Wrapper Class in Salesforce?

    A Wrapper Class is an Apex class used to represent complex data structures, especially when dealing with JSON responses from external APIs. When Salesforce receives a JSON response, it may contain nested objects such as location, current, and condition.

    Instead of manually parsing JSON using maps, we create a wrapper class that mirrors the JSON structure, enabling automatic deserialization via JSON.deserialize().

    Benefits of using Wrapper Classes:

    • Cleaner, more readable code
    • Automatic JSON deserialization
    • Easy property access on nested objects
    • Better maintainability over time

    Weather API JSON Structure

    The weather API returns a response structured as follows:

    				
    					{
     "location":{
        "name":"Chennai",
        "country":"India",
        "localtime":"2026-03-13 16:32"
     },
     "current":{
        "temp_c":31.2,
        "humidity":71,
        "condition":{
           "text":"Sunny",
           "icon":"//cdn.weatherapi.com/weather/64x64/day/113.png"
        }
     }
    }
    				
    			

    🔍 Read More: Salesforce Deployment Explained: Packaging vs CI/CD (When to Use Each and Why It Matters)

    Wrapper Class Implementation

    Using this wrapper class allows Salesforce to convert the JSON response automatically using JSON.deserialize()

    				
    					public class WeatherResponseWrapper {
        
        public Location location {get; set;}
        public Current current {get; set;}
        
        public class Location{
            public String name {get; set;}
            public String region {get; set;}
            public String country {get; set;}
            public String localtime {get; set;}
        }
        
        public class Current {
            public Decimal temp_c {get; set;}
            public Decimal temp_f {get; set;}
            public Integer humidity {get; set;}
            public Decimal wind_kph {get; set;}
            public Condition condition {get; set;}
        }
        
        public class Condition{
            public String text {get; set;}
            public String icon {get; set;}
        }
    }
    
    				
    			

    Apex Controller

    The WeatherVFController handles the complete workflow:

    • Retrieves the API key from Custom Metadata
    • Builds the API request using Named Credentials
    • Sends an HTTP callout to the weather service
    • Parses the JSON response into the wrapper class
    • Handles errors with user-friendly ApexPages messages
    				
    					public with sharing class WeatherVFController {
        
        public String cityName {get; set;}
        public WeatherResponseWrapper weatherData {get; set;}
        
        public void getWeather() {
            
            try{
                
                Weather_Config__mdt wcQuery = [
                    SELECT Id, Label, ApiKey__c 
                    FROM Weather_Config__mdt 
                    WHERE DeveloperName = 'weather_Api_Key' 
                    LIMIT 1
                ];
                
                String apiKey = wcQuery.ApiKey__c;
                
                String endpoint = 'callout:weather_Api/v1/current.json?key='
                    + apiKey + '&q=' + cityName + '&aqi=no';
                
                HttpRequest req = new HttpRequest();
                req.setEndpoint(endpoint);
                req.setMethod('GET');
                
                Http http = new Http();
                HttpResponse res = http.send(req);
                
                if(res.getStatusCode()==200){
                    
                    weatherData = (WeatherResponseWrapper)
                        JSON.deserialize(res.getBody(), WeatherResponseWrapper.class);
                        
                } else {
                    
                    ApexPages.addMessage(
                        new ApexPages.Message(
                            ApexPages.Severity.ERROR,
                            'Weather API Error'
                        )
                    );
                }
                
            } catch(Exception e){
                
                ApexPages.addMessage(
                    new ApexPages.Message(
                        ApexPages.Severity.ERROR,
                        e.getMessage()
                    )
                );
            }
        }
    }
    
    				
    			

    Visualforce Page

    The Visualforce page provides a clean, responsive UI for users to search for weather information. It features:

    • Gradient blue background with card-based layout
    • City name input field with placeholder text
    • Partial page refresh via reRender (no full page reload)
    • Dynamic weather icon fetched from the API response
    • Responsive grid displaying: City, Country, Local Time, Temperature, and Humidity

    Visualforce Code

    				
    					<apex:page controller="WeatherVFController" showHeader="false" sidebar="false"><style>body{
                font-family: "Salesforce Sans", Arial, sans-serif;
                background: linear-gradient(135deg,#4facfe,#00f2fe);
                margin:0;
                padding:0;
            }
    
            .container{
                max-width:900px;
                margin:auto;
                padding:30px;
            }
    
            .card{
                background:white;
                border-radius:12px;
                padding:25px;
                box-shadow:0 8px 25px rgba(0,0,0,0.2);
                margin-bottom:20px;
            }
    
            .title{
                font-size:24px;
                font-weight:600;
                margin-bottom:20px;
                text-align:center;
            }
    
            .input-group{
                display:flex;
                gap:10px;
                flex-wrap:wrap;
                justify-content:center;
            }
    
            .input-group input{
                padding:10px;
                border-radius:6px;
                border:1px solid #ccc;
                width:250px;
                font-size:14px;
            }
    
            .btn{
                background:#0070d2;
                color:white;
                border:none;
                padding:10px 18px;
                border-radius:6px;
                cursor:pointer;
                font-weight:bold;
            }
    
            .btn:hover{
                background:#005fb2;
            }
    
            .weather-grid{
                display:grid;
                grid-template-columns:repeat(auto-fit,minmax(200px,1fr));
                gap:15px;
                margin-top:20px;
            }
    
            .weather-item{
                background:#f4f6f9;
                padding:15px;
                border-radius:8px;
                text-align:center;
            }
    
            .weather-item label{
                font-weight:bold;
                display:block;
                margin-bottom:5px;
                color:#444;
            }
    
            .icon{
                text-align:center;
                margin-bottom:15px;
            }
    
            .icon img{
                width:80px;
            }
    
            @media(max-width:600px){
                .input-group{
                    flex-direction:column;
                    align-items:center;
                }
    
                .input-group input{
                    width:100%;
                }
            }</style><div class="container">
    
            <apex:form>
    
                
                <div class="card">
    
                    <div class="title">🌦 Weather Information</div>
    
                    <apex:pageMessages />
    
                    <div class="input-group">
                        <apex:inputText value="{!cityName}" html-placeholder="Enter City Name"/>
    
                        <apex:commandButton value="Get Weather"
                                            action="{!getWeather}"
                                            reRender="weatherPanel"
                                            styleClass="btn"/>
                    </div>
    
                </div>
    
    
                
                <apex:outputPanel id="weatherPanel">
    
                    <apex:outputPanel rendered="{!NOT(ISNULL(weatherData))}">
    
                        <div class="card">
    
                            <div class="icon">
                                <apex:image url="{!weatherData.current.condition.icon}"/>
                            </div>
    
                            <div class="weather-grid">
    
                                <div class="weather-item">
                                    <label>City</label>
                                    <apex:outputText value="{!weatherData.location.name}"/>
                                </div>
    
                                <div class="weather-item">
                                    <label>Country</label>
                                    <apex:outputText value="{!weatherData.location.country}"/>
                                </div>
    
                                <div class="weather-item">
                                    <label>Local Time</label>
                                    <apex:outputText value="{!weatherData.location.localtime}"/>
                                </div>
    
                                <div class="weather-item">
                                    <label>Temperature (°C)</label>
                                    <apex:outputText value="{!weatherData.current.temp_c}"/>
                                </div>
    
                                <div class="weather-item">
                                    <label>Humidity</label>
                                    <apex:outputText value="{!weatherData.current.humidity}"/>
                                </div>
    
                            </div>
    
                        </div>
    
                    </apex:outputPanel>
    
                </apex:outputPanel>
    
            </apex:form>
    
        </div>
    
    </apex:page>
    
    				
    			

    Your UI looks like this:

    Visualforce Weather Dashboard

    The page dynamically displays:

    • City
    • Country
    • Local Time
    • Temperature
    • Humidity
    • Weather Icon

    Example Output

    Example result for Chennai:

    FieldValue
    CityChennai
    CountryIndia
    Local Time2026-03-13 16:32
    Temperature31.2 °C
    Humidity71%
    ConditionSunny

    🔍 Read More: Salesforce Business Rules Engine (BRE) Explained: Smarter Decisioning Beyond Apex & Custom Metadata

    Best Practices Demonstrated

    Named CredentialsAvoid hardcoded endpoints and manage external services securely
    Custom MetadataStore configuration values like API keys outside of code
    Wrapper ClassesHandle JSON responses cleanly and efficiently
    Error HandlingProvide user-friendly error messages via ApexPages
    Clean UI DesignUse CSS styling to enhance Visualforce pages
    Salesforce Trail

    Final Thoughts

    This project is a great example of how Salesforce can integrate with external systems while maintaining a secure and scalable architecture. Even though modern Salesforce development focuses heavily on Lightning Web Components, Visualforce remains valuable for learning Apex integrations and callout patterns.

    Understanding these patterns helps developers build enterprise-grade integrations in Salesforce.

    Kiran Sreeram Prathi
    Kiran Sreeram Prathi
    Sr. Salesforce Developer – kiransreeram8@live.com

    I’m Kiran Sreeram Prathi, a Salesforce Developer dedicated to building scalable, intelligent, and user-focused CRM solutions. Over the past five years, I’ve delivered Salesforce implementations across healthcare, finance, and service industries—focusing on both technical precision and user experience. My expertise spans Lightning Web Components (LWC), Apex, OmniStudio, and Experience Cloud, along with CI/CD automation using GitHub Actions and integrations with platforms such as DocuSign, Conga, and Zpaper. I take pride in transforming complex workflows into seamless digital journeys and implementing clean DevOps strategies that reduce downtime and accelerate delivery. Recognized by organizations like Novartis, WILCO, and Deloitte, I enjoy solving problems that make Salesforce work smarter and scale better. I’m always open to connecting with professionals who are passionate about process transformation, architecture design, and continuous innovation in the Salesforce ecosystem.

    • Kiran Sreeram Prathi
      #molongui-disabled-link
      Salesforce Deployment Explained: Packaging vs CI/CD
      January 7, 2026
      Salesforce Deployment Explained: Packaging vs CI/CD (When to Use Each and Why It Matters)
    • Kiran Sreeram Prathi
      #molongui-disabled-link
      Salesforce Business Rules Engine (BRE) Explained
      December 15, 2025
      Salesforce Business Rules Engine (BRE) Explained: Smarter Decisioning Beyond Apex & Custom Metadata
    • Kiran Sreeram Prathi
      #molongui-disabled-link
      Build a Dynamic, Reusable Lightning Datatable in Salesforce LWC
      November 25, 2025
      Build a Dynamic, Reusable Lightning Datatable in Salesforce LWC (With Metadata-Driven Columns, Search & Pagination)
    • Kiran Sreeram Prathi
      #molongui-disabled-link
      Salesforce MVP Architecture: A Beginner’s Guide
      November 12, 2025
      Salesforce MVP Architecture: A Beginner’s Guide to Building Clean, Scalable Lightning Web Components
    Apex Apex Callout Apex Callouts API Integration LWC Named Credential salesforce Visualforce Wrapper Class
    Share. Facebook LinkedIn Email Telegram WhatsApp Copy Link

    Related Posts

    How Agentforce Is Changing the Role of Salesforce Marketers

    March 13, 2026

    50 Salesforce CRM Analytics Interview Questions & Detailed Answers

    March 11, 2026

    TDX 2026 Hackathon: Everything Salesforce Professionals Need to Know

    March 9, 2026
    Add A Comment
    Leave A Reply Cancel Reply

    Advertise with Salesforce Trail
    Connect with Salesforce Trail Community
    Latest Post

    How to Hire Salesforce Consultants: Practical Tips Every Business Should Know

    February 19, 2026

    6 Proven Principles to Drive Faster Salesforce CRM Adoption

    November 3, 2025

    Driving Revenue Efficiency with Sales Cloud in Product Companies

    October 30, 2025

    How to Become a Salesforce Consultant: A Complete Guide to Success

    August 15, 2025
    Top Review
    Designer

    Customizing Salesforce: Tailor the CRM to Fit Your Business Needs

    By adminAugust 6, 20240

    Salesforce is an adaptable, powerful customer relationship management (CRM) software that businesses can customize, and…

    Sales Professional

    Unlock 10 Powerful Sales Pitches to Boost Your Revenue by 30X

    By Mayank SahuJuly 4, 20240

    Sales is a very competitive arena, and it is followed by one must have a…

    Salesforce Trail
    Facebook X (Twitter) Instagram LinkedIn WhatsApp Telegram
    • Home
    • About Us
    • Write For Us
    • Privacy Policy
    • Advertise With Us
    • Contact Us
    © 2026 SalesforceTrail.com All Right Reserved by SalesforceTrail

    Type above and press Enter to search. Press Esc to cancel.