Salesforce: Making API calls from Lightning Components

In Lightning Components, you can’t make API calls from client-side code. Lightning Component framework uses Content Security Policy (CSP). Lightning apps will be served from a different domain than any external API end point so the CSP doesn’t allow API calls from JavaScript code.

How will Lightning Components work with external API? I haven’t had a chance to use an external API with Lightning Components. To learn about this, I decided to use OpenWeatherMap API. For this, we need an OpenWeatherMap API key when making OpenWeatherMap API calls. We also need to use Apex to make external API calls; HTTP Callouts can be used here.

The entire code used in this blog post can be found at https://github.com/jrattanpal/JRBlog. Let’s dive right into the code.

Apex Controller

To begin with, we need a class to make an API callout. Code for WeatherController class is at https://github.com/jrattanpal/JRBlog/blob/master/src/classes/WeatherController.cls.

WeatherController.cls defines an AuraEnabled method which can be called from Lightning Component. This method constructs an API url to use when making callout request using HTTPRequest. Once API call succeeds, it grabs the output and sends it back to Lightning Component. By default, OpenWeatherMap returns the response in JSON format.

Lightning Component

Now that we the base ready, we can start using this from a Lightning Component. The entire code Weather component is at https://github.com/jrattanpal/JRBlog/tree/master/src/aura/Weather. The way it works is:

  • A form is displayed when component loads
  • Users can enter a city in the text field and click “Get Weather Information”
  • This will use component helper to make a call to Apex
  • Apex will make an API call to OpenWeatherMap and return results for the provided city
  • And now we can combine this with amazing inbuilt functionalities of Lightning Components
  • We can just take Apex result and assign it to an aura:attribute
  • Once done, we can just start using that and display information

Lightning App

But wait, how do I ensure all of this is working? Well, we can create an app and use that to see how this component works. A DemoApp is at https://github.com/jrattanpal/JRBlog/tree/master/src/aura/DemoApp. You can view this app as https://DOMAIN.lightning.force.com/c/DemoApp.app

Well, what do you know? Just like that, we have created a simple component that can call out to an external API, get the results and display those in a Lightning Component. A good day’s work done and easily tested how external callouts work in a Lightning Component.

Leave a Reply