Develop Advanced Extensions with SAP Cloud SDK

Exercise: Querying SAP APIs in a TypeScript Program

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

After completing this lesson, you will be able to:

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

Querying SAP APIs in a TypeScript program

Description

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

Prerequisites

For the complete execution of the current exercise, you must have completed 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:

  • ts-call-api-initial.zip[download]: contains the NPM/TypeScript project in its initial status. This project has to be imported as a prerequisite for the execution of the exercise.
  • ts-call-api-solution.zip[download]: contains the NPM/TypeScript 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 the 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 src\app.ts file.
  3. 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.
  4. Open the PowerShell. Execute the following commands:
    Code snippet
    cd <project folder path>
    npm install
    npm run build
    npm run start
    Copy code

Task 1: Querying SAP APIs in a TypeScript Program

Steps

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

  2. Open the project folder using Visual Studio Code.

    1. Open Windows File Explorer. Navigate to the folder. Right-click and execute Open with Code.

  3. Review the application files.

    1. Open the src\app.ts file and review the content.

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

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

  4. Install the NPM project.

    1. In the Visual Studio Code, in the Explorer window, choose NPM SCRIPTSpackage.json. Right-click on package.json and choose Run Install. The node packages indicate that the dependencies are downloaded to the node_modules folder.

  5. Build the TypeScript programs.

    1. In the Explorer window, choose NPM SCRIPTSpackage.jsonbuildRun. The TypeScript files are converted to JavaScript and stored in the dist folder.

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

    1. In the src/app.ts 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 src/app.ts file. Click on the red dot beside line number 1. The breakpoint is deleted.

  7. Open the 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.

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

    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: ts-call-api.

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

    4. In the ts-call-api tab, right-click and choose Upload Files..., browse to the ts-call-api-initial.zip file [download], 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

  9. In SAP Business Application Studio, install the NPM project.

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

  10. In SAP Business Application Studio, build the TypeScript programs.

    1. In the Explorer window, choose NPM SCRIPTSpackage.jsonbuild. Right-click and choose Run. The TypeScript files are converted to JavaScript and stored in the dist folder.

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

    1. In the src/app.ts 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) twice. 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 src/app.ts file. Click on the red dot beside line number 1. The breakpoint is deleted.

  12. Look for the documentation of the Business Partner Service. 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.

  13. In any of Visual Studio Code or SAP Business Application Studio, modify and run the project so that the src\app.ts 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 entire package.json file with the content of the ts-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 src\app.ts file and enter the following code (replace the content of the entire app.ts file with the content of the ts-call-api-2-app-ts.txt file [download] , 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
      import { BusinessPartner, BusinessPartnerAddress } 
      from '@sap/cloud-sdk-vdm-business-partner-service';
      
      import { Destination, GetAllRequestBuilder } 
      from '@sap-cloud-sdk/core';
      
      // Create destination
      let dest: Destination = {
          url: "https://sandbox.api.sap.com/s4hanacloud"
      };
      
      // Create request
      let req: GetAllRequestBuilder<BusinessPartner> =
      BusinessPartner.requestBuilder()
          .getAll()
          .select(
              BusinessPartner.BUSINESS_PARTNER,
              BusinessPartner.FIRST_NAME,
              BusinessPartner.LAST_NAME,
              BusinessPartner.TO_BUSINESS_PARTNER_ADDRESS
                  .select(
                      BusinessPartnerAddress.ADDRESS_ID,
                      BusinessPartnerAddress.COUNTRY,
                      BusinessPartnerAddress.CITY_NAME
                  )
          )
          .filter(
              BusinessPartner.FIRST_NAME.equals("Peter")
          ).addCustomHeaders({
              APIKey: '>>>YOUR API KEY<<<'
          });
      
          // execute request
          req.execute(dest)
              .then(
                  // success
                  (result: BusinessPartner[]) => {
                      console.log(JSON.stringify(result, null, '\t'));
                  },
                  // error
                  (error: any) => {
                      console.log("Error: " + error.message);
                  }
              );
      Copy code
    4. In the Explorer window, choose NPM SCRIPTSpackage.jsonbuildRun.

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

  14. In the Studio, modify the project to switch from the sandbox system to your S/4HANA Cloud system, accessible via the following information:

    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.ts 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
      let dest: Destination = {
          url: "https://sandbox.api.sap.com/s4hanacloud"
      };
      Copy code
      with the following new values:
      Code snippet
      let dest: Destination = {
          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 (pay attention not to delete the final semicolon):
      Code snippet
      .addCustomHeaders(
              { apikey: >>>YOUR API KEY<<<' })
      Copy code
      You can copy the content of the whole app.ts program from the ts-call-api-3-app-ts.txt file [download] .

    2. In the Explorer window, choose NPM SCRIPTSpackage.jsonbuildRun.

    3. In the package.json file, a grey Debug control appears just before the scripts definition. Choose Debugstart node dist/app. 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