Pages

Showing posts with label rest. Show all posts
Showing posts with label rest. Show all posts

Friday, September 13, 2024

Calling External API from ABAP to send an SMS

Requirement: Call an external API to send an SMS message.
Prerequisite: RFC destination and external API.

Note: Make sure to test the RFC connection in SM59. Check the SSL certificates. Ask basis team for help for any connection issues.
 
    DATA: lv_message     TYPE string,

          lv_date        TYPE char10,

          lv_msg         TYPE string,

          lr_client      TYPE REF TO if_http_client,

          lo_rest_client TYPE REF TO cl_rest_http_client,

          lo_response    TYPE REF TO if_rest_entity.


    " This is the message that will be sent to SMS

    WRITE us_flt_order-sddt TO lv_date.

    lv_message = |Change Notification: FO# | && us_flt_order-flt_ordno

      && | Flight | && us_flt_order-fltnr && | to | && us_flt_order-dstn

      && | on | && lv_date.

 

    " Create a link to the API by the RFC destination

    CALL METHOD cl_http_client=>create_by_destination

      EXPORTING

        destination              = 'SMS_API_1' "RFC destination

      IMPORTING

        client                   = lr_client

      EXCEPTIONS

        argument_not_found       = 1

        destination_not_found    = 2

        destination_no_authority = 3

        plugin_not_active        = 4

        internal_error           = 5

        OTHERS                   = 6.

 

    "Instantiate REST client

    CREATE OBJECT lo_rest_client

      EXPORTING

        io_http_client = lr_client.

 

    lr_client->request->set_version( if_http_request=>co_protocol_version_1_0 ).

 

    IF lr_client IS BOUND AND lo_rest_client IS BOUND.

 

      DATA(request_entity) = lo_rest_client->if_rest_client~create_request_entity( ).

      CALL METHOD lo_rest_client->if_rest_client~set_request_header

        EXPORTING

          iv_name  = 'Content-Type'

          iv_value = 'application/json'. "Set your header.


      "Set JSON payload

      request_entity->set_content_type( iv_media_type = if_rest_media_type=>gc_appl_json ).

      lv_msg = '{ "msg" : "' && lv_message && '" }' .

      request_entity->set_string_data( lv_msg ).

 

      "Perform POST

      lo_rest_client->if_rest_resource~post( request_entity ).

 

      "Get response

      lo_response = lo_rest_client->if_rest_client~get_response_entity( ).


      "Get status. 200 for success

      DATA(http_status) = lo_response->get_header_field( '~status_code' ).

      DATA(reason) = lo_response->get_header_field( '~status_reason' ).


      "Read response

      DATA(response) = lo_response->get_string_data( ).

 

      "Close the connection

      CALL METHOD lr_client->close

        EXCEPTIONS

          http_invalid_state = 1

          OTHERS             = 2.

    ENDIF.