Skip to Content
Technical Articles

Consuming external / third party REST api’s in SAP using REST handlers – Part 2

Hello Everyone,

This blog will discuss in detail about the technical objects and the ABAP code required to consume the external rest api in SAP using the standard handler classes available in your system. To know about the overview, prerequisites and about the configurations required, please visit the part 1 of this blog series. Let’s get started.

Technical implementation:

In this section, all steps are described that you must implement for calling an external SLACK based web service from ABAP. First we send a GET request to the external REST api and then receive the response data in JSON format. Afterwards this JSON is converted into native ABAP format.

Following are the ABAP classes are used.

CL_HTTP_CLIENT

CL_REST_HTTP_CLIENT

/UI2/CL_JSON

Step 1:

Create a new REST client object with necessary request headers and authorization key.

Destination details should be maintained and received from SM59.

 

*Declarations for REST handlers

data: go_http_client type ref to if_http_client,
go_rest_client type ref to cl_rest_http_client.

*Declarations for Data refereces
data:lo_json type ref to /ui2/cl_json.

*Fetch the SLACK destination details from SM59 and create the HTTP client reference
call method me>create_http_client
exporting i_rfc_dest = gc_rfc_dest
importing e_return = l_wa_return .
if l_wa_return is not initial.
* Send the error message
e_return = l_wa_return.
return.
endif.

method create_http_client.
*& This method is used to fetch the destination details about the SLACK Server from SM59*
*—————————————————————————*
* Data Declarations*
—————————————————————————*
data:lv_reason type string,
lv_utc_timestamp type timestampl.

data GV_AUTH_VAL type STRING .

constants GC_AUTH type STRING value ‘Authorization’ ##NO_TEXT.
constants GC_CONTENT_TYPE type STRING value ‘content-type’
constants GC_ACCEPT type STRING value ‘ACCEPT’ ##NO_TEXT.
constants GC_ACCEPT_VALUE type STRING value ‘application/json’
constants GC_RFC_DEST type RFCDEST value ‘SLACK_REST_API_CONV’ ##NO_TEXT
constants gc_tabname type rstable-tabname value ‘Z_SLACK_LOG’.”Table Name
constants: gc_e type dd26e-enqmode value ‘E’,” E

*Create the HTTP client instance
call method cl_http_client=>create_by_destination exporting
destination = i_rfc_dest
importing
client = go_http_client
exceptions
destination_not_found = 1
internal_error = 2
argument_not_found = 3
destination_no_authority = 4
plugin_not_active = 5
others = 5 .
if sy-subrc ne 0.
“Log the Exception
*Ping Destination Failed get time stamp field
lv_utc_timestamp.
lv_reason = sy-msgv1.
return.
endif.

check go_http_client is bound.
*Set the HTTP header fields
call method go_http_client->request->set_header_field
exporting name = gc_auth
value = gv_auth_val.
call method go_http_client->request->set_header_field
exporting name = gc_accept

value = gc_accept_value.
call method go_http_client->request->set_header_field
exporting name = gc_content_type
value = gc_accept_value.
” set http protocol version go_http_client->request->set_version(
if_http_request=>co_protocol_version_1_0 ).
endmethod.

 

Step 2:

REST call – HTTP GET

We get a string variable that contains the response data in JSON format. To process the data in ABAP, it must be converted into an appropriate ABAP structure or data object for which we use standard parser class

If the request is successful, convert the JSON string into ABAP native internal table format using standard parser class /ui2/cl_json which contains methods to perform serialization and de-serialization. Please read here to know more about these operations.

Catch here is, we need to create a local type or a global type with the attribute names as same as JSON response retrieve from the REST api.

 

*Declations to store the native format data
types: begin of ts_slack_info,
] user type string,
email type string,
end of ts_slack_info .

data ls_slack_data type ts_slack_info.
data GO_HTTP_CLIENT type ref to IF_HTTP_CLIENT .
data: lr_json type ref to /ui2/cl_json.

CHECK go_http_client IS BOUND.
*Set the User ID
IF c_user_id IS NOT INITIAL.
lv_user_guid = c_user_id-zuser_guid.
cl_http_utility=>set_request_uri(
EXPORTING request = go_http_client->request uri = lv_user_guid ).

*Create REST Client object
CREATE OBJECT lo_rest_client
EXPORTING io_http_client = go_http_client.
TRY.
lo_rest_client->if_rest_client~get( ).
DATA(lo_response) = lo_rest_client->if_rest_client~get_response_entity( ).
DATA(lv_http_status) = lo_response->get_header_field( ‘~status_code’ ).
IF lv_http_status NE 200.
lv_error_status = lv_http_status.

*HTTP Request Failed
DATA(lv_reason) = lo_response->get_header_field( ‘~status_reason’ ).

*STOP Processing
e_return-type = gc_err.
e_return-message = lv_reason.
RETURN.
ENDIF.

*Receive the response data in JSON.
DATA(lv_json_data) = lo_response->get_string_data( ).
“Refresh the SLACK response to clear HTTP memory of previous calls
IF go_http_client IS BOUND.
go_http_client->refresh_response( ).
“Close HTTP session (Exception HTTP_NO_MEMORY)
go_http_client->close( ).
ENDIF.

*Collect into the exception table.
CATCH cx_rest_client_exception INTO DATA(lo_rest_client_exception).
ENDTRY.

IF lv_json_data IS NOT INITIAL.
CREATE OBJECT lr_json.
TRY .
lr_json->deserialize_int( EXPORTING json = lv_json_data CHANGING data = ls_slack_data ).

ENDIF.

CATCH cx_sy_move_cast_error INTO DATA(lo_move_cast_error) .

DATA(lv_msg_desrl_err) = `HTTP GET failed: ` && lo_move_cast_error->get_longtext( ). FREE:l_wa_reason,lo_move_cast_error.
ENDTRY.
ENDIF.
ENDIF.

 

Step 3: Troubleshooting

Following are some of the errors that could occur. Part 1 of this blog covers the configurations required to circumvent most of the below errors.

GET or POST method throws exception Communication Error

  • Verify that the specified host name is correct.
  • Check proxy server settings.
    HTTP status is 400 (Bad Request)
  •  Check uri path and parameter string.

HTTP status is 401 (Unauthorized)

  • Check that user name and password as specified in your program matches those of your service instance in external server.

HTTP status is 403 (Forbidden)

  • Proceed as follows to check if the SSL certificate for the external server is installed correctly.
  1. Call transaction SMICM.
  2. Select menu item Goto → Trace File → Display End
  3. If you find the following messages, re-install the SSL certificate.

Disclaimer: Above ABAP code snippets are for illustration purposes only and these are untested. Please tailor/validate these codes based on your business requirements for the production purposes.

Part 3 – We will see how to pull millions of user conversations from the Slack interface into SAP using the background report for initial loading of all data using recursive concept, delta report to pull daily changes after the initial load has completed and also we will touch base on usage of webhooks.

Stay tuned!!!

Hope you enjoyed reading the content.

Ceers

Prabha

3 Comments
You must be Logged on to comment or reply to a post.
  • Dear Prabharan,

     

    How to set the authorisation as mentioned in the below code. how can we set the username and password for accessing the api.

    
call method go_http_client->request->set_header_field
 
     exporting name  = gc_auth
           
     value = gv_auth_val.

    • Hi Deepak.

      Did you try setting the authentication as shown below.

      ” provide service credentials for authentification
      go_http_client->authenticate( username = gc_srv_user password = gc_srv_password ).
      go_http_client->propertytype_logon_popup = if_http_client=>co_disabled.

      I would recommend not to hard-code the credentials like here but you can store it from the custom table with restricted authorizations to display & edit and then retrieve that values in the application code or store these details at operating system level. Please check with your BASIS team and they will be able to do this.

       

      Regards

      Prabha