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:

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

SoftwareVersionType
Java Development Kit, Standard Edition8 
Apache Mavenlatestapplication
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 D:\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 your preferred Java IDE (such as, IntelliJ IDEA or Visual Studio Code). Run the App.main() method. [play]

    1. Open your IDE (IntelliJ IDEA or Visual Studio Code). Within your IDE, open your project folder. Check the status bar of your Java IDE (lower right corner of the window) until the analysis (build) of the project is complete.

    2. Open the src/main/java/com/example/App.java file and review the code. Run the App.main() method (for IntelliJ IDEA, select the green arrow on the left border of the editor, beside the method definition, for Visual Studio Code, choose the Run button just before the definition of the method). A terminal window appears and the program is executed. "Hello World!" is printed in the Terminal.

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

    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.

  4. 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. 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, 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

  5. Choose which IDE you want to use for the following steps. You can choose SAP Business Application Studio, or Intellij IDEA, or Visual Studio Code. Open the project in your development environment, optionally enable source control to better follow code changes in the next steps. [play]

  6. In you IDE of choice, run the App.main() method. [play]

    1. Open the src/main/java/com/example/App.java file and review the code.

    2. If you are using SAP Business Application Studio or Visual Studio Code, choose the Run button just before the definition of the method (it may require a few seconds before Run appears).

    3. if you are using IntelliJ IDEA, choose the green arrow on the left border of the editing area and choose Run App.main()

      Note
      In case you are requested to choose the project type, between Eclipse and Maven. You must choose Maven.
    4. The Debug Console (or the Run window ) is opened and Hello World appears in it.

  7. 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. [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
  8. Modify the project to query your S/4HANA Cloud system, accessible via the following information (replace ### with your user number):

    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, provided in the exercise files (in the code, replace the ">>>YOUR APIKEY<<<" string with your API Key, for example, "FDqbnElM7mgmgqbIKBFHRpS1dvpt6sHD").

    2. Run the App.main() method.

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