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:

  • Creating your Pay-As-You-Go 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:

SoftwareVersionType
Node.jslatest Recommended for Most Users versionapplication
Gitlatestapplication
Visual Studio Codelatestapplication

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 N:\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 Visual Studio Code.

    2. Choose FileOpen Folder.... Navigate to your ts-call-api project folder. Choose Select Folder. The project is opened.

  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, choose TerminalNew Terminal.

    2. In the terminal, run the following command:

      Code snippet
      npm install
      Copy code

      The dependent node modules are downloaded to the node_modules folder.

  5. Build the TypeScript programs.

    1. In the terminal, run:

      Code snippet
      npm run build
      Copy code

      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. In Visual Studio Code, activate source control for current project.

    1. Switch to the Source Control tab,

    2. Choose Initialize Repository. The Git source control database is created. All relevant project files are added to the database.

    3. In the Message field, enter initial(or any text you like), choose Commit. If a popup appears, choose Always. The current project files are committed, The source control area is cleaned up. You are now ready to add new modification to your code, any new modification will be tracked in the source control area.

    4. In the src/app.ts file, change Hello World! to Hello SAP! (and save the file). Note that the file is added to the source control area. If you double-click on the file name in the source control area, a windows appears comparing the old and the new version of the file.

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

    1. In your Web browser (for example, Google Chrome), open your SAP BTP Cockpit based on the link you received at subscription time (for example: https://cockpit.eu20.hana.ondemand.com). If requested, enter your user and password.

    2. Choose the training subaccount, that you created in a previous exercise.

    3. Choose ServicesInstances and Subscriptions.

    4. Choose SAP Business Application Studio.

    5. Eventually start the training development space.

    6. Once the space is running, click on training to enter the development space.

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

  10. 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 dependent node modules are downloaded to the node_modules folder.

  11. Build the TypeScript programs.

    1. In the terminal, run:

      Code snippet
      npm run build
      Copy code

      The TypeScript files are converted to JavaScript and stored in the dist folder.

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

  13. In SAP Business Application Studio, activate source control for current project.

    1. Switch to the Source Control tab,

    2. Choose Initialize Repository. The Git source control database is created. All relevant project files are added to the database.

    3. In the Message field, enter initial(or any text you like), choose Commit. If a popup appears, choose Always. The current project files are committed, The source control area is cleaned up. You are now ready to add new modification to your code, any new modification will be tracked in the source control area.

    4. In the src/app.ts file, change Hello World! to Hello SAP! (and save the file). Note that the file is added to the souce control area. If you double-click on the file name in the source control area, a windows appears comparing the old and the new version of the file.

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

  15. Choose your preferred environment between Visual Studio Code or SAP Business Application Studio. The following steps can be executed in any of the two.

  16. In your development environment of choice, 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

    Once the program runs properly, commit your changes in the source control.

    1. in the package.json file, add the following dependencies:

      Code snippet
      "@sap-cloud-sdk/connectivity": "^2.3.0",
          "@sap-cloud-sdk/odata-v2": "^2.3.0",
          "@sap/cloud-sdk-vdm-business-partner-service": "^2.0.0"
      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 { Destination } from '@sap-cloud-sdk/connectivity';
      import { GetAllRequestBuilder } from '@sap-cloud-sdk/odata-v2';
      import { BusinessPartner, businessPartnerService } from '@sap/cloud-sdk-vdm-business-partner-service';
      
      const { businessPartnerApi, businessPartnerAddressApi } = businessPartnerService();
      
      // Create destination
      let dest: Destination = {
          url: "https://sandbox.api.sap.com/s4hanacloud"
      };
      
      // Create request
      let req: GetAllRequestBuilder<BusinessPartner> =
      businessPartnerApi.requestBuilder()
          .getAll()
          .select(
              businessPartnerApi.schema.BUSINESS_PARTNER,
              businessPartnerApi.schema.FIRST_NAME,
              businessPartnerApi.schema.LAST_NAME,
              businessPartnerApi.schema.TO_BUSINESS_PARTNER_ADDRESS
                  .select(
                      businessPartnerAddressApi.schema.ADDRESS_ID,
                      businessPartnerAddressApi.schema.COUNTRY,
                      businessPartnerAddressApi.schema.CITY_NAME
                  )
          )
          .filter(
              businessPartnerApi.schema.LAST_NAME.equals("Smith")
          ).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 terminal, run:

      Code snippet
      npm run build
      Copy code

      The TypeScript files are converted to JavaScript and stored in the dist folder.

    5. In the terminal, run:

      Code snippet
      npm run start
      Copy code

      The program is executed. The extracted business partner information appears in the window.

    6. Choose the Source Control tab.

    7. In the Message field, enter any text (for example sandbox), choose Commit.

  17. 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.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 terminal, run:

      Code snippet
      npm run build
      npm run start
      Copy code

      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