Integrate Salesforce with OpenWeatherMap Using Salesforce Flow

Advertisements

Last Updated on June 20, 2023 by Rakesh Gupta

Big Idea or Enduring Question:

  • How to integrate Salesforce with OpenWeatherMap using OpenWeather API to get Weather Information using Salesforce Flow?

Objectives:

After reading this blog, you’ll be able to:

  • Create Named Credentials for outbound requests.
  • Setup a free OpenWeather account.
  • Initiate an outbound HTTP GET request utilizing Salesforce Flow without the need for code.
  • Manage the outbound request response and implement appropriate actions.
  • and much more

👉 In the past I’ve written an article on BarCode and QR Code generation. Why not check them out while you are at it?!

  1. Generate Barcode and QR Code in Salesforce

Business Use case

Jestilla Zetkin is working as a Salesforce Architect at Gurukul On Cloud (GoC). During her work on Sales Cloud implementation, she was assigned a task to fetch the current temperature, longitude and latitude of the ‘ShippingCity’ using the OpenWeather API, whenever an account is created. The detailed specifications are as follows:

  1. Initiate a request to the OpenWeather API each time an account is created.
    1. Get the following details for ShippingCity and record it in the corresponding fields (within the account):
      1. Feels Like
      2. Temp Min
      3. Temp Max
      4. Longitude
      5. Latitude
  2. In the event of a failed response, institute a contingency action to create a task for the account’s designated owner.

What is OpenWeather API?

OpenWeatherMap is an online service owned by OpenWeather Ltd that provides global weather data via API, including current weather data, forecasts, nowcasts, and historical weather data for any geographical location. The company offers a minute-by-minute hyperlocal precipitation forecast for any location. 

One Call 3.0 allows users to receive access to the various data for a specific location and includes:

  • Current weather
  • Minute forecast for 1 hour
  • Hourly forecast for 48 hours
  • Daily forecast for 8 days
  • Government weather alerts
  • Historical weather data for 40+ years back
  • History daily aggregation for 40+ years back

OpenWeather API provides an API with JSON, XML, and HTML endpoints and a limited free usage tier. Making more than 60 calls per minute requires a paid subscription. Access to historical data also requires a subscription. Users can request current weather information, extended forecasts, and graphical maps (showing cloud cover, wind speed, pressure, and precipitation).

Here’s an illustrative example of a response obtained from invoking the OpenWeather API:


{
   "coord":{
      "lon":-96.8864,
      "lat":33.089
   },
   "weather":[
      {
         "id":800,
         "main":"Clear",
         "description":"clear sky",
         "icon":"01n"
      }
   ],
   "base":"stations",
   "main":{
      "temp":24.11,
      "feels_like":24.56,
      "temp_min":22.01,
      "temp_max":25.72,
      "pressure":1008,
      "humidity":76
   },
   "visibility":10000,
   "wind":{
      "speed":3.13,
      "deg":31
   },
   "clouds":{
      "all":0
   },
   "dt":1686459485,
   "sys":{
      "type":2,
      "id":2041986,
      "country":"US",
      "sunrise":1686395899,
      "sunset":1686447350
   },
   "timezone":-18000,
   "id":4736388,
   "name":"The Colony",
   "cod":200
}

To use this current weather data API, one must need the API key, which can be obtained from here.

If you need the geocoder to automatic convert city names and zip-codes to geo coordinates and the other way around, you have to use Geocoding API.

Read OpenWeather API documentation to understanding about different parameters and capabilities.

Automation Champion Approach (I-do):

While this can be solved using various automation tools like Apex Trigger and others, we will use Salesforce Flow and newly introduced HTTP GET Callout flow feature.

HTTP Callout pulls or sends data between the Salesforce database and an external system via Flow Builder without using code. You can set up direct integrations as needed without having to work with a developer or call a middleware tool, such as Mulesoft. After you configure the HTTP callout action in a flow, Flow Builder auto-generates an external service registration, an invocable action, and Apex class that you can use to create an Apex-defined resource for flows. You can then use the data output of the API request as input within Flow Builder and across Salesforce.

You can use HTTP Callout to connect a flow to a variety of APIs.

  • Get address information using a map API
  • Get weather conditions with a weather service API
  • Generate the barcode with a barcode service API
  • Get payment authorization information with a payment processing API
  • and much more

Before discussing the solution, let me show you a diagram of the process at a high level. Please spend a few minutes going through the following Flow diagram to understand it.

Guided Practice (We-do):

There are 4 steps to solve Jestilla’s business requirement using Record-Triggered After-Save Flow. We must:

  1. Getting the OpenWeather API key
  2. Create custom fields on the Account to store the response
  3. Create a Named Credential
  4. Salesforce Flow
    1. Define flow properties for record-triggered flow
    2. Configure an HTTP GET callout for OpenWeather API
    3. Add a Decision element to check the response code
    4. Add an Update Records element to update the account
    5. Add a Create Records element to create a Task for the Account owner to handle error response

Step 1: Getting the OpenWeather API Key

To get the API key, we need to register with OpenWeatherMap. After signing up, it will redirect us to the profile settings.

  1. Click here to open the OpenWeather website.
  2. Click the Sign in button.
  3. A new window opens. If you already have an account on the website, enter your credentials. Otherwise, click the Create an Account option.
  4. Once your account is ready, you are automatically directed to the OpenWeather page where you signed in. It asks you about your company, and the purpose of using the OpenWeather platform.
  5. From the top menu bar, click on your username next to the For Business label and select My API keys from the dropdown list. This will redirect you to a page where you’ll see an API key named Default.

Step 2: Create Custom Fields on the Account Object to Store the Response

  1. Click Setup.
  2. In the Object Manager, type Account.
  3. Select Fields & Relationships, then click New.
  4. Now create few custom fields as shown in the screenshot below:
  5. Click Save.

Step 3: Create a Named Credential

  1. Click Setup.
  2. In the Quick Find box, enter Named Credentials, and then select Named Credentials.
  3. Click New Legacy.
  4. Fill out the page with the callout endpoint’s URL and authentication parameters.
  5. Click Save.

Step 4.1: Define Flow Properties

  1. Click Setup.
  2. In the Quick Find box, type Flows.
  3. Select Flows, then click on the New Flow.
  4. Select the Record-Triggered Flow option, click on Create 
    1. Object: Account
    2. Trigger the Flow When: A record is created
    3. Set Entry Conditions: 
      1. Field: ShippingCity
      2. Operator: Does Not Equal
      3. Value: {!$GlobalConstant.EmptyString}
    4. Optimize the Flow For Action and Related Records
    5. Choose the Option to Include a Run Asynchronously path to access an external system after the original transaction for the triggering record is successfully committed.
  5. Click Done.

Step 4.2: Configure an HTTP GET Callout Action

HTTP Callout guides you through entering the details about the HTTP web-based service or REST API endpoint that you’re connecting to. After you complete the configuration, you invoke the action in a flow.

  1. Under Run Asynchronously node, select Action.
  2. Click + Create HTTP Callout.
  3. Configure the external service that connects Salesforce to the HTTP-based API.
    1. Enter a Name for the external service.
    2. Select the named credential that you created in the step 2.
    3. Click Next.
  4. The next step is to configure the invocable action that you can use in Flow Builder or across Salesforce.
    1. For Label, enter the action that the callout performs.
    2. Method: GET
    3. Add the URL endpoint for the request.
      1. URL Path: /data/2.5/weather
    4. Add query parameter keys if the API you’re calling has them. When you use this action in a flow, you input values for the defined keys.
      1. Click Add Key
        1. Key: q
        2. Data Type: String
        3. Required: True
      2. Click Add Key
        1. Key: units
        2. Data Type: String
        3. Required: True
      3. Click Add Key
        1. Key: appid
        2. Data Type: String
        3. Required: True
  5. Provide a sample API response body. Salesforce generates a data structure from the sample response.
    1. Navigate to Provide Sample Response section.
    2. Click New.
    3. Paste a sample JSON response.
    4. Click Review and confirm that the Apex data structure is correct.
    5. To make changes, edit the text in Sample JSON Response or select data types from the data structure.
    6. Click Review.
    7. Click Done.
  6. Click Save.
  7. Flow Builder creates the action and external service. The action is available in the Actions window in the flow.
  8. The next step is to add apex action generated by HTTP Callout setup in the previous steps. We will use the Action element.
    1. Label the new action OpenWeather Callout.
    2. Set Input Values

      1. appid: YOUR_OpenWeather_API_KEY
      2. q{!$Record.ShippingCity}
      3. units: metric
  9. Click Done.

Step 4.3: Using Decision Element to Check the OpenWeather Callout Response Code

Now we will use the Decision element to check the OpenWeather API response code.

  1. On Flow Designer, click on the +icon and select the Decision element.
  2. Enter a name in the Label field; the API Name will auto-populate.
  3. Under Outcome Details, enter the Label the API Name will auto-populate.
  4. Condition Requirements to Execute OutcomeAll Conditions Are Met (AND)
    1. Row 1:
      1. Resource: {!OpenWeather_Callout.responseCode}
      2. Operator: Equals
      3. Value: 200
    2. Add a new OUTCOME ORDER by clicking on the + icon to check City Not Found response.
    3. Row 1:
      1. Resource: {!OpenWeather_Callout.responseCode}
      2. Operator: Equals
      3. Value: 404
    4. Add a new OUTCOME ORDER by clicking on the + icon to check Invalid API Key response.
    5. Row 1:
      1. Resource: {!OpenWeather_Callout.responseCode}
      2. Operator: Equals
      3. Value: 401
    6. Add a new OUTCOME ORDER by clicking on the + icon to check Plan Limit Exceeded response.
    7. Row 1:
      1. Resource: {!OpenWeather_Callout.responseCode}
      2. Operator: Equals
      3. Value: 429
    8. Add a new OUTCOME ORDER by clicking on the + icon to check Contact Provider response.
    9. Condition Requirements to Execute Outcome: Any Conditions Is Met (OR)
    10. Row 1:
      1. Resource: {!OpenWeather_Callout.responseCode}
      2. Operator: Equals
      3. Value: 500
    11. Row 2:
      1. Resource: {!OpenWeather_Callout.responseCode}
      2. Operator: Equals
      3. Value: 502
    12. Row 3:
      1. Resource: {!OpenWeather_Callout.responseCode}
      2. Operator: Equals
      3. Value: 503
    13. Row 4:
      1. Resource: {!OpenWeather_Callout.responseCode}
      2. Operator: Equals
      3. Value: 504
  5. Click Done.

Step 4.4: Adding an Update Records Element to Update the Account

The next step is to update the accounts fields to store the callout response. We will use the Update Records element. 

  1. On Flow Designer, below the Successful node, click on the +icon and select the Update Records element.
  2. Enter a name in the Label field; the API Name will auto-populate.
  3. For How to Find Records to Update and Set Their Values select Use the account record that triggered the flow
  4. Set Filter Conditions: None – Always Update Record
  5. Set Field Values for the Account Records
    1. Row 1:
      1. Field: Feels_Like__c
      2. Value: {!OpenWeather_Callout.2XX.main.feelsx5flike}
    2. Click Add Field
    3. Row 2:
      1. Field: ShippingCity_GeoCode__Latitude__s
      2. Value: {!OpenWeather_Callout.2XX.coord.lat}
    4. Click Add Field
    5. Row 3:
      1. Field: ShippingCity_GeoCode__Longitude__s
      2. Value: {!OpenWeather_Callout.2XX.coord.lon}
    6. Click Add Field
    7. Row 4:
      1. Field: Temp_Max__c
      2. Value: {!OpenWeather_Callout.2XX.main.tempx5fmax}
    8. Click Add Field
    9. Row 5:
      1. Field: Temp_Min_Celcius__c
      2. Value: {!OpenWeather_Callout.2XX.main.tempx5fmin}
  6. Click Done.

Step 4.5: Add Action – Create a Record to Handle Error Response

The next step is to create a task, for this, we will use the Create Records element.

  1. On Flow Designer, below the City Not Found node, click on the +icon and select the Create Records element.
  2. Enter a name in the Label field; the API Name will auto-populate.
  3. Input the following information:
    1. Enter Label the API Name will auto-populate.
    2. How Many Records to Create: One
    3. How to Set the Record Fields: Use separate resources, and literal values
    4. Object: Task
    5. Set Field Values for the Case
    6. Row 1:
      1. Field: Description
      2. Value: {!OpenWeather_Callout.defaultExc}
    7. Click Add Field
    8. Row 2:
      1. Field: OwnerId
      2. Value: {!$Record.OwnerId}
    9. Click Add Field
    10. Row 3:
      1. Field: Priority
      2. Value: High
    11. Click Add Field
    12. Row 4:
      1. Field: Status
      2. Value: Not Started
    13. Click Add Field
    14. Row 5:
      1. Field: Subject
      2. Value: {!OpenWeather_Callout.responseCode}
    15. Click Add Field
    16. Row 6:
      1. Field: WhatId
      2. Value: {!$Record.Id}
  4. Click Done.

In the end, Jestilla’s Flow will look like the following screenshot:

Once everything looks good, perform the steps below: 

  1. Click Save.
  2. Enter Flow Label the API Name will auto-populate.
  3. Click Show Advanced.
  4. API Version for Running the Flow: 58
  5. Interview LabelHTTPS Callout {!$Flow.CurrentDateTime}
  6. Click Save.

Almost there! Once everything looks good, click the Activate button.  

👉 Check out the video for step-by-step instructions.

Proof of Concept

  1. Now onwards, when a user creates an account, the flow will fire and bring the current weather, longitude, and latitude for the current ShippingCity from OpenWeather API.
  2. In an error response, the flow will create a task and assign it to Account Owner.

Formative Assessment:

I want to hear from you!

What is one thing you learned from this post? How do you envision applying this new knowledge in the real world? Feel free to share in the comments below.

Have feedback, suggestions for posts, or need more information about Salesforce online training offered by me? Say hello, and leave a message!

Preferred Timing(required)

 

13 thoughts on “Integrate Salesforce with OpenWeatherMap Using Salesforce Flow

    1. Rakesh Gupta – Mumbai – 9x Salesforce MVP | Senior Solution Architect | 8x Author | 5x Dreamforce Speaker | Salesforce Coach | Co-host of AutomationHour.com and AppXchangeHour.Com

      The Salesforce flow can’t run because nothing is connected to the Start element. – it means that the starting point of your flow has not been connected to any subsequent actions or elements.

  1. Hi Rakesh,

    I am getting below error when I debug it. This showed up at Action element.

    Error Occurred:

    Unexpected error while calling external service. Contact Salesforce Customer Support with error ID: 579838291-141036 (-11429193)

    Any idea what should I do ?

    1. Rakesh Gupta – Mumbai – 9x Salesforce MVP | Senior Solution Architect | 8x Author | 5x Dreamforce Speaker | Salesforce Coach | Co-host of AutomationHour.com and AppXchangeHour.Com

      Please review the error email sent by Salesforce or utilize the debug log for further investigation. Please keep me posted on your progress.

    1. Rakesh Gupta – Mumbai – 9x Salesforce MVP | Senior Solution Architect | 8x Author | 5x Dreamforce Speaker | Salesforce Coach | Co-host of AutomationHour.com and AppXchangeHour.Com

      I’m sorry to hear that you’re encountering the “Received fatal alert: protocol_version” error. This error usually indicates a mismatch in the SSL/TLS protocol version between the client and server.

      I recommend reaching out to OpenWeatherMap’s support team or their documentation for assistance with this specific error. They would be in a better position to help you diagnose and resolve the issue.

    1. Rakesh Gupta – Mumbai – 9x Salesforce MVP | Senior Solution Architect | 8x Author | 5x Dreamforce Speaker | Salesforce Coach | Co-host of AutomationHour.com and AppXchangeHour.Com

      You’re right! I have revised the post to incorporate the changes. Thank you! 😊

Leave a ReplyCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Automation Champion

Subscribe now to keep reading and get access to the full archive.

Continue reading

Exit mobile version
%%footer%%