[ABAP] Einfacher REST-Service (ohne OData)

Piyush Philip auf sap.com hat eine simple Möglichkeit beschrieben, wie man in ABAP einen REST-Service mit den entsprechenden CRUD-Methoden implementieren kann. Dazu ist im Wesentlichen nur eine eigene Handler-Klasse zu implementieren, die von IF_HTTP_EXTENSION erbt. Diese Handler-Klasse wird von einem Service des ICF gerufen.

  1. SE80 -> Neue Klasse anlegen
  2. In der Klasse im Reiter Interfaces: vom Interface IF_HTTP_EXTENSION erben
  3. die Interface-Methode IF_HTTP_EXTENSION~HANDLE_REQUEST implementieren (implementiert nur REST, kein OData-Sevice!)
    METHOD if_http_extension~handle_request.
    
    * Typen
        TYPES: BEGIN OF ty_json_request,
                 param1 TYPE char64,
                 param2 TYPE char64,
               END OF ty_json_request.
    
        TYPES: BEGIN OF ty_json_response,
                 success   TYPE string,
                 msg       TYPE string,
                 operation TYPE string,
               END OF ty_json_response.
    
    * Variablen
        DATA: rv_response TYPE ty_json_response.
        DATA: it_path_info TYPE stringtab.
        DATA: it_query_strings TYPE stringtab.
    
    * Header Fields auslesen
        DATA: it_header_fields TYPE tihttpnvp.
        server->request->get_header_fields( CHANGING fields = it_header_fields ).
    
    * Request Methode (POST, GET, PUT, DELETE ...)
        DATA(lv_request_method) = server->request->get_header_field( name = '~request_method' ).
    
    * URL Pathinfo
        DATA(lv_path_info) = server->request->get_header_field( name = '~path_info' ).
    * erstes '/' entfernen
        SHIFT lv_path_info LEFT BY 1 PLACES.
        SPLIT lv_path_info AT '/' INTO TABLE it_path_info.
    
    * URL Parameter (Query Strings) für Auswertung
        DATA(lv_query_string) = server->request->get_header_field( name = '~query_string' ).
        SPLIT lv_query_string AT '&' INTO TABLE it_query_strings.
    
    * Request Methoden behandeln
        CASE lv_request_method.
    * C (Create)
          WHEN 'POST'.
    * Beispiel: per Request übermittelte JSON-Daten auslesen und behandeln
    * Content-Typ auslesen
            DATA(lv_request_content_type) = server->request->get_content_type( ).
    
    * Wenn Content-Typ JSON
            IF lv_request_content_type CP if_rest_media_type=>gc_appl_json.
    * JSON-Daten auslesen und nach ABAP-Typ konvertieren -> Parameternamen müssen übereinstimmen, sonst HTTP 500!
              DATA(lv_request_cdata) = server->request->get_cdata( ).
    
              DATA: lv_request_abap TYPE ty_json_request.
    
              TRY.
                  /ui2/cl_json=>deserialize( EXPORTING json = lv_request_cdata
                                                       pretty_name = /ui2/cl_json=>pretty_mode-camel_case
                                             CHANGING  data = lv_request_abap ).
    
                CATCH cx_root INTO DATA(e_txt).
                  MESSAGE e_txt->get_text( ) TYPE 'S' DISPLAY LIKE 'E'.
              ENDTRY.
    
              rv_response = VALUE #( success   = 'true'
                                     msg       = lv_request_abap-param1 && ' | ' && lv_request_abap-param2
                                     operation = lv_request_method ).
            ELSE.
              rv_response = VALUE #( success   = 'false'
                                     msg       = 'Request content type must be application/json'
                                     operation = lv_request_method ).
            ENDIF.
    * R (Read)
          WHEN 'GET'.
            DATA(lv_param) = server->request->get_form_field( 'param' ).
    
            rv_response = VALUE #( success   = 'true'
                                   msg       = lv_param
                                   operation = lv_request_method ).
    * U (Update)
          WHEN 'PUT'.
            rv_response = VALUE #( success   = 'true'
                                   msg       = ''
                                   operation = lv_request_method ).
    * D (Delete)
          WHEN 'DELETE'.
            rv_response = VALUE #( success   = 'true'
                                   msg       = ''
                                   operation = lv_request_method ).
    
    * unerlaubte Methoden abfangen
          WHEN OTHERS.
    * Fehlercode 405 zurückgeben
            server->response->set_status( code   = cl_rest_status_code=>gc_client_error_meth_not_allwd
                                          reason = 'method not allowed' ).
    
            server->response->set_content_type( if_rest_media_type=>gc_appl_json ).
    
            server->response->set_header_field( name  = if_http_header_fields=>allow
                                                value = 'POST,GET,PUT,DELETE' ).
    
            rv_response = VALUE #( success   = 'false'
                                   msg       = 'error'
                                   operation = lv_request_method ).
        ENDCASE.
    
    * wenn erfolgreich, dann Wert zurückgeben
        IF rv_response-success = 'true'.
    * HTTP-Status 200
          server->response->set_status( code   = cl_rest_status_code=>gc_success_ok
                                        reason = 'Ok.' ).
    
    * application/json
          server->response->set_content_type( if_rest_media_type=>gc_appl_json ).
    
    * Service-Response als JSON zurückgeben
          server->response->set_cdata( data = /ui2/cl_json=>serialize( data        = rv_response
                                                                       pretty_name = /ui2/cl_json=>pretty_mode-camel_case ) ).
    
        ENDIF.
    
    ENDMETHOD.
    
  4. SICF -> neue ICF-Node (Sub-Element) unterhalb default_host -> sap -> bc als neuen unabhängigen Service anlegen
  5. in der Handlerliste des Service die erstellte Klasse als “Handler” angeben
  6. auf die neue ICF-Node rechtsklicken -> Service aktivieren
  7. auf die neue ICF-Node rechtsklicken -> Service testen
  8. URL aus Browserfenster kopieren (http://domain.de/sap/bc/servicename?sap-client=900)
  9. im Browser mir einem Rest-Plugin (FireFox-Prugin: Rested) testen

Links

[ABAP] HTTP-Client Anfrage (cl_http_client)

Testprogramm: RSHTTP20

Variante 1 (URL)

TRY.
* URL
    DATA(lv_url) = |https://www.google.de/|.

    DATA: o_client TYPE REF TO if_http_client.

* Client-Objekt erzeugen
    cl_http_client=>create_by_url( EXPORTING
                                     url     = lv_url
                                   IMPORTING
                                     client  = o_client ).

    IF o_client IS BOUND.
* Anmeldedaten übermitteln
      o_client->authenticate( username = ''
                              password = '' ).

* Logon-Popup ein- bzw. ausschalten
      o_client->propertytype_logon_popup = o_client->co_enabled.

* HTTP-Prtotokoll-Version
      o_client->request->set_version( version = if_http_request=>co_protocol_version_1_1 ).
* HTTP-Method
      o_client->request->set_method( if_http_request=>co_request_method_get ).

* Header-Felder explizit setzen
*      o_client->request->set_header_field( name  = '~request_method'
*                                           value = 'GET' ).
*
*      o_client->request->set_header_field( name  = 'Content-Type'
*                                           value = 'text/xml; charset=utf-8' ).
*
*      o_client->request->set_header_field( name  = 'Accept'
*                                           value = 'text/xml, text/html' ).

* Cookies akzeptieren
      o_client->propertytype_accept_cookie = if_http_client=>co_enabled.
* Kompression akzeptieren
      o_client->propertytype_accept_compress = if_http_client=>co_enabled.

* HTTP GET senden, evtl. Timeout angeben
      o_client->send( timeout = if_http_client=>co_timeout_default ).

* Response lesen
      o_client->receive( ).

      DATA: lv_http_status TYPE i.
      DATA: lv_status_text TYPE string.

* HTTP Return Code holen
      o_client->response->get_status( IMPORTING
                                        code   = lv_http_status
                                        reason = lv_status_text ).

      WRITE: / 'HTTP_STATUS_CODE:', lv_http_status.
      WRITE: / 'STATUS_TEXT:', lv_status_text.

* Header-Daten der Übertragung
      WRITE: / 'HEADER_FIELDS:'.
      DATA(it_header_fields) = VALUE tihttpnvp( ).
      o_client->response->get_header_fields( CHANGING fields = it_header_fields ).

      LOOP AT it_header_fields ASSIGNING FIELD-SYMBOL(<f>).
        WRITE: / '[', <f>-name, ']', <f>-value.
      ENDLOOP.

* Cookies holen
      WRITE: / 'COOKIES:'.
      DATA(it_cookies) = VALUE tihttpcki( ).
      o_client->response->get_cookies( CHANGING cookies = it_cookies ).

      LOOP AT it_cookies ASSIGNING FIELD-SYMBOL(<c>).
        WRITE: / '[', <c>-name, ']', <c>-value, <c>-xdomain, <c>-path, <c>-secure, <c>-expires.
      ENDLOOP.

* vollständige HTTP Nachricht lesen
      DATA(lv_raw_message) = o_client->response->get_raw_message( ).
      DATA: lv_str_msg TYPE string.

* xstring -> string
      DATA(o_conv_r) = cl_abap_conv_in_ce=>create( input    = lv_raw_message
                                                   encoding = 'UTF-8' ).

      o_conv_r->read( IMPORTING data = lv_str_msg ).

      WRITE: / 'RAW MESSAGE:', lv_str_msg.

* Wenn Status 200 (Ok)
      IF lv_http_status = 200.
* HTTP Body als Character-Daten
        DATA(lv_result) = o_client->response->get_cdata( ).

        WRITE: / 'CDATA:'.
        WRITE: / lv_result.
      ENDIF.

* HTTP Connection schließen
      o_client->close( ).
    ENDIF.
  CATCH cx_root INTO DATA(e_txt).
    WRITE: / e_txt->get_text( ).
ENDTRY.

Variante 2 (HTTP-Alias)

* mit SM59 einrichten
DATA: lv_http_dest TYPE rfcdest VALUE 'HTTP_ALIAS'.

DATA: o_client TYPE REF TO if_http_client.

DATA: lv_http_rc TYPE i.
DATA: lv_reason TYPE string.

TRY.
    cl_http_client=>create_by_destination( EXPORTING
                                             destination = lv_http_dest
                                           IMPORTING
                                             client      = o_client ).

    o_client->request->set_method( if_http_request=>co_request_method_get ).

    o_client->send( ).

    o_client->receive( ).

    o_client->response->get_status( IMPORTING
                                      code   = lv_http_rc
                                      reason = lv_reason ).

    IF lv_http_rc = 200.
      DATA(lv_xml) = o_client->response->get_cdata( ).

      cl_abap_browser=>show_xml( xml_string = lv_xml
                                 title      = 'XML-Daten'
                                 size       = cl_abap_browser=>large ).
    ELSE.
      WRITE: / 'Fehler: ', lv_http_rc.
    ENDIF.

    o_client->close( ).

  CATCH cx_root INTO DATA(e_txt).
    WRITE: / e_txt->get_text( ).
ENDTRY.