REST API using Weather Example

Sometimes you have a requirement to access information from an external source and store or display in Salesforce. One way of doing this is by making a REST API call from Salesforce to an external endpoint. In this example, we show step by step how a call using the REST API can be made to an external site to retrieve weather information related to an Account. We will be using http://openweathermap.org to get the weather and temperature of our Accounts Shipping City.

Summary:

  1. Ensure you have “API Enabled” permission.
  2. Register the site in the Remote Site Settings
  3. Get an API key
  4. Create the controller that will call the API
  5. Check that the HTTP request response code is 200 (OK)
  6. Deserialize JSON response code into a Map of String to Object
  7. Get values you need by accessing the relevant key
  8. Display using a button or an embedded VisualForce page

Step 1:

Ensure you have “API Enabled” permission. This is the setting that allows you to make API calls. This must be enabled to call any external service.

  • Navigate to Setup > Manage Users > Profiles
  • Select the profile of the person who will be the running user.
  • Ensure “API Enabled” is selected

image00

Step 2:

You must register the site we are calling in the Remote Site Settings, otherwise our call will fail.

  • Navigate to Setup > Security Controls > Remote Site Settings
  • Select “New Remote Site”
  • Fill in the name field. This can be anything you choose to identify it for yourself.
  • In the Remote Site URL field add the address of the the site you want to call. In our case it will be “http://api.openweathermap.org”
  • Ensure active is selected
  • Click save

image02

Step 3:

Now we need to get an API key to identify ourselves, this authenticates us to the service.

  • Go to http://openweathermap.org/api
  • Click Subscribe on the weather setting that interests you
  • For our purposes the free package is fine. Click Get API key and Start
  • Sign up
  • Once completed your API key will be shown.

image01

Step 4:

Create the controller that will call the API.
We need a basic Visualforce page the uses the Account standard controller and an extension.
Our extension needs to get the Account record from the controller and the shipping city using SOQL.

[crayon-6114a7583de67245688483/]

  • Now to build the URL based on the API from Open Weather Map.

image04

We copy the API key from the previous step and store it as a String to be added to the end of the URL. We also take the Shipping City that was queried from Account and add it to the URL as instructed.

[crayon-6114a7583de6d880109649/]

  • Creating the HTTP request

We need three variables of type Http, HttpRequest and HttpResponse respectively. The Http class is used to send the HttpRequest and get the HttpResponse.
Once the HttpRequest is initialised we then set the endpoint to the URL we built and set the method to ‘GET’.
We then create the HttpResponse by calling the send method on the Http using the HttpRequest as argument.

[crayon-6114a7583de6e611784538/]

Step 5:

To start we check that the request has been successful by checking the status code is 200, this is the standard response for successful HTTP requests. Then the JSON response needs to be deserialized into a Map of String to Object. The parameters of the API will be accessible as the keys of the Map
We can then get any value we are interested in by accessing the relevant key from the map, assigning the value to a variable in order to display it on our Visualforce page.

image03

[crayon-6114a7583de6f199187619/]

Step 6:

We can either display this using a button that directs to our page or an embedded VisualForce page.

Button:

  • Navigate to Setup > Customize > Accounts > Buttons, Links, and Actions
  • Click ‘New Button or Link’
  • Fill in the label field. This can be anything you choose to identify it for yourself. The name field will automatically populate.
  • Select ‘Detail Page Button’. This is selecting a button, we could also use ‘Detail Page Link’ if we wanted a hyperlink
  • Set Content Source to VisualForce Page.
  • Select our page AccountWeather.
  • Edit your layout to add the button.
  • You may want to have showHeader=”true” sidebar=”true” to show the header and sidebar on the VisualForce page.

image06

Embedded VF Page:

  • Navigate to your Account page layout
  • Select Visualforce Pages from the menu on the left
  • Select the Visualforce page and drag it onto the page where you want it to sit.
  • Save

image05

Complete Code:

[crayon-6114a7583de70396537917/]

[crayon-6114a7583de72711236317/]

The Result

Here is the result – a the Visualforce page has been embedded in our Account page layout, and will retrieve the weather based on the shipping city of our Account!
weather-section

What Certification are you studying for now?

Focus on Force currently provides practice exams and study guides for ten certifications

Comments

    1. Ian

      Hi Minas, Please try replacing line 32: Map results = (Map) JSON.deserializeUntyped(response.getBody()); with Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());”, and line 35: Map mainResults = (Map)(results.get(‘main’)); with “Map<String, Object> mainResults = (Map<String, Object>)(results.get(‘main’));”

      The angle brackets that confine the data types seem to have been stripped out. We’ll make the necessary fix.

  1. BrianC

    Getting error: Unknown constructor ‘AccountWeatherController.AccountWeatherController(ApexPages.StandardController controller)’ when saving the class in the developer console.

  2. Kyle Homovec

    Awesome stuff here Martin! Code works great. Quick question on this example here… I am attempting to pull in the JSON data stemming from the “weather” portion of the OpenWeather API, which is causing me some difficulty since it is formatted as an array. Would you have any advice on how to parse out these data points correctly? Thanks for the help!

    1. Sara S.

      To obtain weather data from OpenWeatherMap, you first need to use a list of Object data type and then go through each object of the list. Since each object is a map of string and object, you need to store it in a map and then obtain the weather information you’re looking for using different string variables. In this case, however, please note that the list contains only a single object since you want to obtain weather data for just one city. Please check the code in this link and the output in this link.

  3. Jon Spink

    This is great – first piece of Visualforce with Apex coding and API call! Took me a while to get it right (those Map statements…) but the result is great. Thanks. Anything else like this?

    1. Alexander Noble

      How did you end up getting the Map statements to work? I’m unsure as to the data types for the deserialized JSON response.. I tried using String as keys but I’m getting errors