Technology Blogs by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
cancel
Showing results for 
Search instead for 
Did you mean: 
former_member184739
Contributor
Hello Everyone,

In this blog we 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.
REPORT z_fetch_slack_data.

*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'.

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

 

Continuation of Report code...
REPORT z_fetch_slack_data.

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

 

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
19 Comments
0 Kudos

Very Informative Blog.

Keep up the good work.

 

Cheers!!

 

noufalcheruvott
Explorer
0 Kudos
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.

former_member184739
Contributor
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
Jelena
Active Contributor
Thanks for sharing! There is no class /UI2/CL_JSON in our ECC EHP6 system, so I'm guessing it comes in with 7.4 or later version. Just for clarification you might want to note which ABAP version was used to develop the code example.

Please also use the code formatting button like in this blog, for example. There are some typos in the code too, I'd suggest to run a syntax check and pretty print on it, then copy-paste back into the blog with proper formatting. It's not clear if this code is from a report or a global class (the method that comes out of the blue is a bit confusing), this should be clarified as well.

Additionally, you might want to take a look at Clean ABAP blog for some recent code guidelines. For example, using prefixes is no longer considered a good practice. Instead, it's better to use descriptive names.
The class /UI2/CL_JSON is part of software component 'SAP_UI', not 'SAP_BASIS', if that is what you were refering to as 7.4.

I appreciate this blog from prabaharan.asokan2, also wishing he could rework the code section so that the presentation matches the importance of this topic.
Jelena
Active Contributor
0 Kudos

SAP_UI component is only available starting with Netweaver 7.4.

former_member184739
Contributor
0 Kudos

Hey jelena.perfiljeva , jelena.perfiljeva2 ,

Thank you for the feedback. I’ve adapted few changes which are suggested like code formatting, pretty print etc. Unfortunately I did not have the backup of entire code, I tried to do the best possible and the whole idea was to give some initial steer to the developers.

Hopefully I will do all your suggestion in my next my next write-up.

Regards,

Prabha

former_member184739
Contributor
0 Kudos
Hello o.does

Thank you for the inputs and heads-up. I've done the rework as much as possible. Hope this helps.

Regards

Prabha
0 Kudos
Thanks Prabha!
former_member259842
Discoverer
Lovely pice of information.. Thanks  for sharing
0 Kudos
Hi Prabha,

 

I ave been able to use as you explained and am able to contact the external API. But Now we have to pass the certificate in the header of the REST call. We have multiple company codes and the external system had given us certificates for each company code. they have been uploaded to STRUST. But Now when we call the API we need to pass the relevant certificate in the header for them to be able to verify the call .

 

How can we do that ? Please suggest.

Thanks!

Sandeep
ailang
Explorer
Well Written Prabha !
gaurav_tripathi3
Explorer
0 Kudos
Very good Prabahakaran !
0 Kudos

Hi Prabahakaran,

 

Hope you are doing well.

 

I am stuck in an assignment where i need to consume a REST API in sap abap. I am new to this technology. I have consumed web services but i am confused how to get the data from REST Based API using POST method.

 

Actually what I get is REST API, Client Credentials and other related stuff.

The service is working fine with POSTMAN application but in sap i am getting 400/Bad Request. There is no Proxy Server involved

 

Can you please help me in getting out of this situation?

 

Many Thanks,

Muhammad Asad Qureshi

balajimeda
Explorer
0 Kudos
Hi Muhammad,

 

Is your issue resolved?


In case you are trying to access Secured REST API for instance OAuth 2.0 protocol based REST APIs. Please follow the code from below SAP WIKI where it tries to access a Facebook API( Secured REST API ) from ABAP Program.


 

https://wiki.scn.sap.com/wiki/display/Security/Access+Facebook+using+the+OAuth+2.0+Client

 

Thanks/Balaji

 

 

 

 
vimoralesg
Explorer
0 Kudos
Hi prabaharan.asokan2,

I have a couple of simple questions regarding the code:

 

  • The step1 and step2 are the same program, right?

  • What is the reference for
    i_rfc_dest​


  • The authorization for the API, shouldn't be part of the SM59 configuration?


 

Thanks,

Israel Morales

 
0 Kudos
Hello prabaharan.asokan2

Do you know why the method
get_string_data

only returns the first 478 characters ?.

 

Thanks,

Javier

 
former_member834510
Discoverer
0 Kudos
HI,

Got Error like :

 

Field "C_USER_ID" is unknown.

 

 
Labels in this area