Exercise: Querying SAP APIs in a Java program

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

After completing this lesson, you will be able to:

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

Querying SAP APIs in a Java program

Description

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

Prerequisites

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

  • 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
Java Development Kit, Standard Edition8application
Apache Mavenlatestapplication
Gitlatestapplication
Cloud Foundry CLIlatestapplication
IntelliJ IDEA Community Editionlatestapplication
Visual Studio Codelatestapplication
Cloudfoundry Manifest YML SupportlatestVisual Studio Code Extension
Debugger for JavalatestVisual Studio Code Extension
Project Manager for JavalatestVisual Studio Code Extension
Extension Pack for JavalatestVisual Studio Code Extension
Test Runner for JavalatestVisual Studio Code Extension
Language Support for Java(TM) by Red HatlatestVisual Studio Code Extension

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

After every step description, you can choose the [play] link to open a recorded simulation of the described actions.

Note

The exercise comes with the following two archive files:

  • java-call-api-initial.zip[download] contains the Maven project in its initial status. This project has to be imported as a prerequisite for the execution of the exercise.
  • java-call-api-solution.zip[download] contains the Maven 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 folder in your local system.
  2. Open the folder with your preferred Java IDE (such as Visual Studio Code). Check the status bar until the analysis of the project is complete.
  3. Edit the src/main/java/com/example/App.java file.
  4. 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).
  5. Run the App.main() method (in Visual Studio Code, choose the Run button just before the definition of the method).

Task 1: Querying SAP APIs in a Java Program

Steps

  1. In your Windows laptop, in the File Explorer, create a project folder with name java-call-api (if you are in the SAP training system, use N:\workspace\java-call-api). Extract the content of thejava-call-api-initial.zip archive [download] to the project folder.

  2. Open the project folder using IntelliJ IDEA Community Edition. Assign the project with the proper SDK. Run the App.main() method. [play]

    1. Open IntelliJ IDEA Community Edition.

    2. In the Welcome window, choose Open. Navigate to your java-call-api project folder. Choose OK. The project is opened in IntelliJ IDEA. The application starts scanning the project, monitor the status in the lower right corner of the window. Wait till the scan is complete.

    3. Choose FileProject Structure.... In the SDK field, select an SDK version 1.8. In the Language level field, select the language level 8 (it should be the default). Choose OK.

    4. Open the src/main/java/com/example/App.java file and review the code. To run the App.main() method, select the green arrow on the left border of the editor, beside the method definition, then choose Run 'App.main()'. A terminal window appears and the program is executed. "Hello World!" is displayed in the terminal.

    5. Close IntelliJ IDEA

  3. Open the project folder using Visual Studio Code. Run the App.main() method.[play]

    1. Open Visual Studio Code.

    2. Choose FileOpen Folder.... Navigate to your java-call-api project folder. Choose Select Folder. The project is opened. The application starts scanning the project, monitor the status in the lower right corner of the window. Wait till the scan is complete.

    3. Open the src/main/java/com/example/App.java file and review the code. To run the App.main() method, choose the small Run command that is located just before the method definition (it may take a couple of minutes before the Run command appears, due to the fact that the project is being analyzed). A terminal window appears and the program is executed. "Hello World!" is displayed in the terminal.

  4. In Visual Studio Code, activate source control for current project. [play]

    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. Choose Commit. In the following popup, choose Always. Enter a Commit message (for example Initial) then choose Enter. 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 App.java 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.

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

    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.

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

    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 name java-call-api.

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

    4. In the java-call-api tab, right-click and choose Upload Files..., browse to the java-call-api-initial.zip file [download], and 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
      Execute the following command to build the maven project:
      Code snippet
      mvn clean install
      Copy code

  7. In SAP Business Application Studio, activate source control for current project. [play]

    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. Choose Commit. In the following popup, choose Always. Enter a Commit message (for example Initial) then choose Enter. 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 App.java 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.

  8. In Visual Studio Code, modify the project so that the App.main() method reads the service using the SAP Cloud SDK. Extract the BUSINESS_PARTNER, LAST_NAME, FIRST_NAME for all the Business Partners whose first name begins with letter E. Commit the changes in Source Control. [play]

    1. Search and add the latest version of the following Java libraries to the pom.xml file in your project:

      Group IDArtifact ID
      com.sap.cloud.sdk.s4hanas4hana-all
      If you encounter an issue, replace the content of the whole pom.xml file with the content of the java-call-api-1-pom.txt file [download], provided in the exercise files.

    2. Replace the whole Main.App() method with the following (in the code, replace the ">>>YOUR APIKEY<<<" string with your API Key, for example, "FDqbnElM7mgmgqbIKBFHRpS1dvpt6sHD"):

      Code snippet
      public static void main(String[] args) throws ODataException {
      
          // Create the destination class
          HttpDestination destination = DefaultDestination.builder()
              .property("Name", "SANDBOX")
              .property("URL", "https://sandbox.api.sap.com/s4hanacloud")
              .property("Type", "HTTP")
              .property("Authentication", "NoAuthentication")
              .build().asHttp();
      
          // Preparing the query to the Business Partner service
          final BusinessPartnerService service =
                  new DefaultBusinessPartnerService();
          BusinessPartnerFluentHelper helper =
              service.getAllBusinessPartner()
                  .select(
                      BusinessPartner.BUSINESS_PARTNER,
                      BusinessPartner.LAST_NAME,
                      BusinessPartner.FIRST_NAME)
                  .filter(
                      BusinessPartner.FIRST_NAME.ge("E")
                          .and(BusinessPartner.FIRST_NAME.lt("F")));
      
          // Setting the API Key in the request header (required for the
          // SAP API Business Hub sandbox system, not required for
          // S/4HANA Cloud).
          helper.withHeader("apikey", ">>>YOUR APIKEY<<<");
      
          // Running the query
          List<BusinessPartner> list = helper.executeRequest(destination);
      
          // Print out the result in a pretty JSON format.
          System.out.println(new GsonBuilder().disableHtmlEscaping()
                  .setPrettyPrinting().create().toJson(list));
      }
      Copy code
      To get the code, replace the content of the whole App.java file with the content of the java-call-api-1-app.txt file [download], provided in the exercise files (in the code, replace the ">>>YOUR APIKEY<<<" string with your API Key, for example, "FDqbnElM7mgmgqbIKBFHRpS1dvpt6sHD").

    3. Run the App.main() method. A list of business partners is extracted and displayed in the terminal window (or in the Debug Console).

      Note
      In the SAP Business Application Studio you may need to re-build the project. To do that, switch to the terminal window and run:
      Code snippet
      mvn clean install
      Copy code
    4. Choose the Source Control tab.

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

  9. Modify the project to query your S/4HANA Cloud system, accessible via the following information (replace ### with your user number): [play]

    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 Main.App() method, change the system information in the following lines:

      Code snippet
      HttpDestination destination = DefaultDestination.builder()
           .property("Name", "SANDBOX")
          .property("URL", "https://sandbox.api.sap.com/s4hanacloud")
          .property("Type", "HTTP")
          .property("Authentication", "NoAuthentication")
           .build().asHttp();
      Copy code
      with the following new values (replace ### with your user number and replace the URL with your own tenant URL):
      Code snippet
      HttpDestination destination = DefaultDestination.builder()
          .property("Name", "S4CLOUD")
          .property("URL", "https://my000000.s4hana.ondemand.com")
          .property("Type", "HTTP")
          .property("Authentication", "BasicAuthentication")
          .property("User", "ADDRESS_MANAGER_###")
          .property("Password", "WelcomeToTheClouds1!")
          .build().asHttp();
      Copy code
      In addition, you can remove the following code that is required for the sandbox, but not required in case of basic authentication:
      Code snippet
      // Setting the API Key in the request header (required for the
      // SAP API Business Hub sandbox system, not required for
      // S/4HANA Cloud).
      helper.withHeader("apikey", ">>>YOUR APIKEY<<<");
      Copy code
      You can copy the content of the whole App.java from the java-call-api-2-app.txt file [download], provided in the exercise files (in the code, replace the ">>>YOUR APIKEY<<<" string with your API Key, for example, "FDqbnElM7mgmgqbIKBFHRpS1dvpt6sHD"), then observe the applied changes in the source control.

    2. Run the App.main() method.

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