Application development with the on-premises or any cloud edition of ABAP SDK for Google Cloud

This document provides you with useful information and resources to help you develop SAP applications using the on-premises or any cloud edition of ABAP SDK for Google Cloud.

This document is intended for SAP ABAP developers.

For a complete list of client libraries that the on-premises or any cloud edition of ABAP SDK for Google Cloud provides, see on-premises or any cloud edition of ABAP SDK for Google Cloud client libraries.

Single-window of interaction

Each Google Cloud API enabled in the ABAP SDK for Google Cloud is represented by an ABAP class, contained in the package /GOOG/CLIENT. An ABAP class consists of multiple public methods and each of these public methods corresponds to a Google Cloud API method. Each public method further consists of IMPORTING parameters and EXPORTING parameters. An ABAP class also contains custom data types, which can be used to construct and map the IMPORTING and EXPORTING parameters. These custom data types map to the API schema definitions.

For every interaction with a target Google Cloud API, its corresponding ABAP class acts as the only interaction point. We call this concept, Single-window of interaction, which shields all the underlying complexities of interacting with a Google Cloud API and presents a simplified interface. This simplified interface enables you to focus on the business solutions being developed using the SDK, without worrying about the underlying SDK features.

Single-window of interaction

Interaction flow

To call an API method, you have the following interaction flow:

  1. Connect to an API.
  2. Construct an input request using the ABAP types.
  3. Call an API method.
  4. Parse errors and exceptions.
  5. Read the response using the ABAP types.

Developer interaction

API client stub

A typical API client stub class consist of the following sections:

  • The ABAP types that map to the API schemas. You use ABAP types to construct an input request and parse the response.
  • The constants and attributes for internal or external usage.
  • The API methods for interacting with API resources.

Class structure

Features

The features of the ABAP SDK for Google Cloud are:

  • HTTP communication: the SDK establishes HTTP connection with the API endpoints.
  • Request marshaling: the SDK converts data in ABAP types to JSON payload that is sent as the request body.
  • Error and exception handling: the SDK handles the return codes and error messages returned by the API, and raises exceptions, if any.
  • Unmarshalling response: the SDK converts back the JSON payload in the response body to corresponding ABAP types.
  • Local error logging: the SDK logs error messages using the logging framework.

API design and API explorer

APIs published by Google follow resource-oriented design. To learn more about Google's API design, see the API design guide.

The ABAP SDK for Google Cloud enables integration with the REST based APIs published by Google.

The API explorer is a tool that lets you try Google Cloud API methods without writing code. Use this tool to study the APIs and required input parameters that you want to pass to their corresponding ABAP methods.

Code constructs

Explains the code constructs that you use to create your ABAP programs using the ABAP SDK for Google Cloud.

Constructor

You first instantiate the API class that you want to use. The constructor of every API class would have a similar pattern as shown in the following example:

    METHODS constructor
      IMPORTING
        !iv_key_name   TYPE /goog/keyname OPTIONAL "Google Cloud Key Name
        !iv_log_obj    TYPE balobj_d OPTIONAL      "Application log: Object name
        !iv_log_subobj TYPE balsubobj OPTIONAL.    "Application log: Subobject
      RAISING
        /goog/cx_sdk .                 "Exception Classes

Importing parameters

The following table explains the importing parameters of a method constructor:

Parameter name Type Required/Optional Description
iv_key_name /GOOG/KEYNAME Required Specify the client key from the configuration that you use to create a connection to Google Cloud. For information about client key configuration, see Authentication.
iv_log_object balobj_d Optional Specify the application log object, which you use to store the SDK generated errors. For information about logging configuration, see Application logging.
iv_log_subobject balsubobj Optional Specify the application log subobject, which you use to store the SDK generated errors. For information about logging configuration, see Application logging.

API method

With resource-oriented design of Google Cloud APIs, an API method is an action that can be performed on a resource published by the API.

For example, if Topics is a resource published by Pub/Sub API, then topics.get is an API method that represent an action on the resource Topics to get the configuration of a topic.

To map an ABAP class method to an API method, you can refer to the method description that follows the pattern:<resource>.<method_verb>.

For example, the method description for a Pub/Sub method is pubsub.projects.topics.get.

  • projects.topics: the resource name.
  • get: the method action.

Method description SAP UI

The name on an ABAP method mapping to an API action follows the pattern:<method_verb>_<resource>.

For example, an ABAP method name for Pub/Sub is: GET_TOPICS

  • GET: the method action.
  • TOPICS: the resource name.

An ABAP method consists of the following sections that map to the REST API methods:

Method name

Importing parameters

An API method can have the following importing parameters. These parameters are optional and you can pass the parameters based on the requirements of an API method that you need to use.

Parameter name Type Category Description

iv_q_<name>

(0 to n)

String Query parameters

The query parameters are appended to the API endpoint after (?).

They are used to define sort, pagination, or filter.

There could be 0 to n query parameters.

iv_p_<name>

(0 to n)

String Path parameters

The path parameters are part of the endpoint.

They are used to point to specific REST API resources.

There could be 0 to n path parameters.

is_input

(0 to 1)

TY_CODE (Class type) Input structure parameters

The data passed as the request body can be mapped using input structure.

The REST API accepts JSON payload as request body. The parameter is a fully-typed parameter that is converted into JSON payload for the API class and the developer is not required to work with JSON.

You can refer to the available class types to understand the ABAP types for mapping the data. For example, Type /GOOG/CL_PUBSUB_V1=>TY_041 maps to the REST Resource: Topic, which is passed as the JSON Payload to the method CREATE_TOPICS.

A method can have a maximum of one request body parameter. Some methods do not have a request body.

Exporting parameters

An API method supports the following exporting parameters:

Parameter name Type Category Description
es_raw data Raw output

This parameter holds the JSON response (Error or Success) returned by the API method. Map this parameter to a variable of type String to receive the JSON response string.

In cases where the response is of any other type, for example, xstring for file output in /goog/cl_storage_v1->get_objects( ) the parameter returns an appropriate value.

Use this parameter for advanced troubleshooting scenarios or for advanced API scenarios.

es_output TY_CODE (Class Type) Output structure

The JSON response is deserialized to ABAP structure and returned using this typed exporting parameter.

You can use this as the primary way to read the API responses using ABAP constructs.

ev_ret_code I (Integer) Return code

The return code that you can use to verify if the API method execution was able to successfully perform its functionality.

For more information, see API return codes, errors, and exceptions.

ev_err_text String Error text

If the method call failed, then this parameter contains the error message that you use to know the reason of failure.

For more information, see API return codes, errors, and exceptions.

ev_err_resp
  • Error type = CHAR 60
  • Error description = STRING
Error response

The parameter provides additional information about the error.

For more information, see API return codes, errors, and exceptions.

Class type

Google Cloud APIs use JSON as the primary format for data exchange. The ABAP SDK for Google Cloud provides ABAP types that map to the JSON schema expected by the Google Cloud APIs.

These ABAP types and related table types are available as class types in every API class that the SDK provides.

The following example shows class type for Pub/Sub API class /GOOG/CL_PUBSUB_V1.

Class type

The description of class type TY_041 under /GOOG/CL_PUBSUB_V1 maps to the REST Resource, Topic, which is passed as JSON Payload to the method CREATE_TOPICS.

ABAP Doc comments are added to all client API classes. While using ABAP Development Tools for SAP NetWeaver (ADT) for development, these comments provide you descriptions of the class types.

API return codes, errors, and exceptions

If an error occurs when the API method of ABAP class is called, the ABAP SDK for Google Cloud passes the error information to the calling program by using the SDK exporting parameters or by raising exceptions.

Return response name

API return code and errors

Google Cloud APIs use an error model that offers consistent experience across different APIs. When a Google Cloud API method is called from the SDK, the following parameters contain the API return code and messages:

To check the status of an API call, use the IS_SUCCESS method. You can use the value of ev_ret_code to determine if an API call was successful or not. In general, when ev_ret_code = 2XX, the method call is considered to be successful. For all other values, the method call is considered unsuccessful.

IF lo_client->is_success( ev_ret_code ).
   "Success: Implement custom code
   ELSE
   "Handle the HTTP error status code
ENDIF.

For some Google Maps Platform APIs, in case you call an API with invalid inputs, the API returns an HTTP success status code 2XX with an error message and error status, instead of an HTTP error status code (4XX or 5XX). This error message and error status in the API response can help you troubleshoot the problem and fix the invalid inputs.

For such Google Maps Platform APIs, in addition to the return code ev_ret_code, check the error message and error status returned in the API response by calling the IS_STATUS_OK method after the API call. The following snippet shows an example of how you can use the IS_STATUS_OK method:

IF lo_client->is_status_ok( ).
  "Success: Implement custom code
  ELSE
  "Handle the HTTP error status code
ENDIF.

The parameter es_err_resp provides additional information about the error. The following table explains the fields in the parameter es_err_resp.

Field Value
es_err_resp-error_description Error message received from the API. This value is same as the parameter ev_error_text.
es_err_resp-error HTTP status description returned from the SAP HTTP client.

Handle errors returned by Google Cloud APIs

Use the following guidance to handle errors returned by Google Cloud APIs:

  • Common error codes: For information about common errors returned by Google Cloud APIs and their cause, see error codes.

  • Capture detailed error: To capture detailed error information with ABAP SDK for Google Cloud, use the exporting parameter es_raw from the SDK class methods and map this parameter to a variable of type String. This variable holds a JSON response containing detailed error messages and specific violations encountered by the APIs.

  • View detailed error: To view detailed error information, use one of the following methods:

    • Debugger: View the contents of the variable that holds the JSON response within the ABAP debugger tool for further analysis.
    • SAP GUI: Use the ABAP class cl_demo_output=>display( lv_response ) for visual representation of the error within a report program. If you are using the API methods in a report program and the program execution is in foreground mode, then use the ABAP class cl_demo_output=>display_json( lv_response ).

      The following code snippet illustrates how to display API response in case of an error:

      DATA lv_response  TYPE string,
        TRY.
            lo_translate = NEW #( iv_key_name = 'DEMO_TRANSLATE' ).
            lo_translate->translate_translations
              EXPORTING
                is_input    = ls_input
              IMPORTING
                es_raw      = lv_response
                es_output   = ls_output
                ev_ret_code = lv_ret_code
                ev_err_text = lv_err_text
                es_err_resp = ls_err_resp.
            IF lo_translate->is_error( lv_ret_code ) = abap_true.
              " Display API response in case of an error
              cl_demo_output=>display_json( lv_response ).
            ENDIF.
          CATCH /goog/cx_sdk INTO lo_exception.
            lv_err_text = lo_exception->get_text( ).
        ENDTRY.
      

  • API specific documentation: Some Google Cloud APIs provide detailed error information and troubleshooting guidance within their individual documentation. To resolve an error related to an API, see the documentation specific to that API, for example, Pub/Sub, Document AI, and Cloud Storage.

Exceptions

When an unexpected error occurs during an API method call, such as incorrect SDK configuration or HTTP communication failure, the SDK raises a class exception of type /GOOG/CX_SDK. You must catch this exception in your code and write an appropriate error handling logic.

Handle exception

You can get the error message by calling the method get_text of the exception class. The error message returned by the exception class has the following format:

/GOOG/MSG : Return_Code - Error_Message

The cause of the error and resolution steps depends on the value of Return_Code.

Value of Return_Code Cause of the error Resolution
461 The ABAP SDK for Google Cloud uses a special return code, 461, to inform that a specific installation and configuration step is not done or completed incorrectly. Corresponding Error_Message provides more details about the error. You must carefully review the installation and configuration instructions for the SDK and ensure they are done correctly.
Any other value This return code is the last HTTP error from the standard SAP HTTP Client Class. This error signifies that the SAP ICM faced a communication issue when calling a Google REST API method. You must carefully review your network, firewall, SAP ICM settings, and make sure that configurations allow HTTP calls to Google Cloud APIs.

For typical error messages triggered in the ABAP SDK for Google Cloud and their resolution, see the troubleshooting guide.

Logging

The ABAP SDK for Google Cloud enables you to log error messages using an embedded logging framework. The log object ZGOOG and subobject ZABAP_SDK are shipped with the SDK transport files that you can use as default objects for log configurations.

As a developer, you can pass your own custom log objects and subobjects while instantiating the API client stub. This requires an additional configuration to indicate to the SDK to use your custom log objects instead of the default log object and subobject.

The following example shows a calling code with custom log object and subobject passed:

TRY.
    CREATE OBJECT lo_api_class
      EXPORTING
        iv_key_name   = 'CLIENT_KEY'
        iv_log_obj    = 'ZSD'            "Application Log Object
        iv_log_subobj = 'ZSD_SALES_ORDERS'. "Subobject
  CATCH /goog/cx_sdk INTO DATA(lo_exception).
      DATA(lv_msg) = lo_exception->get_text( ).
      MESSAGE lv_msg TYPE 'E'.
ENDTRY.

For more information about configuring logging and creating custom log objects, see Application logging.

Data type mapping

The following tables provides a full list of type and format values supported by Google APIs Discovery Service and corresponding ABAP data type.

For more information about type and format values supported by Google APIs Discovery Service, see Type and format summary.

Type value Format value ABAP data type Meaning
any TYPE REF TO DATA The property may have any type. Defined by the JSON Schema spec.
array TABLE TYPE WITH NON UNIQUE KEYS A JavaScript array of values. The items property indicates the schema for the array values. Defined by the JSON Schema spec.
boolean ABAP_BOOL A boolean value, either "true" or "false". Defined by the JSON Schema spec.
integer int32 INT4 A 32-bit signed integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
integer uint32 INT4 A 32-bit unsigned integer. It has a minimum value of 0 and a maximum value of 4,294,967,295 (inclusive).
number double /GOOG/NUM_DOUBLE (string) A double-precision 64-bit IEEE 754 floating point.
number float /GOOG/NUM_FLOAT (string) A single-precision 32-bit IEEE 754 floating point.
object TYPES A JavaScript object. Defined by the JSON Schema spec.
string STRING An arbitrary string. Defined by the JSON Schema spec.
string byte STRING A padded, base64-encoded string of bytes, encoded with a URL and filename safe alphabet (sometimes referred to as "web-safe" or "base64url"). Defined by RFC 4648.
string date STRING An RFC 3339 date in the format YYYY-MM-DD. Defined in the JSON Schema spec.
string date-time STRING An RFC 3339 timestamp in UTC time. This in the format of yyyy-MM-ddTHH:mm:ss.SSSZ. The milliseconds portion (".SSS") is optional. Defined in the JSON Schema spec.
string google-datetime STRING An RFC 3339 timestamp in UTC time. This in the format of yyyy-MM-ddTHH:mm:ss.SSSZ. The milliseconds portion (".SSS") is optional.
string google-duration STRING A string ends in the suffix "s" (indicating seconds) and is preceded by the number of seconds, with nanoseconds expressed as fractional seconds. The period is always used as the decimal point, not a comma.
string google-fieldmask STRING A string where field names are separated by a comma. Field names are
represented in lower-camel naming conventions.
string int64 STRING A 64-bit signed integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).
string uint64 STRING A 64-bit unsigned integer. It has a minimum value of 0 and a maximum value of (2^64)-1 (inclusive).

Demo programs

The ABAP SDK for Google Cloud comes with several demo programs that show you how to consume Google services using the SDK. The demo programs are located in the package /GOOG/DEMO.

The demo programs cover a variety of Google services, such as:

  • Document AI
  • Pub/Sub
  • Cloud Translation
  • Cloud Storage
  • Secret Manager

The demo programs are a great way to learn how to use the ABAP SDK for Google Cloud. They are also a great way to test your configuration. The program documentation with demos provides additional details about each demo.

To access the demo programs, perform the following steps:

  1. In SAP GUI, execute the transaction code /GOOG/SDK_IMG.

    Alternatively, execute the transaction code SPRO, and then click SAP Reference IMG.

  2. Go to ABAP SDK for Google Cloud > Demos.

Serialization and deserialization of API request and response

By default, the ABAP SDK for Google Cloud takes care of marshalling and unmarshalling API requests and responses. Each ABAP class for a Google Cloud API has embedded ABAP types to form the input and output of the methods. To implement custom transformation of request and response, you can use the enhancement spot with SAP Business Add-In (BAdI) definitions that are shipped with the SDK.

Implement custom transformation

The enhancement spot /GOOG/ES_TRANSFORM_JSON, which is shipped with the SDK, includes the following BAdI definitions:

  • /GOOG/BADI_SERIALIZE_JSON: to implement custom serialization logic.
  • /GOOG/BADI_DESERIALIZE_JSON: to implement custom deserialization logic.

You can write specific transformation logic in implementations of these BAdIs. The interfaces of these BAdIs have IV_METHOD_NAME as the importing parameter. You use this parameter to segregate the transformation logic for each API and API method using IF…ENDIF blocks. In your implementation block, set the exporting parameter EV_HANDLED to X.

To implement custom transformation, follow these steps:

  1. For /GOOG/BADI_SERIALIZE_JSON, create an enhancement implementation:

    • For transforming API requests, create an implementation for BAdI /GOOG/BADI_SERIALIZE_JSON with an implementation class.
    • For transforming API responses, create an implementation for BAdI /GOOG/BADI_DESERIALIZE_JSON with an implementation class.
  2. Determine the method ID of the API method for which you need to write the transformation. The method ID is concatenation of the following:

    • The value of the class attribute constant C_SERVICE_NAME.
    • The character #.
    • The description of the API class method for which you need to implement the transformation.

    For example, to write transformations for publishing messages to a Pub/Sub topic, the method ID is: pubsub:v1#pubsub.projects.topics.publish

  3. In the method implementation of the BAdI, perform the following:

    1. For the method ID, write your custom transformation under an IF….ENDIF block.
    2. Set the exporting parameter EV_HANDLED to X.

      If EV_HANDLED is not set to X, then the default marshalling and unmarshalling logic of the SDK is applied.

The custom transformation logic is invoked during runtime. When you use custom transformations, the default serialization and deserialization logic shipped with the SDK is skipped.

Namespace

All Google provided code is placed under the reserved namespace /GOOG/.

Code wizard

Code wizard helps you accelerate development for all the public methods of the API client stubs provided by the ABAP SDK for Google Cloud. Code wizard is similar to the pattern option used in ABAP development. However, in addition to the ABAP pattern, Code wizard also helps with the following:

  • Generates all the required data declarations.
  • Provides placeholders in the code for filing method importing parameters.
  • Generates basic response and exception handling.
  • Provides additional customizations and features in the form of choosing ABAP 7.5 syntax, adding and removing blocks for opening and closing HTTP connections.
  • Provides a copy option for the generated code.

Code wizard only provides a code frame that you can modify as per your requirements. Code wizard supports both SAP S/4HANA and SAP ECC syntax.

To access Code wizard, perform the following steps:

  1. In SAP GUI, execute the transaction code /GOOG/SDK_IMG.

    Alternatively, execute the transaction code SPRO, and then click SAP Reference IMG.

  2. Go to ABAP SDK for Google Cloud > Utilities > Code Wizard.

The following example shows the boilerplate code created for an API method CREATE_TOPICS of the Pub/Sub client stub, /GOOG/CL_PUBSUB_V1:


 DATA:
   lv_p_projects_id TYPE string,
   lv_p_topics_id   TYPE string,
   ls_input         TYPE /goog/cl_pubsub_v1=>ty_041.

 TRY.

* Open HTTP Connection
     DATA(lo_client) = NEW /goog/cl_pubsub_v1( iv_key_name = 'client_key' ).

* Populate relevant parameters
* lv_p_projects_id = 'string_value'.
* lv_p_topics_id = 'string_value'.
* ls_input = .

* Call API method
     CALL METHOD lo_client->create_topics
       EXPORTING
         iv_p_projects_id = lv_p_projects_id
         iv_p_topics_id   = lv_p_topics_id
         is_input         = ls_input
       IMPORTING
*        es_raw           =
         es_output        = DATA(ls_output)
         ev_ret_code      = DATA(lv_ret_code)
         ev_err_text      = DATA(lv_err_text)
         es_err_resp      = DATA(ls_err_resp).

     IF /goog/cl_http_client=>is_success( lv_ret_code ).
       MESSAGE 'Success' TYPE 'S'.
     ELSE.
       MESSAGE lv_err_text TYPE 'E'.
     ENDIF.

* Close HTTP Connection
     lo_client->close( ).

   CATCH /goog/cx_sdk INTO DATA(lo_exception).
     MESSAGE lo_exception->get_text( ) TYPE 'E'.
 ENDTRY.

Get support

If you need help resolving problems with the ABAP SDK for Google Cloud, then do the following: