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.
- Ensure you have “API Enabled” permission.
- Register the site in the Remote Site Settings
- Get an API key
- Create the controller that will call the API
- Check that the HTTP request response code is 200 (OK)
- Deserialize JSON response code into a Map of String to Object
- Get values you need by accessing the relevant key
- Display using a button or an embedded VisualForce page
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
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
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.
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.
- Now to build the URL based on the API from Open Weather Map.
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.
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.
We can either display this using a button that directs to our page or an embedded VisualForce page.
- 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.
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.
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!
What Certification are you studying for now?
Focus on Force currently provides practice exams and study guides for fifteen certifications
I am getting an error when trying to save the AccountWeatherController
Error: Compile Error: Unexpected token ‘Map’. at line 32 column 12
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.
Getting error: Unknown constructor ‘AccountWeatherController.AccountWeatherController(ApexPages.StandardController controller)’ when saving the class in the developer console.
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!
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.
Great code ! just what I needed. Could you also share us the testclass you used for this ?
Hi Jean, sorry we don’t have the test class available for this.
Thanks Jon, glad you found it useful. What other types of examples would you like to see?
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?
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