Developing A REST API in ABAP - SAP Blogs
Developing A REST API in ABAP - SAP Blogs
GetStarted
Solutions Support Training Community Developer Partner
About
Community / Blogs
DevelopingaRESTAPIinABAP
January24,2013 | 5,442Views |
RdigerPlantiko
morebythisauthor
ABAPDevelopment
Follow
TheICFTree
FirstStrategy:HTTPRequestMethod
SecondStrategy:DataTransferFormat
TheCommonPlotforAllRequests
ASpecificTaskthePUTRequest
Session,IdentityandLocking
UsingABAPsBuiltInJSONConverter
Summary
Intworecentblogs,IdemonstratedhowtowritewebclientsofREST
APIswithXML(demoapplicationhere)orJSON(demoapplication
here)asdatatransferformat.Inthisblog,Iwillfocusontheserverside:
HowtoimplementaRESTAPIasABAPrequesthandler.Youcan
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 1/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
inspectallthecodeIamdiscussinghereontheMIGROSBSPwebsite:
ItsallinClassZCL_JOB_DATA.
TheICFTree
Requesthandlersareclassesimplementingtheinterface
IF_HTTP_EXTENSION,whichconsistsofonesinglemethod
HANDLE_REQUEST.Arequesthandlerclasscanbeattachedtoapath
intransactionSICF.AnincomingHTTPrequestwillbeanalyzedbythe
InternetCommunicationFramework,tryingtomatchtherequestpath
againsttheSICFpath.Thematchprocessisstoppedassoonasanode
withanattachedrequesthandlerisfound.Ifthisisthecase,aninstance
ofthehandlerclasswillbecreated,andthemethod
HANDLE_REQUESTwillbecalled.
Ourexampleserviceisattachedtothepath/job/attributes.Theclass
ZCL_JOB_DATAisdeclaredtoberesponsibleforallincomingrequests
wheretherequestpathstartswith/job/attributes:
FirstStrategy:HTTPRequestMethod
Theimplementationoftheinterfacemethod
if_http_extension~handle_request()formstheuppermostlevelof
processing.Therefore,theimplementationonlygivestherough
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 2/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
processingskeleton:Aninstancefordatabaseoperations,aswellasan
instancefortheprocessingoftheRESToperationarecreated,the
requesthandlingisdelegatedtothatinstance,andthereisacatchblock
forerrorprocessingincasethatnoinstancecouldbedeterminedfor
processingtherequest.SuchasituationshouldresultinanHTTP
responsewithstatuscode400BadRequest.
Atthisplace,weareusingtheStrategydesignpattern:Dependingon
theHTTPmethod(GET,PUT,POST,DELETE,OPTIONS),aspecific
instanceiscreated.Eachpossibleinstancecorrespondstoaspecific
strategy.
methodif_http_extension~handle_request.
data:lo_dbtypereftolif_db,
lo_resttypereftolif_rest,
lo_invalid_methodtypereftozcx_error,
lv_reasontypestring.
try.
*Objectfordatabaseoperations
lo_db?=get_db(io_server=server).
*Getthecorrectresthandlerinstance,dependingontheverb(GET,PUT,POST,OPTIONS,DELETE)
lo_rest?=get_rest(io_server=server
io_db=lo_db).
*Dotheoperation
lo_rest>handle_request().
catchzcx_not_foundintolo_invalid_method.
lv_reason=lo_invalid_method>get_text().
server>response>set_status(code=400"BadRequest
reason=lv_reason).
endtry.
endmethod.
Weareusinganamingconventionfortheinstancedetermination:The
classLCL_REST_GETwillbeassociatedwithHTTPverbGET,
LCL_REST_PUTwithPUT,andsoon.Alltheseclassesimplementthe
interfaceLIF_REST.Thisway,wecanusedynamicinstancecreation.
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 3/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
Alternatively,wecouldhavewrittenalargeCASEstatementwith
manyWHENs.TheadvantageoftheCASEwouldbethatthecreate
objectstatementcouldbestaticallycheckedforsyntacticalcorrectness.I
havechosenthedynamicalvariantsinceIfinditclearerandmore
readablethanabunchofWHENbranches.
ObservethattheHTTPrequestmethod(GET,PUT,POST,)is
availableaspseudoheaderfieldwiththename~request_method:
methodget_rest.
data:lv_classnametypeseoclsname,
lv_methodtypestring,
lv_messagetypetext255.
lv_method=io_server>request>get_header_field('~request_method').
concatenate'LCL_REST_'lv_methodintolv_classname.
try.
createobjecteo_rest
type(lv_classname)
exporting
io_request=io_server>request
io_response=io_server>response
io_db=io_db.
catchcx_sy_create_object_error.
lv_message='Method''&''notsupported'(001).
replace'&'inlv_messagewithlv_method.
_raise_with_textzcx_not_foundlv_message.
endtry.
endmethod.
SecondStrategy:DataTransferFormat
NowwehavedifferenthandlerclassesforthedifferentHTTPrequest
methods.Butforallthesehandlers,therearesomecommontasks.One
ofthesecommontasksis:todeterminethecurrentdatatransferformat,
andtoconverttheinputifavailableintoABAPdata,andviceversa:
toconverttheABAPresultdataintotheoutputwiththedesireddata
transferformat(XMLorJSON).
Now,somerequestmethodslikeGETdonotrequireanyrequest
content.Sotheconversionofincomingdataisperformedbythose
methodhandlersthatknowtheyrequirecontentdata.Ontheother
hand,therewillalwaysbearesultofthefollowingdatatype:
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 4/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
types:
beginofty_result,
msgtypetypesymsgty,
messagetypeclength255,
jobstypezjobs_tab,
endofty_result.
Theremaynotalwaysbeentriesinthejobtable.Butnotevery
componentofthisstructurewillbeinitial.Ifthereisnojobtable,then
usuallytherewillbeamessage.Sotheconversionoftheresultcan
alwaysbeperformed.
Itmakessensetoworkwithanabstractconverterclass,thespecific
subclassescontainingtheconversionalgorithmspercontenttype.This
isthesecondapplicationoftheStrategypattern.
classlcl_converterdefinitionabstract.
publicsection.
classmethodsget_instance
importing
iv_accepttypestring
returningvalue(eo_instance)typereftolcl_converter.
methodscontent_typeabstract
returningvalue(ev_content_type)typestring.
methodsget_entered_dataabstract
importing
iv_cdatatypestring
exporting
es_jobtypezjobs
raisingzcx_parse_error.
methodsresult_to_cdataabstract
importing
is_resulttypety_result
exporting
ev_cdatatypestring.
endclass."lcl_converterDEFINITION
ThestaticmethodLCL_CONVERTER=>GET_INSTANCE()makesthe
distinction,dependingontheAcceptheaderfieldoftheHTTPrequest:
classlcl_converterimplementation.
methodget_instance.
ifiv_acceptcs'application/json'.
createobjecteo_instancetypelcl_json_converter.
else.
createobjecteo_instancetypelcl_xml_converter.
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 5/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
endif.
endmethod."get_instance
endclass."lcl_converterIMPLEMENTATION
TheCommonPlotforAllRequests
Wecanextractcommontasksintoasuperclasslcl_restofallspecific
methodhandlers,implementingtheinterfacelif_rest~handle_request()
onceforallsubclasses.
Thecommoncodeinthesuperclasseneedstobemixedwithspecific
code,implementedinthesubclassanddefiningthespecificbehaviourof
thatsubclass.Toachievethis,wecallatthedesiredpointoftimein
lif_rest~handle_request(),anabstractmethoddo(),whichhastobe
redefinedinthesubclasses.Thisdo()methodwillcontainthespecific
action.
Now,thecommonimplementationlif_rest~handle()inthesuperclass
onlydefinestheflowoftheprocessing,leavingtheconcreteactionsto
thesubclassesortodelegateslikego_converter:
1.Executethespecificactionbycallingdo(),
2.Errorhandling,withHTTPerrorcode400BadRequestincase
ofconversionerror(wrongincomingdata),orsettingresponse
dataforanerrormessageincaseofanapplicationerror,
3.Theresultstructureismappedtotheresponsedatastructure
(XMLorJSON),usingthecorrespondingconverterinstance,
4.Finally,theresponsedataisplacedintothebodyoftheHTTP
response,andalsotheappropriateresponsetypeisset:
application/json,ortext/xml.
Thisisthegeneralsketchtheresponseprocessingthatisvalidforall
HTTPrequestmethodsandforallcontenttypes(XMLaswellasJSON).
Thedetailsarecontainedinthecalledmethods.
methodlif_rest~handle_request.
data:lo_extypereftocx_root,
lv_cdatatypestring,
ls_resulttypety_result.
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 6/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
try.
*Executethespecificoperation
do(importinges_result=ls_result).
catchzcx_parse_errorintolo_ex.
go_response>set_status(code=400"Badrequest
reason=lo_ex>get_text()).
set_response_parameters().
return.
catchzcx_errorintolo_ex.
ls_resultmessage=lo_ex>get_text().
ls_resultmsgtype='E'.
endtry.
*ConvertresultstructureintoJSONorXML,respectively
callmethodgo_converter>result_to_cdata
exporting
is_result=ls_result
importing
ev_cdata=lv_cdata.
*Placetheresultintheresponsebody
callmethodset_response
exporting
iv_content_type=go_converter>content_type()
iv_cdata=lv_cdata.
endmethod."handle_request
ASpecificTaskthePUTRequest
Letslookataspecifictaskforillustration:ThePUTrequestwhich
alwaysisatasktoupdateorinsertjobattributesforagivenIDonthe
database.Asfollowsfromthedesign,thereisanownlocalclass
LCL_REST_PUThandlingPUTrequests.Actually,forthisrequest
handler,therewasonlythedomethoditselftoimplement(whichisthe
absoluteminimumforaspecifictaskclasstoimplement:do()isabstract
intheparentclass.Withoutanimplementation,noinstancescouldbe
built.):
classlcl_rest_putdefinitioninheritingfromlcl_rest.
protectedsection.
methodsdoredefinition.
endclass."lcl_rest_putDEFINITION
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 7/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
Theimplementationgoesasfollows:
ThejobwiththespecifiedIDisreadfromthedatabase(ifanID
wasspecifiedfornewjobs,thisisnotthecase),
Theentereddatawillbeparsedintoanls_jobstructure,usingthe
appropriatego_converterinstance,
Andfinally,thesave()methodiscalled.Itisimplementedinthe
superclass,sinceotherrequestmethodsuseit,too.
classlcl_rest_putimplementation.
methoddo.
data:ls_jobtypezjobs,
lv_idtypezjobsid.
try.
get_job_by_id(importinges_job=ls_job).
lv_id=ls_jobid.
catchzcx_not_found.
endtry.
clearls_job.
callmethodgo_converter>get_entered_data
exporting
iv_cdata=go_request>get_cdata()
importing
es_job=ls_job.
ifls_jobisnotinitial.
iflv_idisnotinitial.
ls_jobid=lv_id.
endif.
save(changingcs_job=ls_job).
es_resultmessage='Job&hasbeensaved'(002).
replace'&'ines_resultmessagewithls_jobid.
es_resultmsgtype='S'."successmessage
insertls_jobintotablees_resultjobs.
endif.
endmethod."do
endclass."lcl_rest_putIMPLEMENTATION
NotethattheimplementationofthistaskdoesntcareabouttheHTTP
datastructure,theformatactuallyinuse,noraboutthedetailsofthe
transferdataformat.ItsimplyworkswithABAPdatastructuresls_jobfor
theinputandes_resultfortheoutput.
Session,IdentityandLocking
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 8/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
Inthetestapplications(neitherintheJSONappnorintheXMLapp),
thereisneitherloginnorenqueueofthedata.Sincetheapplicationsare
openforeverybody,thisworksonlysinceIdontreallyoperateona
databasetableZJOBS.Actually,eachclientwhocallstheapplicationis
workingwithhisownsessiondata,sohedoesntconflictwithother
usersoperations,andishimselfnotdisturbedbyotherusers.The
sessiondataarepreservedforhimasserversidecookies,survivingthe
singledialoguestep(forexamplereloadingthepagewouldreproduce
thecurrentstateofthedata).
WhenawebclientiswrittenasBSP,thereisasessionIDavailablein
theattributeruntime>server_id.ThissessionIDidentifiestheparticular
browserinstancethatmadetherequest.Ontheclientside,thissession
IDisalwayscontainedinacookiecalledsapappcontext.Ifan
applicationhasstatewhichhastobepreservedwithasessionID,theID
hastobeextractedfromthesapappcontextcookieandhastobe
passedasaqueryparameterwithalltheAjaxrequests.Hereisthe
functionwhichextractsthesapappcontextfromthecookie:
functionget_appcontext(){
varlAppcontextCookie=document.cookie.match(/sapappcontext=(.*?)(?:;|$)/
returnlAppcontextCookie&&
(lAppcontextCookie.length>=2)&&
unescape(lAppcontextCookie[1])||"";
}
Theappcontextreturnedfromthisfunction,canbepassedasquery
parameterwitheveryAjaxrequest.Ontheserverside,thesessionID
canbeextractedfromthatparameter:
methodget_session_id.
data:lv_app_contexttypestring,
lv_app_context64typestring.
*Readtheformfield,providedbytheAjaxrequest
lv_app_context64=io_server>request>get_form_field('sap_appcontext').
iflv_app_context64isnotinitial.
*Base64decode
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 9/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
lv_app_context=cl_http_utility=>decode_base64(lv_app_context64).
*ExtracttheSessionID
findregex'sapsessionid=([^;]+)(?:;|$)'
inlv_app_context
submatchesev_session_id.
endif.
ifev_session_idisinitial.
ev_session_id=io_server>session_id.
endif.
endmethod.
Asafallback,inline22,theserver>session_idisused.However,there
willbeanewserver>session_idforeachrequest,whichresultsinfresh
sessiondatawitheachdialoguestep.Ifyoureallyneedsession
management,itisessentialthatthesessionidispassedtotheserver.
Itisagoodideatocombinethesessionidwiththeloginprocedure:If
theuserauthenticates,hisbrowserreceivesasessionidwithalimited
validity.ThatsessionIDhastobepassedwitheachsuccessiveREST
operation.InABAP,itcanbeusedtostoreandretrievesessionspecific
datainthedatabasetableSSCOOKIE,viaitsdatabaseaccessclass
CL_BSP_SERVER_SIDE_COOKIE.
Thiscouplingofasessionidwithloginisroughlythewayhowthe
RESTAPIfortheHPQualityCenterworks.
UsingABAPsBuiltInJSONConverter
WhiletheXMLconverterinstanceisprettystraightforwardtoimplement
callinganXSLTtransformationforXML>ABAP,andanotheronefor
thewaybackitmightcomeasasurprisethattheJSONconversion
canbehandledexactlythesameway:withtransformations.Thisis
possiblesincethecalltransformationstatementsupportstheJSON
format(atleastasperSAP_BASIS702).JSONisautodetectedand
parsedintoanintermediateJSONXMLformat.Thiscanbeprocessed
withanarbitraryXSLTtransformation,andconvertedintootherXML
documentsortoABAPdata.
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 10/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
Forexample,aPUTrequestfromourtestapplicationmaysendthe
followingJSONdatatotheserver:
{
"ID":"0001",
"REPID":"RSNAST00",
"VARID":"UXPD_KUBE_KV",
"PRIO":"2",
"RESTART":"X",
"DESCR":"Outputallsalesorderconfirmations",
"CONTACT":"RainerZufall"
}
IfastringwiththiscontentispassedasSOURCEXMLtoABAPsCALL
TRANSFORMATIONstatement,theJSONwillbeparsedintoanXML
representationlikethisone(theformatiseasytounderstandIthinka
detailledexplanationisnotnecessaryhere):
<?xmlversion="1.0"encoding="utf8"?>
<object>
<strname="ID">0001</str>
<strname="REPID">RSNAST00</str>
<strname="VARID">UXPD_KUBE_KV</str>
<strname="PRIO">2</str>
<strname="RESTART">X</str>
<strname="DESCR">Outputallsalesorderconfirmations</str>
<strname="CONTACT">RainerZufall</str>
</object>
WhenprocessinganarbitraryXSLTtransformation,withtheCALL
TRANSFORMATIONstatement,andpassingaJSONstringassource,
theXSLTwilloperateonthisinternalJSONXMLrepresentation.Itis
easytotransformsuchaJSONXMLdocumentintoABAPdatatobe
moreprecise:totransformitintoanasXMLrepresentationofABAP
data.Forexample,considerthefollowingXSLTtransformation:
<xsl:transformversion="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform
<xsl:templatematch="/">
<asx:abapxmlns:asx="http://www.sap.com/abapxml"version="1.0">
<asx:values>
<JOB>
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 11/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
<xsl:applytemplates/>
</JOB>
</asx:values>
</asx:abap>
</xsl:template>
<xsl:templatematch="str">
<xsl:elementname="{@name}">
<xsl:valueofselect="."/>
</xsl:element>
</xsl:template>
</xsl:transform>
WhenappliedtotheJSONstring,itwillproducethefollowingresult:
<?xmlversion="1.0"encoding="UTF8"?>
<asx:abapxmlns:asx="http://www.sap.com/abapxml"version="1.0">
<asx:values>
<JOB>
<ID>0001</ID>
<REPID>RSNAST00</REPID>
<VARID>UXPD_KUBE_KV</VARID>
<PRIO>2</PRIO>
<RESTART>X</RESTART>
<CONTACT>RainerZufall</CONTACT>
<DESCR>Outputallsalesorderconfirmations</DESCR>
</JOB>
</asx:values>
</asx:abap>
ThisisavalidABAPdatadescription.Ifthetransformationisnamed
ZJSON2JOB,thedatacansimplybeimportedintoanABAPdata
structurewiththecomponentsID,REPID,andsoonasisthestructure
es_jobinthefollowingimplementationoftheJSONconverter.
classlcl_json_converterimplementation.
methodget_entered_data.
data:lo_extypereftocx_transformation_error.
cleares_job.
checkiv_cdatacnspace.
try.
calltransformationzjson2job
sourcexmliv_cdata
resultjob=es_job.
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 12/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
catchcx_transformation_errorintolo_ex.
raise_parse_error(lo_ex).
endtry.
endmethod."get_entered_data
ManythingscanbedonewiththeidentitytransformationID,withno
needtodefineanownXSLTtransformationatall.Ifyoucanimposethe
JSONdatastructuretobeusedinthewebapplication,itisofadvantage
tousesuchacanonicalstructure.Forexample,considerwrappingthe
JSONhashwiththejobattributesintoanotherhash,makingitthevalue
forsomesymbolickeynamelikeJOB:
{
"JOB":{
"REPID":"RSNAST00",
"VARID":"UXPD_KUBE_KV",
"PRIO":"2",
"RESTART":"X",
"DESCR":"Outputallsalesorderconfirmations",
"CONTACT":"RainerZufall",
"ID":"0001"
}
}
Thenthedatacouldbeparsedintoastructurewithouttheneedof
developingacustomXSLTtransformation,simpleusingtheidentity:
calltransformationid
sourcexmliv_cdata
resultjob=es_job.
Inthisexample,sinceIhavewrittenthewebclientandtheserverside
processing,Icouldhavechosenthismorecanonicalformat.Butbynot
chosingit,IlearnedhowtoworkwithmoreflexibleJSONdataformats.
ThereareseveralreasonsforworkingwithnoncanonicalJSON
representationsofABAPdata:
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 13/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
AJSONformatmaybedesignedinfavourofthewebapplication
tooptimizethereadabilityoftheclientJavaScriptcodeworking
onthedata.
TheremaybeclientcomponentsrequiringaparticularJSON
formats.Forexample,thejQuerydatatablerequiresthetable
datatobepassedasanarrayofarrays:
http://www.datatables.net/release
datatables/examples/data_sources/ajax.html
JSONbasedthirdpartyservicesmaybecalledfromtheABAP
side(withaHTTPclientobject)
ABAPdatamaybeprojectedtotheessentialdata,reducingthe
messagesizetothedatawhicharereallyneeded.
Justtoillustrate,letshavealookattheotherconversionthewayout
fromtheservertotheclient.Again,theformatdiffersslightlyfromthe
canonicalJSONformat,whichwouldsimplifytheABAPsidehandling
considerably.Asmentioned,theresultdatastructurecontains
amessage,
amessagetype,
andatableofjobattributes:
types:
beginofty_result,
msgtypetypesymsgty,
messagetypeclength255,
jobstypezjobs_tab,
endofty_result.
ThefollowingformatwouldbeaperfectJSONpendantforthisstructure.
Itcouldbesimplyproducedwiththeidentitytransformation,passingas
sourceresult=ls_result(wherels_resultisastructureoftype
ty_result):
AllthecomponentnamesmatchperfectlywiththeJSONhashkey
names,
AninternaltableismappedasaJSONarrayofhashs,eachhash
representingoneentryofthetable,
AndthereisatoplevelhashwithasymbolicnameRESULTfor
thecompletething:
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 14/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
{
"RESULT":{
"MSGTYPE":"I",
"MESSAGE":"Test",
"JOBS":[
{
"ID":"0001",
"REPID":"ZZTEST",
"VARID":"VARI1",
"PRIO":"1",
"RESTART":"X",
"CONTACT":"HarryHaller",
"DESCR":"Ahopelessjob"
},
{
"ID":"0002",
"REPID":"ZZTEST2",
"VARID":"VARI2",
"PRIO":"3",
"RESTART":"",
"CONTACT":"PeterPan",
"DESCR":"Ajuvenilejob"
}
]
}
}
ButtheJSONformatthattheRESTAPIsupports,actuallydiffersin
somedetails:
Thejobsaredesignednotasanarray,butasahash,withtheID
ashashkey.
Thereisnoredundanthash,wrappingthewholethingasthe
valueforsomekey.
ThecomponentforMSGTYPEisdifferent.Itissimplycalled
TYPE.
Hereisanexampleinstance:
{
"JOBS":{
"0001":{
"REPID":"RSNAST00",
"VARID":"UXPD_KUBE_KV",
"PRIO":"2",
"RESTART":"X",
"CONTACT":"RainerZufall",
"DESCR":"Outputallsalesorderconfirmations"
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 15/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
},
"0002":{
"REPID":"RBDAPP01",
"VARID":"UXPD_EDI_GUT02",
"PRIO":"3",
"RESTART":"X",
"CONTACT":"HerbertHurtig",
"DESCR":"CreditMemos"
}
},
"MESSAGE":"",
"TYPE":""
}
Weproceedinasimilarwayasabove,onlyintheotherdirection:based
ontheABAPdatatypety_result,wewriteanXSLTtransformationto
obtaintheinternalJSONXMLformatcorrespondingtothisJSONdata
string.
TheJSONXMLdataformatofthedesiredJSONdatastringlookslike
this:
<?xmlversion="1.0"encoding="utf8"?>
<object>
<objectname="JOBS">
<objectname="0001">
<strname="REPID">RSNAST00</str>
<strname="VARID">UXPD_KUBE_KV</str>
<strname="PRIO">2</str>
<strname="RESTART">X</str>
<strname="CONTACT">RainerZufall</str>
<strname="DESCR">Outputallsalesorderconfirmations</str>
</object>
<objectname="0002">
<strname="REPID">RBDAPP01</str>
<strname="VARID">UXPD_EDI_GUT02</str>
<strname="PRIO">3</str>
<strname="RESTART">X</str>
<strname="CONTACT">HerbertHurtig</str>
<strname="DESCR">CreditMemos</str>
</object>
</object>
<strname="MESSAGE">Test</str>
<strname="TYPE">I</str>
</object>
Sothisisthetargetthathastobeobtainedasresultofthe
transformation.Ontheotherhand,theasXMLformatofthestructure
ty_resultlookslikethis:
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 16/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
<?xmlversion="1.0"encoding="utf8"?>
<asx:abapxmlns:asx="http://www.sap.com/abapxml"version="1.0">
<asx:values>
<DATA>
<JOBS>
<ZJOBS>
<ID>0001</ID>
<REPID>RSNAST00</REPID>
<VARID>UXPD_KUBE_KV</VARID>
<PRIO>2</PRIO>
<RESTART>X</RESTART>
<CONTACT>RainerZufall</CONTACT>
<DESCR>Outputallsalesorderconfirmations</DESCR>
</ZJOBS>
<ZJOBS>
<ID>0002</ID>
<REPID>RBDAPP01</REPID>
<VARID>UXPD_EDI_GUT02</VARID>
<PRIO>3</PRIO>
<RESTART>X</RESTART>
<CONTACT>HerbertHurtig</CONTACT>
<DESCR>CreditMemos</DESCR>
</ZJOBS>
</JOBS>
<MESSAGE>Test</MESSAGE>
<MSGTYPE>I</MSGTYPE>
</DATA>
</asx:values>
</asx:abap>
AndthisistheXSLTprogramthatwillperformthetransformation:
<xsl:transformxmlns:xsl="http://www.w3.org/1999/XSL/Transform"version
<xsl:templatematch="DATA">
<object>
<xsl:applytemplates/>
</object>
</xsl:template>
<xsl:templatematch="JOBS">
<objectname="JOBS">
<xsl:applytemplates/>
</object>
</xsl:template>
<xsl:templatematch="ZJOBS">
<objectname="{./ID}">
<xsl:applytemplatesselect="*[name()!='ID']"/>
</object>
</xsl:template>
<xsl:templatematch="ZJOBS/*|MESSAGE">
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 17/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
<strname="{name()}">
<xsl:valueofselect="."/>
</str>
</xsl:template>
<xsl:templatematch="MSGTYPE">
<strname="TYPE">
<xsl:valueofselect="."/>
</str>
</xsl:template>
</xsl:transform>
Weseethat,basically,foreachdeviationfromthecanonicalJSON
representationofABAPdata,thereisatemplateintheXSLT
transformationhandlingthisdeviation.Forexample,thedifferentname
TYPEinsteadofMSGTYPEinthetargetishandledwiththetemplate
<xsl:templatematch="MSGTYPE">
<strname="TYPE">
<xsl:valueofselect="."/>
</str>
</xsl:template>
TheIDhastoberearranged:Frombeingasimpleattributeofthe
ZJOBSdatastructure,ithastoberaisedonelevelhighertobecomethe
keyofahash.Alltheotherattributes,exceptID,arecopiedasstring
nodesintotheresult.Forthis,thesetwotemplatesarenecessary:
<xsl:templatematch="ZJOBS">
<objectname="{./ID}">
<xsl:applytemplatesselect="*[name()!='ID']"/>
</object>
</xsl:template>
<xsl:templatematch="ZJOBS/*|MESSAGE">
<strname="{name()}">
<xsl:valueofselect="."/>
</str>
</xsl:template>
Mappingthety_resultdataobjectintoaJSONstringoftheexpected
format,isnowperformedinABAPwiththefollowingcode:
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 18/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
methodresult_to_cdata.
data:lo_writertypereftocl_sxml_string_writer.
lo_writer=cl_sxml_string_writer=>create(type=if_sxml=>co_xt_json).
calltransformationzjobs2json
sourcedata=is_result
resultxmllo_writer.
ev_cdata=cl_abap_codepage=>convert_from(lo_writer>get_output()).
endmethod."result_to_cdata
Thatsall:ev_cdatawillthencontaintheJSONdatastring,tobeplaced
intheHTTPresponsebody.
Summary
IoutlinedsometypicaltopicsconcerningtheimplementationofREST
APIsinABAP.Itispossibletokeepseparateconcernsinseparate(local
orglobal)classesbyapplyingpatternslikestrategy.Thisishowthe
classZCL_JOB_DATA,servingmydemoRESTAPI,isorganized(the
basicideashavebeendiscussedinthisblog):
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 19/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
AlertModerator
42Comments
YoumustbeLoggedontocommentorreplytoapost.
CraigStasila
January24,2013at10:14pm
Suchagoodpost!IhadarequirementtoexposeaRESTAPIabout16months
ago.Thiswouldvecomeinveryhelpful.GradeAdevelopment!
RdigerPlantiko Postauthor
January25,2013at7:13am
HelloCraig,thankyouforthegoodgrade! Maybetheblog
givesyousomeideasforyournextRESTAPIproject!Cheers,
Rdiger
MUHAMMADAHMADALI
September20,2014at2:29pm
hellosir,
ihavetoconsumejsonformatwebserviceinabap.i
consumedandnowtheformatin
jsonxmlasiattachediusedSMUM_XML_PARSEbut
thecvalueandcnamebotharecommingincvalue.please
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 20/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
tellmehowtogetthedata
CesarMartin
March5,2013at12:31pm
HiRdiger,
Verynice!!Ihadntreadyourpostuntilnow,whichisanicecoincidencethatwe
havebeenworkinginverysimilardirections.Checkmyposthere:
http://scn.sap.com/community/abap/connectivity/blog/2013/03/05/jsonadapter
forabapfunctionmodules
Looksthatweallhavethesameconcernsthesedays!
Cheers,
Csar.
SreejaReddy
June2,2013at2:04pm
HiRdiger,
ThisinfohelpedmegreatlytounderstandtheconceptofRestAPI.
Theproblemisicreatedaserviceinsicfwithhandlerclasswhichimplements
IF_HTTP_EXTENSION~HANDLE_REQUEST,butwheniexecutethecorrespondinghtml
pageitisnottriggeringthehandlerclass ..
PleaseHelpme
Thanksinadvance,
Sreeja.
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 21/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
RdigerPlantiko Postauthor
June2,2013at5:51pm
HiSreeja,
PleaseHelpme
Iwouldliketo
wheniexecutethecorrespondinghtmlpageitisnottriggeringthe
handlerclass ..
AssumingyouknowthataRESTserviceisnotanHTMLpagebutonlya
remotelycallablefunctionusingHTTPasprotocolandwithdataas
response(usuallyinXMLorJSONformat),Iunderstandthatyouhavea
webapplicationwhichcallstheRESTAPIimplicitlywithJavaScript.
WhenyouanalyzethepagebehaviourwithatoollikeFirebug:
istherequestreallyissuedbyyourJavaScript?Youseethisin
yourNetworktab
istherearesponsesentfromtheSAPsystem?
IsthisresponseOK(status200),ornotOK(status40xoreven
50x)?Inthenetworktab,thelatterarewritteninredcolor.
IftheresponseisnotOK,analyzetheresponseforfindingout
whatwentwrong.
Thereisavarietyofpossiblereasonsthatarequestmayfail:
WrongURL,SICFservicenotactive,wrongormissingrequestdata
(whenrequired),anABAPshortdumpduringprocessing,
Regards,
Rdiger
JaneMascarenhas
July2,2013at4:27pm
HiRudiger,
IamconnectingtoSAPusingHTTPWebResponseandHTTPWebRequest.We
arefetchingalistofordersfromSAP.Theissueisthatforeachorderthatis
fetchedfromSAP,asessiongetscreatedanddoesnotgetclosed/end.On
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 22/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
debuggingweusedtheURLusedtofetchthedata(createdinthecode)and
pastedinthebrowserwindow.Itcreatedasession.NowweusedtheURL
(createdinthecode)fortheclosesessionandpastedinthebrowserwindow.It
loggedoffthesession.Ultimatelyfromthebrowserweareabletoopenand
closesessionbutnotfromthecode.Canyoupleasehelp?
RdigerPlantiko Postauthor
July4,2013at6:13am
HiJane,ifyouonlywantalistoforders,youdontneedastateful
service.Workingwithastatelessserviceinstead,wouldmeanthat
thesessionwillnotbepreserved.
Regards,Rdiger
YuvarajShanmugam
July9,2013at9:43am
HiRdiger,
Greatpost,IamgladthatIranintoyourblog.
IhavebeenreadingandtryingtoimplementRESTAPIinABAPand
communicatewithitfromanAndroiddevice(Outofcuriositymostly).SofarI
havesucceededdoingitbydefiningaclassimplementing
IF_HTTP_EXTENSION~HANDLE_REQUEST().
YourideaofimplementingStrategypatterntohandlePUT,GETetciscool.I
washappythatIcoulddothesameuntillIranintothishelpdocumentation
RESTInterfacesandClassesConnectivitySAPLibrary.ThenewREST
libraryalreadyhasinterfacestoimplementthePUT,GETrequestsinsteadof
doingitviaourlogicusing~requestmethodheadervalue.
ButIamnotveryclearonhowtoachievethissinceIcouldntgetmyhandson
theRESTlibraryasitsnotyetavailableinthesystemthatIamworkingon.
Itwillbeveryusefulifwegettoseesomedocumentedimplementation.
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 23/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
CesarMartin
July9,2013at11:33am
HiYuvaraj,
TheABAPRESTLibraryisquitenewanditisverylikelythatyour
systemdoesnthaveityet.Itiscominginthebasissystemwith
release7.40andyoucanonlygetitinpreviousreleasesonlywith
thelatestSAP_BASISpatches.
Itisonlydocumentedfor7.40.Youalreadyhavethecorrectlink.
Youcanalsofindthisbloguseful:
http://scn.sap.com/community/abap/connectivity/blog/2013/05/16/us
ageoftheabaprestlibrarysapbasis740
IthinkthatthisABAPLibraryistheendtoallofourseparateefforts
todoRESTlikeinterfacesforABAP.Probablythisisthewaytogo
fromnowon.
Hopethishelps,
Csar.
YuvarajShanmugam
July9,2013at4:23pm
HICaesar,
Yes,theRESTLibraryisnew.Iwasinterestedtosee
howtheclasseswillwork.Ademoapplicationwould
havegivenagoodperspective.
IwasabletotakealookattheclassesinaSample
System,SignupandgetstartedwiththeSAPGateway
DemoConsumptionSystem,whichismainly
availabletoconnectandconsumepreloaded
webservices.
Theclassesaredefinedwiththenamespace,
/IWCOR/(eg./IWCOR/CL_REST_HTTP_HANDLER).
ButeveninthatsystemIwasnotabletofindany
ServicedefinedusingtheRESTLibrary,alsothereis
nodeveloperaccesshenceitwasnotofmuchuse.But
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 24/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
itcouldbehelpfulifweneedtoknowhowSAPhas
handledRESTcommunications.
CesarMartin
July9,2013at5:55pm
HiYuvaraj,
Thesystemyoureaccessingiscurrentlya
release7.02.Assuch,theSREST
packageismissing.
Theclassesyourementioningdoindeed
belongtotheRESTLibrary,butitisthe
implementationspecifictobeusedby
Gateway.Thisimplementationisin
principlenotintendedtobeused
generically.SoImafraidyoucannotdo
muchwithit.Youneeda7.03/7.31or7.40
system.
Regards,
Csar.
RdigerPlantiko Postauthor
July9,2013at12:25pm
HiYuvaraj,
thanksforpointingmetotheSAPRESTlibrarywhichhasbeen
deliveredwithbasisrelease731andisabsolutelynewtome.
Aswitheveryframework,itmaybethatitdeliverstoomuchfora
concretepurpose.Iwillhavetoexplorethat.
Ifyouhavequestionsaboutmywayofimplementationas
exposedherethengoahead.WhatIcannotdoisanswer
questionsabouttheSAPRESTlibrary,sinceitisnewtome.(But
youdonthaveaconcretequestionaboutit,either.Onlyonthe
availability:whichseemstobeSAP_BASIS731)
Cheers,
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 25/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
Rdiger
CesarMartin
July9,2013at5:43pm
HiRdiger,
Letmeconfirmavailability:theRESTLibraryis
includedin7.40and7.31/7.03.
AspecificreleaseisalsoincludedaspartofSAP
NetWeaverGateway,butintendedtobeusedonlyfor
Gateway,notasageneralsolution.Itisusedinternally
byGateway.
TheRESTLibraryprojectstartedinternallyatSAPat
leastin2010,buthasonlybeenrecentlyreleased.Itis
fullydocumentedonlyfor7.40.
Ihaventhadthetimetoplaywithiteither,butitlooks
promising.Letskeepwatching.
Bestregards,
Csar.
RaghavendraPrabhuMithal
December9,2013at10:40am
HiRdiger,
IhaveasituationwhereIneedtoautmaticallylogintoSAPwhentheuserenteridandpwd
intoa.netapplication.IamplanningtocreatearestservicethroughSICFnodeandredirect
theusertoaSAPwebdynproapplication.
Mybiggestchallengeis
HowcanIauthenticatehim,Iamplanningtomatchtheuseridandpwdof.Netapplication
withthatofSAP,sowhenthecalltherestusingtheURLIdontwantaPopupforuseridand
passwod
IsthereawaytoavoidthepopuprequestinguseridandpasswordsinceIalreadyhavethe
useridandpasswordandcanpassasURLparam.thereisnosecurityconcernsasita
terminalserver.
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 26/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
Thanksforanysuggestionorhelp.
RaghavendraPrabhu
RdigerPlantiko Postauthor
December9,2013at9:21pm
HiRaghavendra,
unfortunately,Idontunderstandyourscenario.
Soyouhavea.Netapplicationandwanttopresenttheuseraweb
dynprofromthere.ButforwhatdoyouneedRESTthen.
IsthereawaytoavoidthepopuprequestinguseridandpasswordsinceI
alreadyhavetheuseridandpasswordandcanpassasURLparam.thereis
nosecurityconcernsasitaterminalserver.
Thisseemstobesomehowunrelatedtotheformer.Ifitbothersyouthatyour
servicerequiresuserandpassword,youcouldmaketheserviceanonymous
byprovidingcredentialsintheSICFservice.
IfyoureallywanttopassuseridandpasswordasURLparameterswhich
nobodywouldrecommendyou,eveninaseeminglyprotectedenvironment
youcanaffordthisbyusingtheappropriateURLqueryparameters:sapuser
andsappassword.
Justreadthedocu
http://help.sap.com/saphelp_470/helpdata/en/6f/04d73a90e7322be10000000a
11405a/content.htm
forfurtherinfos.
Regards,
Rdiger
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 27/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
RaghavendraPrabhuMithal
December10,2013at4:20am
HiRdiger
Reallyappreciateyourreply,wehaveascenario
whereinsinglesignonisnotapossibility.
Ihaveathirdpartyapplicationthroughwhichtheuser
enterthecredentials.BasicallyIwanttocalla
Webdynproscreenaftertheuserloginsthroughthird
party,weareplanningtosynctheuseridofthethird
partyapplicationwiththatofSAP.Afteruserlogins
throughthirdpartyapplicationIwanttocallaservice
throughSICFnodeandloginwithoutgivingtheprompt
toenteruseridandpwdagain,afterthelogininis
successfulIshallredirectfromtheservicehandlerto
thewebdynproapplication.SorryifIamconfusing
you.
IwanttoskipthatpasswordpromptwhichSAPgives
whenwecalltheSICFservicebyspecifyingtheURL.
Thanksverymuchforallyourinputs.
RaghavendraPrabhu
RdigerPlantiko Postauthor
December10,2013at6:45am
HiRhagavendra,
sothispartofmyformerreplyshouldbethe
answer:
Ifitbothersyouthatyourservice
requiresuserandpassword,youcould
maketheserviceanonymousby
providingcredentialsintheSICF
service.
Ifyoureallywanttopassuseridand
passwordasURLparameterswhich
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 28/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
nobodywouldrecommendyou,evenin
aseeminglyprotectedenvironment
youcanaffordthisbyusingthe
appropriateURLqueryparameters:
sapuserandsappassword.
Justreadthedocu
http://help.sap.com/saphelp_470/helpd
ata/en/6f/04d73a90e7322be10000000
a11405a/content.htm
forfurtherinfos.
Kindregards,
Rdiger
CarstenZiegler
June4,2014at2:23pm
Rdiger,youmademyday!
JustlookingintohttpclientandserverhandlingonABAPforthecommunication
betweenABAPandHANAXS.Thisblogpostsavesmesometime.
OnceagainIhavetothankyouforyourwork.
RdigerPlantiko Postauthor
June4,2014at3:04pm
Carsten,Ienjoyitthattheblogwasofuseforyou.Thanksforyour
feedback!Regards,Rdiger
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 29/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
RdigerPlantiko Postauthor
June4,2014at3:21pm
YoumightalsobeinterestedintheABAPRESTlibrary(whichI
didntknowwhenIhadwrittenthisblog).Someoftheabstractions
whichIdetailedinthisblogseemtobeavailablethereforreuse:
UsageoftheABAPRESTLibrary[SAP_BASIS7.40]
CarstenZiegler
June5,2014at10:43am
Thanksforthelink.Divingintothetopicatthe
moment
VedranShkupuljupi
September25,2014at9:23am
ThankyouverymuchRdiger!
Additionalquestion:howisitpossibletohandlelocks?Iwanttochangee.g.a
notificationinawebapplication,butifiwanttolockitinsap(withenqueue)the
lockwillbedeletedaftertherequestisfinished.
RegardsVedran
RdigerPlantiko Postauthor
September28,2014at7:47pm
HiVedran,
inthestatelessrequestthatIprefer,thereisnootherwaythanto
writealockentryinaspecialdatabaseentry.Intheapplicationsin
whichweneededsuchalocking,wehadcreatedaspecial
databasetableZLOCK,withaGUIDaskey,theninthedataparta
genericobjectkeyfield,anobjecttype(togetherbuildinga
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 30/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
secondaryindex),afieldforuserid,andthelockcreationtime.
RequestingalocklooksforentriesinZLOCKforthesameobject
key&type,andwithacreationdatenotolderthanasystemwide
definedtimeoutparameter,andwithadifferentuseridthanthe
ownone.Ifsuchanentryexists,thecurrentusercansethislock,
theexceptionisthrowntoinformtheservicethattheobjectin
questioncantbechanged.Ifnosuchentryexists,theusercanset
hisownentry.Ifanentryexistsbutisoutofdate,userandcreation
timecanbeupdated.
Additionaltothetimeoutmechanism,youcanprovideaspecial
logofffunctionwhichclearsallentriesforthecurrentuser.
SimilartoSM12fornormalenqueueentries,alittlereportishelpful
forsupporttoshowthecurrentlocks,andtodeletethem(inspecial
cases).
Hopethishelps
Rdiger
VedranShkupuljupi
September29,2014at6:21am
HiRdiger
Thanksforyouranswer.Ihadalsothesameidea,but
itsalottodotodevelopanextensioninoraroundthe
enqueueFMscodetohandethis.SoIchangedto
statefulrequestswiththemethodserver
>set_session_statefeful()insidethehandler.Ihope
thatnobigdisatvantageswillappear.
Greets
Vedran
RdigerPlantiko Postauthor
September29,2014at7:01am
HiVedran,
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 31/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
butitsalottodotodevelopan
extensioninoraroundtheenqueue
FMscodetohandethis.
acentralserviceclassforenqueue
requestswhichworksagainstaDBtable
couldbeworthwritingit.Forourprojects
itdefinitelywas.Bytheway,wedidnt
touchthestandardenqueueFMs.
Thebigadvantageofstateless
applicationsisthattheyscalemuch
better.
Regards,
Rdiger
VedranShkupuljupi
December5,2014at10:12am
HiRdiger,
Itsmeagain.NowIwrotea
statefulapplication(outside
sap,phponawebserver).It
worksgreatwithstandard
lockingmechanisminsap.I
canremovelockswiththe
samesessionandifIlogout,
thelocksarealsoremoved!I
canreadanmanupulate
data,Perfect!
ButIfImakeachangeat
thesourcecode(sapside),
thecurrentsessiondoesnt
recognizethechanges.This
isntabigthing,Icouldkick
theuser/sessionfromSM05.
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 32/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
Nowmyproblem:ifIchange
e.g.anequipmentinSAP,the
changesalsoarent
recognizedatthecurrent
session(ifIvealreadyopen
thisequipmentfromweb).
Doyouknowwhythisis
happening?Isthereasetting
forit?
IthoughwhynotusingSAP
standartstuffnowIregret
whyIdidntimplementyour
suggestion
Thankyou.
GreetsVedran
RdigerPlantiko Postauthor
December5,2014at1:00pm
HiVedran,
whatyoudescribeisstandard
SAPbehaviour.Theneeded
dataareloadedintothe
sessionmemoryfromdata
basewhenatransactionis
started,andlaterchangesof
thedatabasewonteffectthe
sessiondatainmemory.This
isfordataconsistencyduring
asession.
BTW,youwouldfacesimilar
problemsifyoukeptsession
dataintableSSCOOKIEfor
usageacrossdialogsteps,
whenworkingwithstateless
applications.
Inbothcases,youwould
needtohavesomekindof
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 33/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
notificationmechanismtoget
yourtransactioninformed
aboutchanges.
Forthis,youwouldneeda
centralentrypointinthecode
whichispassedwitheach
dialogstep.ForBSP
applications,thiswouldbe
somethinglikethemethod
DO_INITATTRIBUTESor
evenDO_REQUEST
(redefined).Inthis,youcould
checksomethinglikea
changestacktablefor
recentchangesandreload
themasterdataifnecessary.
Youwontgetthisforfree!
Butinspiteofthisbeing
technicallypossible,the
questionremains:
Whatiftheuserschanges
makesenseonlyforthe
versionofdataasofwhen
theuserstartedthe
transaction?Howtohandle
this?
Regards,
Rdiger
PhaniSivapuran
June17,2015at9:32pm
HiRdiger,
ThisbloggavemesomeunderstandingofconfiguringserviceinSICFand
implementingtheinterface,IF_HTTP_EXTENSION~HANDLE_REQUEST.But,I
needtoaccesstheURLusedtoaccessthisservice.Ineedtoreadoraccess
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 34/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
theparametersconcatinatedtotheURLgeneratedbySICF.Because,tothe
URLgeneratedbySAP,userswillinputandpasssomedefaultvaluestothe
selectionscreenofatransactioncode.Ineedtocapturethoseparatmetersand
performsomeoperationonthesame.Pleasehelp.
Inaddition,withtheimplementationofcustomclass,parameterspassedinGUI
configurationofSICFhavebecomeirrelevant.ThoughIampassing
singletransactionparameter,itisnotshowinganyeffectasweareusingcustom
handlerclass.Anysuggestionsonhowtogetthiswork?
Thanks,
Phani
RdigerPlantiko Postauthor
June18,2015at8:14am
HiPhani,
youwanttogetformfieldvalues(passedasqueryparametersin
theURL)?Thenuseserver>request>get_form_field()andRTFM
forfurtherquestionsonthecalldetails.
Forthis,youwouldntneedtheURL.Youcanuseserver>request
>get_form_field(),itretrievestheURLqueryparametersasparsed
fromtheURL,soyoudontneedtoparsetheURLyourself.If,for
whateverreasons,youwouldliketodothisparsingyourself,you
canusethepseudoheaderfield~query_string(thatis,youcall
server>request>get_header_field(~query_string)).SeeListof
thePseudoHeaderFieldsComponentsofSAPCommunication
TechnologySAPLibraryformoredetails.
Asforthesecondquestion:ImustadmitIdontunderstandit.
Maybesomebodyelsedoes.
Regards
Rdiger
PhaniSivapuran
June18,2015at2:32pm
HiRdiger,
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 35/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
Thanksforyourquickresponse.
Regardingthesecondquestion,wehavetheoptionto
setparametersoftheservice.Asshownbelow,Ihave
selectedtheparameter~singletransactionas1.This
willnotallowusertonavigatetoanyothertransaction
apartfromtheonelinkedwiththerespectiveURL.AsI
haveusedcustomimplementationofhandlerequest,
thisisnotworkinganymore.
ArticleEmploySAPGUIforHTMLinsteadofan
InternetserviceWikiSCNWiki
Alsooutputdisplayedistruncated.Imeanoutput
displayedisnotcomplete.ButifIjustscrolllittlebit
towardsright,thenthepageisgettingrefreshedandI
canseethecompleteoutput.
Thanks,
Phani
VASANTHAKUMARPALANISAMY
March4,2016at11:49am
HiColleagues,
IsitAsyncRequestpossiblehereinRESTAPI?
Ifyes,couldyoupleasetellmehowtoachieveit.
Thanksinadvance.
Regards
Vasanth
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 36/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
ArijitDas
May20,2016at2:31am
HiRdigerPlantiko
Atrulywonderfulblog!Itmakesforveryinterestingreading.
IhaveaquestionwouldyoubefamiliarwithhowSAPECC(oranySAP
backendsystem)cancallanapigeeendpointforasynchronousscenario?
TheintegrationpatternisECCapigeeappapigeeECC
Iunderstandthataclient_idandclient_secretarerequiredbyapigee
(POSTMANscreenshotattachedbelow).
Regards
Arijit
RdigerPlantiko Postauthor
May20,2016at7:09am
HiArijit,yourquestionisslightlyofftopic,asthisblogdescribesthe
SAPsystemintheserverrole.YouareaskingonhowtouseaSAP
systemasclienttoperformAPIcallsviatheunifiedtoolapigee.
Anywayifyouknowtheformfieldstosubmit,youcanuseclass
cl_http_clientforthis.Itisdocumented,andtherearesample
reportslikeRSHTTP01.
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 37/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
Regards,
Rdiger
ArijitDas
May21,2016at2:24am
ThankyouRdigerPlantikoforyourhelpinpointing
meintherightdirection.Ishalltrythereport
JeanFranoisParmentier
June1,2016at3:41pm
HiRdiger,
thanksalotforyourprecisedescription.
Imtryingtouseyourexampleinmysystem.Isearchedinthecodeyou
provided.
thedirectionoftranscodificationImtryingtodoisthefollowing:
internaltableinSAP>XML>REST.
mysapbasisversionis7.2.Ihaventgottherestobjectinmysystem.
Ijustappliedtheoss1648418inordertousetypejsonlikeif_sxml=>co_xt_json.
despitemyefforts,Icantmanagetousethetransormationyouusewith
ls_resultasentry:
lo_writer=cl_sxml_string_writer=>create(type=if_sxml=>co_xt_json).
CALLTRANSFORMATIONzjpar_test04
*SOURCEdata=lt_itab
SOURCEdata=ls_result
RESULTXMLlo_writer.
ev_cdata=cl_abap_codepage=>convert_from(lo_writer>get_output()).
sorryifmyquestionseemsobviousbuthowdoyouusels_resultwithyour
followingstructure:
TYPES:
BEGINOFty_result,
msgtypeTYPEsymsgty,
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 38/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
messageTYPEcLENGTH255,
jobsTYPEstring,
ENDOFty_result.
ItrywiththefollowingdatabutcantfigureouttheformatIneedtouse:
1.<?xmlversion=1.0encoding=utf8?>
2.<asx:abapxmlns:asx=http://www.sap.com/abapxmlversion=1.0>
3.<asx:values>
4.<DATA>
5.<JOBS>
6.<ZJOBS>
7.<ID>0001</ID>
8.<REPID>RSNAST00</REPID>
9.<VARID>UXPD_KUBE_KV</VARID>
10.<PRIO>2</PRIO>
11.<RESTART>X</RESTART>
12.<CONTACT>RainerZufall</CONTACT>
13.<DESCR>Outputallsalesorderconfirmations</DESCR>
14.</ZJOBS>
15.<ZJOBS>
16.<ID>0002</ID>
17.<REPID>RBDAPP01</REPID>
18.<VARID>UXPD_EDI_GUT02</VARID>
19.<PRIO>3</PRIO>
20.<RESTART>X</RESTART>
21.<CONTACT>HerbertHurtig</CONTACT>
22.<DESCR>CreditMemos</DESCR>
23.</ZJOBS>
24.</JOBS>
25.<MESSAGE>Test</MESSAGE>
26.<MSGTYPE>I</MSGTYPE>
27.</DATA>
28.</asx:values>
29.</asx:abap>
thanksforyourhelp.
regards,
JeanFranois.
RdigerPlantiko Postauthor
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 39/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
June2,2016at10:32am
HiJeanFranois,fromyourquestionitisnotclearwhichproblemyouhave.
Thepieceofcodethatyoupastedseemstoindicatethatyou
haveaselfwrittentransformationzjpar_test04(whichwedontknow),
youwanttoapplythistransformationtoastructure,notaninternaltable,
sinceyouuseavariablenamedls_result
andyouwanttoreceivetheresultintheformofJSONdata.
TheresultofthetransformationmustthereforebeavalidXML
document,conformingtotheXMLJSONsyntax.Youcancheckthis
byusingmyschematronvalidatorthatIdescribedinanotherblog.
Justwritetheresultnotintolo_writerbutintoastring(resultxml
lv_result),copytheXMLfromthedebuggeratthatpoint,and
pasteintotheJSONXMLvalidator.
Ifitisvalid,thenprettysurelo_writerwillreceivecorrectJSONin
yourcodesnippet.Ifnot,youllhavetoadaptthetransformationto
makeitwork.
Hopethishelps,
Rdiger
JeanFranoisParmentier
September19,2016at12:08pm
HiRdiger,
thanksalotforyourhelpconcerningmyissue.
IknowthatmyproblemisnotclearasImimproving
myskillsconcerningAPIswhiledevelopping.
thankstoyou,isucceededindeveloppingthe
transformationsheetandconvertingXMLtoJSON.
contrarytoyoursolution,imnotreceivingAPI.Im
tryingtosenddatatoanAPI.
Unfortunatelyimfacingtwoissues:
withmySAPversion(SAPBASIS70207),when
usingSM59theHTTPuserislimitedto32characters.
thereisanoss2020611whichseemstocorrectthis
issue.however,itisnotavailableformySAPBASIS
version.
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 40/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
whentestingSM59connexion,ialwaysreceivehttp
403withforbiddenstatus.
itseemstoberelatedtomethodofconnexion.theAPI
imusingonlyworkswithPOSTmethodandSM59only
workswithGETmethod.
itseemsthatwithABAPdeveloppementitispossibleto
usePOSTversion(examplecodeinfollowingphoto):
however.Imalwaysreceiving
http_communication_failureerrorwithmessage
ICM_HTTP_INTERNAL_ERRORwhentestinganAPI.
Doyouthinkthereisasolutiontomyproblems?
Doyouthinkweneedtoapplyasupportpackageto
createthissolution?
Regards,
JeanFranois.
SahilShah
September19,2016at1:20pm
IfthewebserviceisRestFulandexposed
tointernet,whydoyouneedanentryin
SM59?
JeanFranoisParmentier
September19,2016at3:19pm
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 41/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
HiSahil,
thatsagoodquestion.
withapi,itseemsthatthe
versionmayevolveinthe
future.hencetheurlmay
changeaswell.itseems
easiertochangeSM59
directlyinproductionsystem
thanchangetheABAPcode
andtransportTOs.
SahilShah
September19,2016at3:57pm
TheideaofaRestfulWeb
Serviceisitshouldbe
StatelessandLoosely
coupledandthatswhyiuse
itdirectly.
Iwillsuggesttotestyourapi
andtherequestparameters
directlyfromsomeother
application(likeJavascript
etc)orusingOnlineHTTP
Requestsites(likeRequest
Maker,Hurl.itetc)andseeif
youcanconnectit.Ifyouare
successful,thenyoushould
besuccessfulwithinSAP
also.
Thanks
Sahil
AjithJ
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 42/43
2/8/2017 DevelopingaRESTAPIinABAP|SAPBlogs
October17,2016at12:15pm
Hi,
IneedtoconsumeawebservicewhichisRESTandXMLformat.
IamawarethatSAPhasprovidedstandardclassesif_rest_clientand
if_rest_entityinBASIS731butoursystemversionisBASIS702.
Isthereanywaywecanstillconsumesuchwebservicein702versioninABAP?
SampleinputisbelowandthemethodisPOST
<?xmlversion=1.0encoding=UTF8?>
<XML_Request>
<MAT>TEST1</MAT>
<OUTPUT_TYPE>3</OUTPUT_TYPE>
</XML_Request>
@sourav.das3
@rdiger.plantiko2
Ajith.
https://blogs.sap.com/2013/01/24/developingarestapiinabap/ 43/43
In ABAP, JSON data can be transformed into an XML representation using the CALL TRANSFORMATION statement. The JSON string is parsed into a JSON-XML format, which is then processed by an XSLT transformation to convert it into asXML format representing ABAP data structures. For example, a JSON string with job attributes is transformed into an XML format that aligns with ABAP's data structure, allowing easy import into an ABAP program's data structures. This method offers advantages in terms of flexibility, allowing developers to handle non-canonical JSON formats optimized for web client readability or third-party integration. It also simplifies data handling by converting JSON to structured ABAP data without custom XSLT when using canonical forms .