Skip to Content
Author's profile photo Former Member

WebIDE Ninja #1: Consume 3rd Party services with UI5

/wp-content/uploads/2016/03/ninja_logo_913521.png

This blog is the first one of a series of blog which we like to call “Becoming a Ninja Web IDE Developer”. This series will expose advanced topics in Web IDE beyond the standard Fiori development which you all mastered by now.


Important Update (posted on 27.4.2016)


When i wrote this blog (about a month ago) the open API weather did not require an API Key, but it is not required (thanks to An Thanh Phan gor noticing this), so now a prerequisite for using this API is to first generate an API Key.

To do so, go thought the following steps:

  1. Go to the OpenWeatherMap homepage OpenWeatherMap current weather and forecast
  2. Click on sign up (enter your email, password and all the required fields)
  3. Then under the setup tab you can find  your API key (you will need to replace the API key that we use in this blog with this value)


24 - open api weather api key.png

  1. I also updated the source code under the GIT repository

Prerequisites

  • SAP Web IDE instance – either trial or production (you can get one here: SAP HANA Cloud Platform )
  • Knowledge in UI5 development and data binding
  • Modern web browser (chrome/firefox etc.)
  • Have a quick look at the Open weather APIWeather API


Introduction

Most of the common apps that are implemented with Web IDE and UI5 are apps which consume oData services from SAP backend. Creating a UI5 app in Web IDE which consume oData is pretty straight forward using Web IDE rapid development tools you can generate an app which consume oData easily using template wizards, WYSIWYG, Extensibility and more.. but what if the API that you are trying to consume is not an oData API but JSON REST API? and what if in addition to consume oData you want also to consume other REST services which are available out there like: Facebook , twitter, google API’s, weather and more. Most of the public API’s which exist today expose their data in simple JSON format and not built on top of the oData protocol and currently you cannot use all the rapid capabilities of Web IDE for developing an app which consume such services.

In this blog post we will show how we can create a simple app which consume 3rd REST service with SAP WebIDE. we will also use as many as tools that we can that are part of Web IDE in order to reduce the development time to a minimum and will write my code according to the SAPUI5 and Fiori guidelines (data binding, xml views, component and more).

Let’s get started!

Open Weather API

The 3rd party API that we will consume in this app will be the Open Weather API.  The specific URL that we will use in our app is described here: forecast16

The App

The app that we will create will be a simple app which will consume the open weather API and will show the forecast in London (can be changed) for the next 16 days.

The result of this blog post will be an app that will contain 2 UI elements:

  • Object Header – will show  the country and the city SAPUI5 Explored
  • Table – will show the forecast of the next 16 days (date,average degrees,units and humidity)  SAPUI5 Explored

The app UI will be like the following:

1 - final app.png

As you can see from the image above the app is simple because the idea of this blog post is to show all the relevant steps that are required in order to develop an app which consume 3rd party services in the Right Way!

1 – Generate an empty app

  • Open your Web IDE instance
  • Click on File –> New –> Project From Template
  • In the dialog select SAP Fiori Application in the first combobox and then select the SAPUI5 Application tile
    2-sapui5 dialog.png
  • Click Next and fill in the following details in the next window
    • Project Name: OpenWeatherSample
    • Namespace: com.demo
    • Leave the set this project hybrid mobile application unchecked

      3 - dialog sec step.png
  • Click Next and on the next step fill in the following details
    • View Type: XML
    • View Name: Main

      4 - third step.png
    • Click Finish –> a new project will be generated into your Workspace.
    • The project structure should look like the following:

      5 - project structure.png

2 – Create destination in HCP cockpit

Now we are ready to create a new destination in HCP cockpit that will point to the open weather API.

creating of new destination is required in order to avoid cross origin (that the host where the apps run on try to access a different host in our case is the open weather API host). More details about CORS can be found here: HTTP access control (CORS) – HTTP | MDN

Please do the following in order to create new destination:

  • In Web IDE go to Tools –> SAP Hana Cloud Platform Cockpit to open the HCP cockpit

    6 - go to HCP cockpit.png

  • In the HCP cockpit select Destinations (from the left menu)
  • Click on New Destination button the create a new destination and fill in the following details:
    • Name: OpenWeather
    • Type: HTTP
    • Description: Open Weather API
    • URL: http://api.openweathermap.org
    • Proxy Type: Internet
    • Authentication: No Authentication
    • Additional Properties:
      • WebIDEEnabled: true
      • WebIDESystem: API
  • Click Save to create the new Destination .

    7 - new destination.png

  • Or you can download the attached destination that we uploaded and import it to your HCP cockpit

3 – Add the new destination to neo-app.json

In order to use this destination in our app we will need to add it to the neo-app.json file. The neo-app.json is the configuration file of the HCP front-end server. This file contains all the services/destinations that are required in order to app to run on the HCP server.

In order to add our new destinations please do the following:

  • Go to Web IDE and expand the OpenWeatherSample app (the one that we generated in the first step)
  • Double click on the neo-app.json to edit it
  • Under the routes array add a new object with the following details:

{
      "path": "/OpenWeather",
      "target": {
        "type": "destination",
        "name": "OpenWeather",
        "entryPath": "/"
      },
      "description": "Open weather API"
}






























  • Now, in order to consume the Open Weather API the only thing that we will need to do in code is the call to “/OpenWeather” behind the scenes HCP front-server will search for a destination with name “OpenWeather” and will redirect us to the URL that we specified in the destination
  • If you are having troubles with modify the neo-app.json file you can just download the file that we attached and replace it with the one that you have in your workspace. (please make sure that you don’t change the name of this file)

4 – Design the app UI

In this section we will create the UI for our app.

Like we mentioned above for this simple app we will use only 2 UI elements an ObjectHeader and a Table

we also mentioned that we will use as many as tools as possible in order to reduce the development time and complexity, specifically for designing the UI we will use the Layout Editor (WYSIWYG) which is a tool that allow developer to create UI by dragging&dropping UI5 controls into a canvas.

  • Expand the View folder and select the Main.view.js file
  • Right click on the file and select Open With –> Layout Editor
    8 - open layout editor.png
  • Web IDE layout editor will be opened with an empty view
  • Now we have 2 options to add UI elements into our canvas:
    • By dragging & dropping them from the left side (under controls tab) into the right side (the canvas) – This is the what we will do
    • By using the outline there you can add UI elements by right click on one of the controls and select Add in order to add elements into it
  • Please do the following in order to add the UI elements into the view
    • Make sure the Controls tab (appear on the left side) is selected
      9 - controls tab.png
    • Using the search box search for ObjectHeader control and select it
    • Drag the ObjectHeader control from the left side into the right side and make sure it is located on the top of the page
      10 - drag objectheader.png
    • Again, using the search box this time search for Table and select it
    • Drag and drop the Table control and make sure it is located under the ObjectHeader
      11 - drag and drop table.png
  • Next we need to change the UI elements properties according to our needs. Because the layout editor currently supports only oData model binding we will need to do some manual changes in both the XML code editor and the layout editor.
  • Please do the following for the changes that we need to make in the Layout Editor
    • From the right side canvas select the ObjectHeader control
    • After the control is selected you will be able to see and change the control properties. The control properties are located on the right side of the canvas
    • Please change the following properties
      • Title: {/country}
      • Intro: {/city}
      • Number: Leave it empty
      • Number Unit: Leave it empty

                12 - objectheader props.png

  • Now we need also to change the Table control properties but this time we will do it in the XML code editor (and not in the layout editor)
    • From your workspace select the Main.view.xml file and double click on it to open in with the XML code editor
    • In the code editor search for the <Table tag and add the following attributes:
      • columns=”{/cols}”
      • items=”{/items}”
      • Remove the attribute of noDataText
    • After making the changes to the Table tag it should look like the following:
      
      <Table items="{/items}" columns="{/cols}"  id="__table0">
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    • Under the <items> tag please make sure that you have only one <ColumnListItem> which looks like the following:
      13 - columnlistitem.png

      Notice that the {date} , {temp} … are placeholders for the model data binding. We need only one ColumnListItem under the <items> because this ColumnListItem act as the Template so each row of the table will have 4 columns (date,temp,units and humidity)

    • Now we need also to create the template of the table columns. Like we did for the <items> tag we need to do for the <Columns> tag but this time we will use <Column> tag under the <Columns> and not <ColumnListItem>
    • Under <Columns> please make sure you have only one <Column> which looks like the following:
      14 - column.png
    • After all the changes your Main.view.js file should look like the following:

      15 - main view.png

5 – Writing the business logic

Setting up the data model

Before we start writing the code inside the app controller we need to create our model. Our model will contain all the data that should be presented in the UI that we just build.

Our data model should contain the following information:

  • Country
  • City
  • List of days so each day in the list should have
    • Date
    • Average temperature
    • Units
    • Humidity

In addition the data model should contain the columns of the table.

In order to create our data model please do the following:

  • Select the file models.js which located under the model folder
  • Create a new function with name createAPIModel
  • Inside the function body we need to create our model. Because we consume 3rd party JSON service we must use JSONMODEL (and not ODATAMODEL) so our function body must contain the following lines of code:

    16 - api model.png

  • As you can see from the screenshot above our data model contains the city, country, list of columns and list of items (currently empty)
  • Next we need  to set this model as our global model. To set our model as the global model please do the following:
    • Select the Component.js file and open it for edit
    • Add the following line of the to the bottom of the init function
      
      this.setModel(models.createAPIModel());
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
  • Last thing on the UI that we need to do is to change the title of the page in order to change the title please do the following:
    • Expand  the i18n folder
    • Select the i18n.properties file and open it for edit
    • change the following:
      • appTitle = Open weather API
      • title = Open Weather
    • after we made the changes the i18n.properties file should look like the following:

      22 - i18.png

Writing the app controller

Next we need to write the app business logic. The business logic will be written inside the app controller.

Our controller will do the following:


  • Execute an HTTP request to Open Weather API and query the forecast for the next 16 days in London
  • Map the query results into our data model
  • Update (render) the view

Our controller should contain the following functions:

  • onInit –  a function that will be called when the controller will be created
    17 - onInit.png
    the onInit simply call to the _loadForecast function
  • _loadForecast – execute an ajax request to the Open Weather API and get the forecast for the next 16 days in London
    18 - loadForecast.png
    the _loadForecast do the following:
    • Build the URL and the URL parameters with the following data
      • City is London (q = “London”)
      • Units are celsius (units = “metric”)
      • Query the forecast for the next 16 days (cnt = 16)
      • Date format is json (mode = “json”)
      • App id – if you have your own app id (signup and login is required) then you can specify it here otherwise you can use this one
    • Execute ajax request to the Open Weather API ($.get) with the relevant parameters
    • If we got results (.done()) we call the _mapResults function to map the results to our data model
    • if the request failed (.fail()…) we show an error message to the user
    • _mapResults – map the results from the ajax response to the data model
      19 - map results.png
    • This function get the query results as parameter and update the data model. this mapping is required because we must use a model who fits the data binding that we defined in view
  • _formatDate – format the date into string

    20 - format date.png

After you write the code to all the functions which describe above the main.controller.js file should look like the following:

21 - controller 1.png

21 - controller 2.png

21 - controller 3.png

Run the app !

The last thing that left to do now is to run the app.

In order to run the app select the index.html file and click on the Run button (at the top)

23 - run.png

After you click on the run button a new tab will be opened and you will be able to see the app running.

If the app is not running you can check in the console what went wrong and if you still didn’t manage to figure it our then you can clone the following GIT repository https://github.com/ranhsd/OpenWeatherSample.git into your WebIDE and run it.

That’s it! 🙂

Ran.

m

Assigned Tags

      28 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Denise Nepraunig
      Denise Nepraunig

      And afterwards you could use your newly aquired knowledge and create something with the Chuck Norris Jokes API 😉

      sapui5-hcp-examples/Readme.md at master · denisenepraunig/sapui5-hcp-examples · GitHub

      Author's profile photo Matthias De la Roche
      Matthias De la Roche

      🙂  

      Code runs faster when chuck Norris watches it  

      No statement can catch the ChuckNorrisException.

      No one has ever pair-programmed with Chuck Norris and lived to tell about it

      Author's profile photo Former Member
      Former Member

      It seems the openweathermap requires the API consumers to create an account to adopt the APPID.

      So I tried to changed the destination URL to: http://api.openweathermap.org?APPID=<myAPPID> but It didn't work.When I run the app it always shows "No data". Could you take a look at this?

      Thanks,

      An Thanh

      Author's profile photo Former Member
      Former Member
      Blog Post Author

      Hi An Thanh,

      it looks like to open API weather now require an APP ID . It's very strange because when i wrote this blog (about a month ago) an api key was not required.

      I will update my blog post and explain how to create an api key and use one.

      In your case you get 404 (Not found) error because you must specify which resource you like to consume from the open weather API and in your case you just put the URL but without the resource. So please test the following URL and check if it works for you:http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID={YOUR_API_KEY}

      Thanks a lot !

      Ran.

      Author's profile photo Brendan Conroy
      Brendan Conroy

      Nice example!

      Now that openweathermap.org requires a user and password this has to be entered in HCP Cockpit destination for your OpenWeather destination, refer to this section from above

      2 - Create destination in HCP cockpit

      Author's profile photo Boris Hais
      Boris Hais

      Hi,

      thank you very much for this nice example. I succeed to do it with SAP Web IDE but when I try to export it in Eclipse it's impossible to run the app (just the Fiori blue screen appear & I've no error in the console).

      I tried to run app with "Web app preview" and "Tomcat V7 server".


      I just change in the index.html the source (src= "https://sapui5.netweaver.ondemand.com/resources/sap-ui-core.js")

      Do you have any idea ?

      Thanks in advance for your help.

      Author's profile photo Former Member
      Former Member
      Blog Post Author

      Can you look at your console and check if you see some errors there? I think it may be related to CORS which is cross domain issue.

      Author's profile photo Boris Hais
      Boris Hais

      Thank you for your answer 🙂

      I've no error in the console. This maybe due to the destination.

      Maybe I should add the destination locally ? It's my first app with SAPUI5 on Eclipse maybe I miss something...

      Author's profile photo Former Member
      Former Member

      Hi Ran,

      I have an error when trying to consume a similar web service you up, you could help please reviewing:

      http://scn.sap.com/thread/3958686

      thanks,

      regards,

      Joe Gonzales.

      Author's profile photo Michael Appleby
      Michael Appleby

      Unless you are asking for clarification/correction of some part of the Document, please create a new Discussion marked as a Question.  The Comments section of a Blog (or Document) is not the right vehicle for asking questions as the results are not easily searchable.  Once your issue is solved, a Discussion with the solution (and marked with Correct Answer) makes the results visible to others experiencing a similar problem.  If a blog or document is related, put in a link.  Read the Getting Started documents (link at the top right) including the Rules of Engagement. 

      NOTE: Getting the link is easy enough for both the author and Blog.  Simply MouseOver the item, Right Click, and select Copy Shortcut.  Paste it into your Discussion.  You can also click on the url after pasting.  Click on the A to expand the options and select T (on the right) to Auto-Title the url.

      Thanks, Mike (Moderator)

      SAP Technology RIG

      Author's profile photo Tapan Sarkar
      Tapan Sarkar

      Thanks for a wonderful article. I have tried to import the application from github and wanted to run it as it is
      The only change I did was replacing the API key in Main.Controller.js. But when I am running, it says "No data" , whereas the url below is working fine in the browser

      http://api.openweathermap.org/data/2.5/forecast/daily?q=London&mode=json&units=metric&cnt=16&APPID=c4c70502be918e40972943bc5e9954ef

      I have found the following error in console

      "https://webidetesting1315913-p1941770679trial.dispatcher.hanatrial.ondemand.com/webapp/api.openweathermap.org/data/2.5/forecast/daily?q=London&mode=json&units=metric&cnt=16&APPID=c4c70502be918e40972943bc5e9954ef

      Failed to load resource: the server responded with a status of 404 (Not Found)"

      I have no idea, why and where from the part below is getting added on top of the url for the resource (see the error message above)?

      "https://webidetesting1315913-p1941770679trial.dispatcher.hanatrial.ondemand.com/webapp/"   is getting added

      How to resolve this and make the GitHub source running?

      Thanks

      Author's profile photo Former Member
      Former Member

      You saved me! 😀

      Author's profile photo Mustafa Saglam
      Mustafa Saglam

      Thanks Ran! Great blog, as always :-).

      Author's profile photo Former Member
      Former Member

      The code is running but the app doesn't show up. It displays a blank page with a settings icon in the bottom right corner giving the option of enabling Cordova Facade. I have checked every file of code from your GitHub project but still, it is not running. Also I have included my API KEY .

      Author's profile photo Former Member
      Former Member

      Great blog!! Very detailed and helpful. Thanks for your efforts.

      Author's profile photo Former Member
      Former Member

      Hi Ran,

      this is my header content.

      1. q: London
      2. units: metrics
      3. appId:  "114b08ec1f5a0d27bb86e98b51465b"
      4. cnt:16
      5. mode: json

      And I am getting the response like below.
      Please help me to resolve this.

      404 Not Found


      nginx

      Author's profile photo Former Member
      Former Member
      Blog Post Author

      Can you please post the full URL you are trying to access?

      Author's profile photo Former Member
      Former Member

      https://webidetesting2419893-p1942701631trial.dispatcher.hanatrial.ondemand.com/OpenWeather/data/2.5/forecast/daily?id=1270260&units=metrics&APPID=114b08ec1f5bfbb86e98b51465b&cnt=5&mode=json

       

      Author's profile photo Former Member
      Former Member
      Blog Post Author

      I cannot access it because its running on your own tenant..

      What you need to do is to check if your destination configured correctly as well as your neo-app.json  file in your project.

      Author's profile photo Nitin Kant
      Nitin Kant

      Thank you for this great article. Successfully implemented and tested 🙂

      Author's profile photo Former Member
      Former Member

      Useless Article. Code doesn't work

      Author's profile photo Alexander Waldhier
      Alexander Waldhier

      that is not true, it works perfectly.

       

      OpenWeatherMap changed its API for daily forecasts so that it is not free of charge anymore. You'll have to either pay or change it to the hourly API. I did the latter and it works.

      Author's profile photo Former Member
      Former Member

      https://stackoverflow.com/questions/48396443/unable-to-consume-rest-api-in-sapui5?noredirect=1#comment83782757_48396443

      Author's profile photo Wagner Manganelli
      Wagner Manganelli

      Thank you for writing this article, it was perfect for me 🙂

      Author's profile photo Prakash Waddar
      Prakash Waddar

      Thanks  for Article.

      This Application works perfectly  but  we  need  to  do some minor changes .

      1. Signup  to https://openweathermap.org URL  and  get API Key

      2. Change URL in Main.controller.js

              var sUrl = "/OpenWeather/data/2.5/forecast";

      3. Changes required in for loop  to fetch Temp and humidity data

       

      for (var i = 0; i < results.list.length; i++) { for (var i = 0; i < results.list.length; i++)

      {

      var oTemp = results.list[i].main.temp;

      var date = this._formatDate(results.list[i].dt * 1000);

      aForecastResults.push(

      { date: date,

      temp:  oTemp,

      units: "Celsius",

      humidity: results.list[i].main.humidity }); }

      Author's profile photo Juan Camilo Jaramillo
      Juan Camilo Jaramillo

      Thanks  for Article.

      This Application works perfectly if the application is deployed in SAP Cloud Platform.

      When I deploy it to the Abap Server, it does not work anymore.

       

      • Is there any way to consume these services from the Abap Server?

       

      • Should an additional configuration be made to the server or to the code in order to consume these services on the Abap Server?

       

      For your help, thank you very much!

      Regards.

       

       

       

       

      Author's profile photo Meghanatha shetty
      Meghanatha shetty

      Hi Juan,

      Were you able to deploy the UI5 application with the rest call in ABAP server. I am also trying to implement similar scenario.

      Appreciate your help.

      Thanks

      Megha

      Author's profile photo Juan Camilo Jaramillo
      Juan Camilo Jaramillo

      Hi Meghanatha,

      If it is an external API the best way is to consume it from the ABAP code, and this match with the Odata Service that your application consumes. It was the way we solved it.

       

      I hope this helps.

      Regards.