Consuming REST API with Basic Authentication- Step-by-Step Guide for the GET Method
2023-11-13 23:6:14 Author: blogs.sap.com(查看原文) 阅读量:7 收藏

In this blog post, I will show you how to consume an API step by step. The API contains various methods, with the most commonly used ones being “Get,” “Post,” and “Delete.”

For the sake of example, in this blog, I will use the “Get” method.

“GET” Method: The “GET” method is used to retrieve information from a web API or query resources (data). This method is used to request data from a specific resource and is typically called with parameters through a URL (web address). A “GET” request typically does not modify data, it only reads it.

     1.Create Destination

First, we will create the Destination that we will use to make the API call. To do this, go to the “SM59” T-code and click the “Create” button, as shown in Figure 1. Then, fill out the information as shown in Figure 1.

Figure%201

Figure 1

In the opened window, fill in the fields marked in Figure 2 with API-specific information. The “Host” field can be different for each API. I used an example link.

For the Port field, if the API link starts with “https,” you can enter “443.”

Figure%202

Figure 2

 After filling in these fields, go to the “Logon & Security” tab. Since the API we are using uses Basic Authentication, select the radio button as shown in the Figure 3. Fill in the “User” and “Password” fields with the credentials provided to you earlier and save the settings.

Figure%203

Figure 3

 Our destination is now ready for use in the program.

     2.Create Program

We are creating an executable program using the SE38 transaction code.

When I reviewed the API documentation, I noticed that there is only one parameter that needs to be sent, which is “quickRfqId.” This number will be entered using the Selection Screen.

          2.1 Preparation of Data

&---------------------------------------------------------------------*
*& Report Z_TEST_API
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT z_test_api.


DATA: lt_header_fields TYPE tihttpnvp,
      mv_uri           TYPE string,
      mv_response      TYPE string,
      mo_http_client   TYPE REF TO  if_http_client,
      mt_header_fields TYPE  tihttpnvp.
DATA: lv_json     TYPE /ui2/cl_json=>json,
      ls_response TYPE Z******* "A structure of a custom type, the same as the result..
DATA lo_response       TYPE REF TO if_rest_entity.

PARAMETERS: p_rfqid TYPE numc10. "Our Input Parameter


mv_uri = '/PromenaRFQ/1.0/quick-rfq/awarding-winners'. "The extension of our API that we will append to the end of our link."

CALL METHOD cl_http_client=>create_by_destination
  EXPORTING
    destination              = 'Z_TEST_DESTINATION' " Logical destination (specified in function call)
  IMPORTING
    client                   = mo_http_client " HTTP Client Abstraction
  EXCEPTIONS
    argument_not_found       = 1 " Connection Parameter (Destination) Not Available
    destination_not_found    = 2 " Destination not found
    destination_no_authority = 3 " No Authorization to Use HTTP Destination
    plugin_not_active        = 4 " HTTP/HTTPS communication not available
    internal_error           = 5 " Internal error (e.g. name too long)
    OTHERS                   = 6.
IF sy-subrc <> 0.
  MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
             WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

The “mv_uri” parameter is the extension of our API that we will append to the end of our link.

We are calling the Destination we previously created. (cl_http_client=>create_by_destination)

APPEND VALUE #( name = 'Content-Type' value = 'application/json' ) TO lt_header_fields.
APPEND VALUE #( name = 'accept' value = 'application/json' ) TO lt_header_fields.

mo_http_client->request->set_header_fields( fields = lt_header_fields ).

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

When examining the API, we can see that there are variables in the “Header fields” that we need to send, and these variables determine the response type. In the code above, we create and set these parameters.

Additionally, we set the method we will use, which is the “GET” method.

         2.2 Create Connection

v_json = /ui2/cl_json=>serialize( data = p_rfqid pretty_name = /ui2/cl_json=>pretty_mode-camel_case ).

mo_http_client->request->set_cdata(
  EXPORTING
    data   =   lv_json       ).
CONCATENATE mv_uri '?quickRfqId=' p_rfqid INTO mv_uri.

cl_http_utility=>set_request_uri(
EXPORTING
 request = mo_http_client->request    " HTTP Framework (iHTTP) HTTP Request
 uri     = mv_uri                     " URI String (in the Form of /path?query-string)
).

mo_http_client->send(
EXCEPTIONS
  http_communication_failure = 1
  http_invalid_state         = 2
  http_processing_failed     = 3 ).

IF sy-subrc <> 0.

ENDIF.
  • First, we use the variable named p_rfqid to convert the data into JSON format using “/ui2/cl_json=>serialize“. This process prepares the data in JSON format.
  • JSON data prepared with “/ui2/cl_json=>serialize” is set for the HTTP request using “mo_http_client->request->set_cdata”.
  • The CONCATENATE operation appends the value of p_rfqid to the mv_uri variable. This creates the Uniform Resource Identifier (URI) for the API request.
  • The URI is configured for the HTTP request using “cl_http_utility=>set_request_uri”.
  • Finally, we send the HTTP request to the API using “mo_http_client->send”. This process checks whether the request was sent successfully and evaluates the result using sy-subrc.

          2.3 Consume Response

Now, after sending an HTTP request, we will process the JSON-formatted response and parse it appropriately to convert it into usable data.

mo_http_client->receive(
 EXCEPTIONS
   http_communication_failure = 1
   http_invalid_state         = 2
   http_processing_failed     = 3 ).
IF sy-subrc EQ 0.
  mo_http_client->response->get_status( IMPORTING code   = DATA(lv_code)
                                                  reason = DATA(lv_reason) ).
  IF lv_code <> '200'.
    CALL METHOD mo_http_client->close
      EXCEPTIONS
        http_invalid_state = 1
        OTHERS             = 2.
*        MESSAGE lv_reason TYPE 'E'.
  ENDIF.
ENDIF.

CLEAR mv_response.
DATA(lo_rest_client) = NEW cl_rest_http_client( io_http_client = mo_http_client  ).

lo_response = lo_rest_client->if_rest_client~get_response_entity( ).
*   Get string data
mv_response = lo_response->get_string_data( ).
/ui2/cl_json=>deserialize( EXPORTING json = mv_response CHANGING data = ls_response ).
  • “mo_http_client->receive” is used to retrieve the HTTP response after sending an HTTP request.
  • If sy-subrc is equal to 0, meaning the HTTP request was sent successfully, the status of the request is checked. “mo_http_client->response->get_status” is used to obtain the status code (lv_code) and the reason (lv_reason) from the HTTP response.
  • If lv_code is not ‘200’, which is typically not a success status code, necessary error handling is performed, or the HTTP request is closed.
  • We create the local object “lo_rest_client” using the “cl_rest_http_client” class to be used for processing the result.
  • The response is retrieved as a string and assigned to the mv_response variable.
  • Finally, the JSON response data (mv_response) is deserialized into the ls_response variable using /ui2/cl_json=>deserialize.

“ls_response” is a structure of the same type as the result, which holds the result data.

          2.4 Result

When we examine the ‘ls_response’ structure in debug mode, we see that our API is functioning and returning a successful result. Now we can use this data in our developments.(Figure 4)

Figure%204

Figure 4

I tried to explain these events with simple examples so that you can implement them in your own scenarios. I hope it was useful.


文章来源: https://blogs.sap.com/2023/11/13/consuming-rest-api-with-basic-authentication-step-by-step-guide-for-the-get-method/
如有侵权请联系:admin#unsafe.sh