Technology Blogs by SAP
Learn how to extend and personalize SAP applications. Follow the SAP technology blog for insights into SAP BTP, ABAP, SAP Analytics Cloud, SAP HANA, and more.
cancel
Showing results for 
Search instead for 
Did you mean: 
Former Member

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)


  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 API - Weather 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:

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
  • 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



  • Click Next and on the next step fill in the following details
    • View Type: XML
    • View Name: Main

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

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

  • 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 .

  • 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
  • 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
    • 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
    • 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
  • 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

               

  • 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:


      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:
    • After all the changes your Main.view.js file should look like the following:

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:

   

  • 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:

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

    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

    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
    • 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

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

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)

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! :smile:

Ran.

m

28 Comments