Develop Advanced Extensions with SAP Cloud SDK

Exercise: Querying SAP APIs in a JavaScript Program

Objectives
After completing this lesson, you will be able to:

After completing this lesson, you will be able to:

  • Within a JavaScript program, call a SAP API and retrieve data from SAP S/4HANA Cloud

Querying SAP APIs in a JavaScript Program

Description

In a basic JavaScript program, read the Business Partner API service using SAP Cloud SDK.

Prerequisites

For the complete execution of current exercise, you must first execute the following exercises:

  • Create your Free Trial Account in SAP BTP
  • Activating the APIs in SAP S/4HANA Cloud: this exercise activates the required API in the S/4HANA Cloud tenant.

For the full execution of this exercise, you need to have the following software installed on your laptop:

SoftwareType
Node.jsapplication
Visual Studio Codeapplication
@sap-cloud-sdk/cliapplication

Some steps of this exercise depend on the https://api.sap.com website. As a consequence, they may not run properly if the website is not running 100% correctly. In this case, proceed with the exercise to reach the part that runs against the SAP S/4HANA Cloud instance.

Information for execution

The exercise comes with two archive files:

  • js-call-api-initial.zip[download] contains the Node.js project in its initial status. This project has to be imported as a prerequisite for the execution of the exercise.
  • js-call-api-solution.zip[download] contains the Node.js project in its final status after the correct execution of the exercise. This project can be used to clarify the correct solution or to copy and paste parts of source code.

In the case you wish to run the solution application directly without going through the exercise steps, then complete the following actions (this is not a prerequisite to exercise execution):

  1. Extract the archive to a project folder in your local system.
  2. Edit the app.js file.
  3. Replace ">>YOUR API KEY<<<" with your own API Key (for example, "FDqbnElM7mgmgqbIKBFHRpS1dvpt6sHD"). To know your valid API Key, open https://api.sap.com/api/API_BUSINESS_PARTNER, then Log On and choose Show API Key).
  4. To run the program, in the Windows PowerShell, execute the following commands:
    Code snippet
    cd <project folder path>
    npm install
    npm run start
    Copy code

Task 1: Querying SAP APIs in a JavaScript Program

Steps

  1. On your laptop, in the File Explorer, create a project folder with name js-call-api (if you are in the SAP training system, use D:\workspace\js-call-api. Extract the js-call-api-initial.zip archive [download] to the project folder.

  2. Open the project folder using Visual Studio Code.

    1. Open Windows File Explorer and navigate to the folder.

    2. Right-click and execute Open with Code.

  3. Review the application files.

    1. Open the app.js file and review the content.

    2. Open the package.json file and review the content. In the file, a start script is defined.

    3. Open the .vscode/launch.json file and review the content. It contains a run configuration launching the app.js script.

  4. Set a breakpoint at line 1 of the app.jsfile. Make the application run and stop at the breakpoint. Continue execution. Remove the breakpoint.

    1. In the app.js file, select line number 1. A breakpoint is created and a red dot appears.

    2. Choose F5 (RunStart Debugging). Follow the text in the Debug Console: the program starts in debug mode and stops at the breakpoint.

    3. Choose Step Over (F10). The execution advances one line.

    4. Choose Continue (F5). The execution continues to the end. Hello World! appears in the Debug Console.

    5. In the app.js file, select the red dot beside line number 1. The breakpoint is deleted.

  5. Open SAP Business Application Studio, open the training development space.

    1. In your Web browser (for example, Google Chrome), open https://account.hanatrial.ondemand.com. If requested, enter your user and password.

    2. Choose SAP Business Application Studio.

    3. Enter the training development space.

  6. In SAP Business Application Studio, create a new project folder named js-call-api, open it as a workspace, import in it the content of the js-call-api-initial.zip[download] archive.

    1. Choose FileOpen Workspace... (Ctrl+Alt+W), choose the projects folder and choose Open.

    2. In the Projects tab, right-click and create a sub folder with the name js-call-api.

    3. Choose FileOpen Workspace... (Ctrl+Alt+W), choose the projects/js-call-api folder and choose Open.

    4. In the js-call-api tab, right-click and choose Upload Files..., browse to the js-call-api-initial.zip[download] file, choose Open.

    5. Choose TerminalNew Terminal. A terminal window appears in the lower part of the screen.

    6. In the terminal, execute the following command:

      Code snippet
      unzip *.zip
      Copy code
      The archive content is extracted to the local folder. Execute the following command to remove the archive:
      Code snippet
      rm *.zip
      Copy code

  7. In SAP Business Application Studio, set a breakpoint at line 1 of the app.jsfile. Make the application run and stop at the breakpoint. Continue execution. Remove the breakpoint.

    1. In the app.js file, select line number 1. A breakpoint is created and a red dot appears.

    2. Choose F5 (RunStart Debugging). Follow the text in the Debug Console: the program starts in debug mode and stops at the breakpoint.

    3. Choose Step Over (F10). The execution advances one line.

    4. Choose Continue (F5). The execution continues to the end. Hello World! appears in the Debug Console.

    5. In the app.js file, select the red dot beside line number 1. The breakpoint is deleted.

  8. Look for the Business Partner Service documentation and review it.

    1. In your Web browser, open http://help.sap.com/viewer/product/SAP_CLOUD_SDK

    2. Go to DevelopLatest Version of JSDoc

    3. In the Modules list look for the module containing the business partner service: vdm/business-partner-service.

  9. In the Visual Studio Code or SAP Business Application Studio, modify and run the project so that the app.js program reads the Business Partners with last name Smith. For every business partner, read the following information:

    EntityProperty
    BusinessPartnerBUSINESS_PARTNER
    BusinessPartnerFIRST_NAME
    BusinessPartnerLAST_NAME
    BusinessPartnerAddressADDRESS_ID
    BusinessPartnerAddressCITY_NAME
    BusinessPartnerAddressCOUNTRY
    1. In the package.json file, add the following dependencies:

      Code snippet
      "@sap-cloud-sdk/core": "^1.54.0",  
      "@sap/cloud-sdk-vdm-business-partner-service": "^1.28.2"
      Copy code
      For any problem, you can replace the content of the whole package.json file with the content of the js-call-api-2-package-json.txt file [download] , provided in the exercise files.

    2. Choose TerminalNew Terminal. In the terminal, execute the following command:

      Code snippet
      npm install
      Copy code
      The node packages indicated in the dependencies are downloaded to the node_modules folder.

    3. Open the app.js file and enter the following code (replace the content of the whole app.js file with the content of the js-call-api-2-app-js.txt[download] file, provided in the exercise files, then replace >>>YOUR API KEY<<< with your own API Key. To get your API Key, open https://api.sap.com/api/API_BUSINESS_PARTNER, then Log On and choose Show API Key):

      Code snippet
      const bps = require('@sap/cloud-sdk-vdm-business-partner-service');
      
      // Create destination
      dest = {
          url: "https://sandbox.api.sap.com/s4hanacloud"
      };
      
      // Create request
      req = bps.BusinessPartner
          .requestBuilder()
          .getAll()
          .select(
              bps.BusinessPartner.BUSINESS_PARTNER,
              bps.BusinessPartner.FIRST_NAME,
              bps.BusinessPartner.LAST_NAME,
              bps.BusinessPartner.TO_BUSINESS_PARTNER_ADDRESS
                  .select(
                      bps.BusinessPartnerAddress.ADDRESS_ID,
                      bps.BusinessPartnerAddress.COUNTRY,
                      bps.BusinessPartnerAddress.CITY_NAME
                  )
          )
          .filter(
              bps.BusinessPartner.LAST_NAME.equals("Smith")
          )
          .addCustomHeaders(
              { apikey: '>>>YOUR API KEY<<<' });
      
      // execute request
      req.execute(dest)
          .then(
              // success
              function (result) {
                  console.log(JSON.stringify(result, null, '\t'));
              },
              // error
              function (error) {
                  console.log("Error: " + error.message);
              }
          );
      Copy code
    4. In the package.json file, a grey Debug control appears just before the scripts definition. Choose Debugstart node app.js. A terminal window is opened and the program is executed. The extracted business partner information appears in the window.

  10. Modify the project to query your S/4HANA Cloud system, which is accessible via the following information (replace ### with your user number, replace the URL with the one of your SAP S/4HANA Cloud tenant):

    InformationValue
    URLYour S/4HANA Client tenant URL, for example https://my000000.s4hana.ondemand.com
    Service user nameADDRESS_MANAGER_###
    PasswordWelcomeToTheClouds1!
    Note
    As a prerequisite, for this API to be accessible in the S/4HANA Cloud tenant, you need to execute the previous exercise: Activating the APIs in SAP S/4HANA Cloud.
    1. In the app.js program, change the system information in the following lines (replace ### with your user number, replace the URL with the one of your SAP S/4HANA Cloud tenant):

      Code snippet
      dest = {
          url: "https://sandbox.api.sap.com/s4hanacloud"
      };
      Copy code
      with the following new values:
      Code snippet
      dest = {
          url: 'https://my000000.s4hana.ondemand.com',
          username: 'ADDRESS_MANAGER_###',
          password: 'WelcomeToTheClouds1!'
      };
      Copy code
      You can optionally remove the statement that includes the apikey in the request headers (ensure not to delete the final semicolon):
      Code snippet
      .addCustomHeaders(
              { apikey: >>>YOUR API KEY<<' })
      Copy code
      You can copy the content of the whole app.js program from the js-call-api-3-app-js.txt file [download].

    2. In the package.json file, a grey Debug control appears just before the scripts definition. Choose Debugstart node app.js. A terminal window is opened and the program is executed. The extracted business partner information appears in the window.

Save progress to your learning plan by logging in or creating an account