Rest Api Step by Step
Rest Api Step by Step
Project Requirement :
1. Create a rest based service, which will be called by customer portal or mobile app for
creating the customer complaint.
2. Generate unique id for each complaint and send the created id in response.
3. If complaint id pass through portal, send the details status of the complaint.
1. Customer Name
2. Mobile Number
3. Email ID
4. Complaint description
Development approach:
1. Create a table.
1: Create Table
enter short text, long text, number length domain, % warning and save.
Page |4
click on Ranges
lo_router->ATTACH(
EXPORTING
IV_TEMPLATE = '/webcomplaint' " Unified Name for Reso
urces
IV_HANDLER_CLASS = 'ZCL_WEBCOMPLAINT_RP' " Object Type Name
RO_ROOT_HANDLER = lo_router.
Page |7
method IF_REST_RESOURCE~GET.
*CALL METHOD SUPER->IF_REST_RESOURCE~GET
* .
/UI2/CL_JSON=>SERIALIZE(
EXPORTING
DATA = gs_complaint " Data to serialize
* COMPRESS = ABAP_FALSE " Skip empty elements
* NAME = " Object name
* PRETTY_NAME = " Pretty Print property names
* TYPE_DESCR = " Data descriptor
RECEIVING
R_JSON = lv_string2 " JSON string
).
MO_RESPONSE->CREATE_ENTITY( )-
>SET_STRING_DATA( iv_data = lv_string2 ).
MO_RESPONSE->SET_HEADER_FIELD(
P a g e | 10
EXPORTING
IV_NAME = 'Content-Type' " Header Name
IV_VALUE = 'application/json' " Header Value
).
endmethod.
similar redefine the post method and add the below code
method IF_REST_RESOURCE~POST.
*CALL METHOD SUPER->IF_REST_RESOURCE~POST
* EXPORTING
* IO_ENTITY =
* .
data(lo_entity) = mo_request->GET_ENTITY( ).
data(lo_response) = mo_response->CREATE_ENTITY( ).
/ui2/cl_json=>DESERIALIZE(
EXPORTING
JSON = lv_data " JSON string
* PRETTY_NAME = " Pretty Print property names
CHANGING
DATA = gs_complaint " Data to serialize
).
* CATCH CX_SY_MOVE_CAST_ERROR. "
NR_RANGE_NR = '01'
OBJECT = 'ZRESTC'
QUANTITY = '1'
* SUBOBJECT = ' '
* TOYEAR = '0000'
* IGNORE_BUFFER = ' '
IMPORTING
NUMBER = GS_COMPLAINT-id
* QUANTITY =
* RETURNCODE =
EXCEPTIONS
INTERVAL_NOT_FOUND = 1
NUMBER_RANGE_NOT_INTERN = 2
OBJECT_NOT_FOUND = 3
QUANTITY_IS_0 = 4
QUANTITY_IS_NOT_1 = 5
INTERVAL_OVERFLOW = 6
BUFFER_OVERFLOW = 7
OTHERS = 8
.
IF SY-SUBRC <> 0.
* Implement suitable error handling here
ENDIF.
GS_COMPLAINT-createdby = sy-uname.
GS_COMPLAINT-CREATEDON = sy-datum.
GS_COMPLAINT-time = sy-uzeit.
/ui2/cl_json=>SERIALIZE(
EXPORTING
DATA = gs_complaint " Data to serialize
* COMPRESS = ABAP_FALSE " Skip empty elements
* NAME = " Object name
* PRETTY_NAME = " Pretty Print property names
* TYPE_DESCR = " Data descriptor
P a g e | 12
RECEIVING
R_JSON = LV_RESPONSE " JSON string
).
endmethod.
click on execute.
P a g e | 13
now before testing add one record in our table , then test the service.
P a g e | 15
Thank you...