You are on page 1of 27

24/03/2017 RESTfulWebServicesQuickGuide

RESTfulWebServicesQuickGuide
https://www.tutorialspoint.com/restful/restful_quick_guide.htm
Copyrighttutorialspoint.com

RESTfulWebServicesIntroduction
WhatisREST?
RESTstandsforREpresentationalStateTransfer.RESTisawebstandardsbasedarchitectureanduses
HTTPProtocolfordatacommunication.Itrevolvesaroundresourceswhereeverycomponentisaresource
andaresourceisaccessedbyacommoninterfaceusingHTTPstandardmethods.RESTwasfirstintroduced
byRoyFieldinginyear2000.

InRESTarchitecture,aRESTServersimplyprovidesaccesstoresourcesandtheRESTclientaccessesand
presentstheresources.HereeachresourceisidentifiedbyURIs/GlobalIDs.RESTusesvarious
representationstorepresentaresourcelikeText,JSONandXML.JSONisnowthemostpopularformat
beingusedinWebServices.

HTTPMethods

ThefollowingHTTPmethodsaremostcommonlyusedinaRESTbasedarchitecture.

GETProvidesareadonlyaccesstoaresource.

PUTUsedtocreateanewresource.

DELETEUsedtoremovearesource.

POSTUsedtoupdateanexistingresourceorcreateanewresource.

OPTIONSUsedtogetthesupportedoperationsonaresource.

RESTFulWebServices
Awebserviceisacollectionofopenprotocolsandstandardsusedforexchangingdatabetweenapplications
orsystems.Softwareapplicationswritteninvariousprogramminglanguagesandrunningonvarious
platformscanusewebservicestoexchangedataovercomputernetworksliketheInternetinamanner
similartointerprocesscommunicationonasinglecomputer.Thisinteroperability
e. g. , betweenJ avaandP ython, orW indowsandLinuxapplicationsisduetotheuseofopenstandards.

WebservicesbasedonRESTArchitectureareknownasRESTfulWebServices.Thesewebservicesuse
HTTPmethodstoimplementtheconceptofRESTarchitecture.ARESTfulwebserviceusuallydefinesa
URIU nif ormResourceI dentif ier,whichisaservicethatprovidesresourcerepresentationsuchasJSON
andasetofHTTPMethods.

CreatingRESTFulWebService
Inthistutorial,wewillcreateawebservicecalledUserManagementwiththefollowingfunctionalities

Sr.No. HTTPMethod URI Operation OperationType


https://www.tutorialspoint.com/cgibin/printpage.cgi 1/27
24/03/2017 RESTfulWebServicesQuickGuide

1 GET /UserService/users Getlistofusers ReadOnly


2 GET /UserService/users/1 GetUserwithId1 ReadOnly
3 PUT /UserService/users/2 InsertUserwithId2 Idempotent
4 POST /UserService/users/2 UpdateUserwithId2 N/A
5 DELETE /UserService/users/1 DeleteUserwithId1 Idempotent
6 OPTIONS /UserService/users Listthesupportedoperationsinwebservice ReadOnly

RESTfulWebServicesEnvironmentSetup
ThistutorialwillguideyouonhowtoprepareadevelopmentenvironmenttostartyourworkwithJersey
FrameworktocreateRESTfulWebServices.JerseyframeworkimplementsJAXRS2.0API,whichisa
standardspecificationtocreateRESTfulWebServices.ThistutorialwillalsoteachyouhowtosetupJDK,
TomcatandEclipseonyourmachinebeforeyoutheJerseyFrameworkissetup.

SetupJavaDevelopmentKitJ DK
YoucandownloadthelatestversionofSDKfromOracle'sJavasiteJavaSEDownloads.Youwillfindthe
instructionsforinstallingJDKinthedownloadedfiles.Followthegiveninstructionstoinstallandconfigure
thesetup.FinallysetthePATHandJAVA_HOMEenvironmentvariablestorefertothedirectorythat
containsJavaandJavac,typicallyjava_install_dir/binandjava_install_dirrespectively.

IfyouarerunningWindowsandinstalledtheJDKinC:\jdk1.7.0_75,youwouldhavetoputthefollowing
lineinyourC:\autoexec.batfile.
setPATH=C:\jdk1.7.0_75\bin;%PATH%
setJAVA_HOME=C:\jdk1.7.0_75

Alternatively,onWindowsNT/2000/XP,youcouldalsorightclickonMyComputerselectProperties
thenAdvancedthenEnvironmentVariables.Then,youwouldupdatethePATHvalueandpresstheOK
button.

OnUnixS olaris, Linux, etc.,iftheSDKisinstalledin/usr/local/jdk1.7.0_75andyouusetheCShell,you


wouldputthefollowingintoyour.cshrcfile.

setenvPATH/usr/local/jdk1.7.0_75/bin:$PATH
setenvJAVA_HOME/usr/local/jdk1.7.0_75

Alternatively,ifyouuseanIntegratedDevelopmentEnvironmentI DElikeBorlandJBuilder,Eclipse,
IntelliJIDEA,orSunONEStudio,compileandrunasimpleprogramtoconfirmthattheIDEknowswhere
youinstalledJava,otherwisedopropersetupasgivendocumentoftheIDE.

SetupEclipseIDE
AlltheexamplesinthistutorialhavebeenwrittenusingtheEclipseIDE.So,Iwouldsuggestyoushould
havethelatestversionofEclipseinstalledonyourmachine.

ToinstallEclipseIDE,downloadthelatestEclipsebinariesfromhttps://www.eclipse.org/downloads/.Once
youdownloadedtheinstallation,unpackthebinarydistributiontoaconvenientlocation.Forexample,in
C:\eclipseonwindows,or/usr/local/eclipseonLinux/UnixandfinallysetthePATHvariableappropriately.

Eclipsecanbestartedbyexecutingthefollowingcommandsonawindowsmachine,oryoucansimply
doubleclickoneclipse.exe.

%C:\eclipse\eclipse.exe

https://www.tutorialspoint.com/cgibin/printpage.cgi , , . 2/27
24/03/2017 RESTfulWebServicesQuickGuide

EclipsecanbestartedbyexecutingthefollowingcommandsonUnixS olaris, Linux, etc.machine


$/usr/local/eclipse/eclipse

Afterasuccessfulstartup,ifeverythingisfine,thenyourscreenshoulddisplaythefollowingresult

SetupJerseyFrameworkLibraries
Now,ifeverythingisfine,thenyoucanproceedtosetuptheJerseyframework.Followingareafewsimple
stepstodownloadandinstalltheframeworkonyourmachine.

MakeachoicewhetheryouwanttoinstallJerseyonWindows,orUnixandthenproceedtothenext
steptodownloadthe.zipfileforwindowsandthenthe.tzfileforUnix.

DownloadthelatestversionofJerseyframeworkbinariesfromthefollowinglink
https://jersey.java.net/download.html.

Atthetimeofwritingthistutorial,Idownloadedjaxrsri2.17.ziponmyWindowsmachineandwhen
youunzipthedownloadedfileitwillgiveyouthedirectorystructureinsideE:\jaxrsri2.17\jaxrsrias
showninthefollowingscreenshot.

YouwillfindalltheJerseylibrariesinthedirectoriesC:\jaxrsri2.17\jaxrsri\libanddependenciesin
C:\jaxrsri2.17\jaxrsri\ext.MakesureyousetyourCLASSPATHvariableonthisdirectoryproperly

https://www.tutorialspoint.com/cgibin/printpage.cgi 3/27
24/03/2017 RESTfulWebServicesQuickGuide

otherwiseyouwillfaceproblemwhilerunningyourapplication.IfyouareusingEclipse,thenitisnot
requiredtosettheCLASSPATHbecauseallthesettingswillbedonethroughEclipse.

SetupApacheTomcat
YoucandownloadthelatestversionofTomcatfromhttps://tomcat.apache.org/.Onceyoudownloadedthe
installation,unpackthebinarydistributionintoaconvenientlocation.ForexampleinC:\apachetomcat
7.0.59onwindows,or/usr/local/apachetomcat7.0.59onLinux/UnixandsetCATALINA_HOME
environmentvariablepointingtotheinstallationlocations.

Tomcatcanbestartedbyexecutingthefollowingcommandsonawindowsmachine,oryoucansimply
doubleclickonstartup.bat.
%CATALINA_HOME%\bin\startup.bat

or

C:\apachetomcat7.0.59\bin\startup.bat

TomcatcanbestartedbyexecutingthefollowingcommandsonaUnixS olaris, Linux, etc.machine


$CATALINA_HOME/bin/startup.sh

or

/usr/local/apachetomcat7.0.59/bin/startup.sh

Afterasuccessfulstartup,thedefaultwebapplicationsincludedwithTomcatwillbeavailablebyvisiting
http://localhost:8080/.Ifeverythingisfinethenitshoulddisplaythefollowingresult

FurtherinformationaboutconfiguringandrunningTomcatcanbefoundinthedocumentationincludedon
thispage.ThisinformationcanalsobefoundontheTomcatwebsitehttps://tomcat.apache.org.

Tomcatcanbestoppedbyexecutingthefollowingcommandsonawindowsmachine
%CATALINA_HOME%\bin\shutdown

or
C:\apachetomcat7.0.59\bin\shutdown

TomcatcanbestoppedbyexecutingthefollowingcommandsonUnixS olaris, Linux, etc.machine

https://www.tutorialspoint.com/cgibin/printpage.cgi 4/27
24/03/2017 RESTfulWebServicesQuickGuide

$CATALINA_HOME/bin/shutdown.sh

or
/usr/local/apachetomcat7.0.59/bin/shutdown.sh

Onceyouaredonewiththislaststep,youarereadytoproceedforyourfirstJerseyexamplewhichyouwill
seeinthenextchapter.

RESTfulWebServicesFirstApplication
LetusstartwritingtheactualRESTfulwebserviceswithJerseyFramework.Beforeyoustartwritingyour
firstexampleusingtheJerseyFramework,youhavetomakesurethatyouhavesetupyourJersey
environmentproperlyasexplainedintheRESTfulWebServicesEnvironmentSetupchapter.Here,Iam
alsoassumingthatyouhavealittleworkingknowledgeofEclipseIDE.

So,letusproceedtowriteasimpleJerseyApplicationwhichwillexposeawebservicemethodtodisplay
thelistofusers.

CreatingaJavaProject
ThefirststepistocreateaDynamicWebProjectusingEclipseIDE.FollowtheoptionFileNew
ProjectandfinallyselecttheDynamicWebProjectwizardfromthewizardlist.Nownameyourprojectas
UserManagementusingthewizardwindowasshowninthefollowingscreenshot

https://www.tutorialspoint.com/cgibin/printpage.cgi 5/27
24/03/2017 RESTfulWebServicesQuickGuide

Onceyourprojectiscreatedsuccessfully,youwillhavethefollowingcontentinyourProjectExplorer

https://www.tutorialspoint.com/cgibin/printpage.cgi 6/27
24/03/2017 RESTfulWebServicesQuickGuide

AddingtheRequiredLibraries
AsasecondstepletusaddJerseyFrameworkanditsdependencieslibraries inourproject.Copyalljars
fromfollowingdirectoriesofdownloadjerseyzipfolderinWEBINF/libdirectoryoftheproject.

\jaxrsri2.17\jaxrsri\api
\jaxrsri2.17\jaxrsri\ext
\jaxrsri2.17\jaxrsri\lib

Now,rightclickonyourprojectnameUserManagementandthenfollowtheoptionavailableincontext
menuBuildPathConfigureBuildPathtodisplaytheJavaBuildPathwindow.

NowuseAddJARsbuttonavailableunderLibrariestabtoaddtheJARspresentinWEBINF/libdirectory.

CreatingtheSourceFiles
NowletuscreatetheactualsourcefilesundertheUserManagementproject.Firstweneedtocreatea
packagecalledcom.tutorialspoint.Todothis,rightclickonsrcinpackageexplorersectionandfollowthe
optionNewPackage.

NextwewillcreateUserService.java,User.java,UserDao.javafilesunderthecom.tutorialspointpackage.

User.java

packagecom.tutorialspoint;

importjava.io.Serializable;
importjavax.xml.bind.annotation.XmlElement;
importjavax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="user")

publicclassUserimplementsSerializable{
privatestaticfinallongserialVersionUID=1L;
privateintid;
privateStringname;
privateStringprofession;
https://www.tutorialspoint.com/cgibin/printpage.cgi 7/27
24/03/2017 RESTfulWebServicesQuickGuide
publicUser(){}

publicUser(intid,Stringname,Stringprofession){
this.id=id;
this.name=name;
this.profession=profession;
}
publicintgetId(){
returnid;
}
@XmlElement
publicvoidsetId(intid){
this.id=id;
}
publicStringgetName(){
returnname;
}
@XmlElement
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetProfession(){
returnprofession;
}
@XmlElement
publicvoidsetProfession(Stringprofession){
this.profession=profession;
}
}

UserDao.java
packagecom.tutorialspoint;

importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
importjava.util.ArrayList;
importjava.util.List;

publicclassUserDao{
publicList<User>getAllUsers(){

List<User>userList=null;
try{
Filefile=newFile("Users.dat");
if(!file.exists()){
Useruser=newUser(1,"Mahesh","Teacher");
userList=newArrayList<User>();
userList.add(user);
saveUserList(userList);
}
else{
FileInputStreamfis=newFileInputStream(file);
ObjectInputStreamois=newObjectInputStream(fis);
userList=(List<User>)ois.readObject();
ois.close();
}
}catch(IOExceptione){
e.printStackTrace();
}catch(ClassNotFoundExceptione){
e.printStackTrace();
}
returnuserList;
}
https://www.tutorialspoint.com/cgibin/printpage.cgi 8/27
24/03/2017 RESTfulWebServicesQuickGuide

privatevoidsaveUserList(List<User>userList){
try{
Filefile=newFile("Users.dat");
FileOutputStreamfos;
fos=newFileOutputStream(file);
ObjectOutputStreamoos=newObjectOutputStream(fos);
oos.writeObject(userList);
oos.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
}

UserService.java

packagecom.tutorialspoint;

importjava.util.List;
importjavax.ws.rs.GET;
importjavax.ws.rs.Path;
importjavax.ws.rs.Produces;
importjavax.ws.rs.core.MediaType;
@Path("/UserService")

publicclassUserService{
UserDaouserDao=newUserDao();
@GET
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
publicList<User>getUsers(){
returnuserDao.getAllUsers();
}
}

Therearetwoimportantpointstobenotedaboutthemainprogram,

UserService.java
Thefirststepistospecifyapathforthewebserviceusing@PathannotationtotheUserService.

Thesecondstepistospecifyapathfortheparticularwebservicemethodusing@Pathannotationto
methodofUserService.

CreatingtheWeb.xmlconfigurationFile
YouneedtocreateaWebxmlConfigurationfilewhichisanXMLfileandisusedtospecifyJersey
frameworkservletforourapplication.

web.xml
<?xmlversion="1.0"encoding="UTF8"?>
<webappxmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/webapp_3_0.xsd"
id="WebApp_ID"version="3.0">
<displayname>UserManagement</displayname>
<servlet>
<servletname>JerseyRESTfulApplication</servletname>
<servletclass>org.glassfish.jersey.servlet.ServletContainer</servletclass>
<initparam>
<paramname>jersey.config.server.provider.packages</paramname>
https://www.tutorialspoint.com/cgibin/printpage.cgi 9/27
24/03/2017 RESTfulWebServicesQuickGuide
<paramvalue>com.tutorialspoint</paramvalue>
</initparam>
</servlet>
<servletmapping>
<servletname>JerseyRESTfulApplication</servletname>
<urlpattern>/rest/*</urlpattern>
</servletmapping>
</webapp>

DeployingtheProgram
Onceyouaredonewithcreatingsourceandwebconfigurationfiles,youarereadyforthisstepwhichis
compilingandrunningyourprogram.Todothis,usingEclipse,exportyourapplicationasawarfileand
deploythesameintomcat.

TocreateaWARfileusingeclipse,followtheoptionFileexportWebWarFileandfinallyselect
projectUserManagementanddestinationfolder.TodeployawarfileinTomcat,placethe
UserManagement.warintheTomcatInstallationDirectorywebappsdirectoryandstarttheTomcat.

RunningtheProgram

WeareusingPostman,aChromeextension,totestourwebservices.

MakearequesttoUserManagementtogetlistofalltheusers.Put
http://localhost:8080/UserManagement/rest/UserService/usersinPOSTMANwithGETrequestandseethe
followingresult.

Congratulations,youhavecreatedyourfirstRESTfulApplicationsuccessfully.

RESTfulWebServicesResources
WhatisaResource?
RESTarchitecturetreatseverycontentasaresource.TheseresourcescanbeTextFiles,HtmlPages,Images,
VideosorDynamicBusinessData.RESTServersimplyprovidesaccesstoresourcesandRESTclient
accessesandmodifiestheresources.HereeachresourceisidentifiedbyURIs/GlobalIDs.RESTuses
variousrepresentationstorepresentaresourcewhereText,JSON,XML.Themostpopularrepresentationsof
resourcesareXMLandJSON.

RepresentationofResources
https://www.tutorialspoint.com/cgibin/printpage.cgi 10/27
24/03/2017 RESTfulWebServicesQuickGuide

AresourceinRESTisasimilarObjectinObjectOrientedProgrammingorislikeanEntityinaDatabase.
Oncearesourceisidentifiedthenitsrepresentationistobedecidedusingastandardformatsothattheserver
cansendtheresourceintheabovesaidformatandclientcanunderstandthesameformat.

Forexample,inRESTfulWebServicesFirstApplicationchapter,auserisaresourcewhichisrepresented
usingthefollowingXMLformat
<user>
<id>1</id>
<name>Mahesh</name>
<profession>Teacher</profession>
</user>

ThesameresourcecanberepresentedinJSONformatasfollows

{
"id":1,
"name":"Mahesh",
"profession":"Teacher"
}

GoodResourcesRepresentation
RESTdoesnotimposeanyrestrictionontheformatofaresourcerepresentation.AclientcanaskforJSON
representationwhereasanotherclientmayaskforXMLrepresentationofthesameresourcetotheserverand
soon.ItistheresponsibilityoftheRESTservertopasstheclienttheresourceintheformatthattheclient
understands.

Followingaresomeimportantpointstobeconsideredwhiledesigningarepresentationformatofaresource
inRESTfulWebServices.

UnderstandabilityBoththeServerandtheClientshouldbeabletounderstandandutilizethe
representationformatoftheresource.

CompletenessFormatshouldbeabletorepresentaresourcecompletely.Forexample,aresource
cancontainanotherresource.Formatshouldbeabletorepresentsimpleaswellascomplexstructures
ofresources.

LinkablityAresourcecanhavealinkagetoanotherresource,aformatshouldbeabletohandle
suchsituations.

However,atpresentmostofthewebservicesarerepresentingresourcesusingeitherXMLorJSONformat.
Thereareplentyoflibrariesandtoolsavailabletounderstand,parse,andmodifyXMLandJSONdata.

RESTfulWebServicesMessages
RESTfulWebServicesmakeuseofHTTPprotocolsasamediumofcommunicationbetweenclientand
server.AclientsendsamessageinformofaHTTPRequestandtheserverrespondsintheformofanHTTP
Response.ThistechniqueistermedasMessaging.Thesemessagescontainmessagedataandmetadatai.e.
informationaboutmessageitself.LetushavealookontheHTTPRequestandHTTPResponsemessages
forHTTP1.1.

HTTPRequest

https://www.tutorialspoint.com/cgibin/printpage.cgi 11/27
24/03/2017 RESTfulWebServicesQuickGuide

AnHTTPRequesthasfivemajorparts

VerbIndicatestheHTTPmethodssuchasGET,POST,DELETE,PUT,etc.

URIUniformResourceIdentifierU RI toidentifytheresourceontheserver.

HTTPVersionIndicatestheHTTPversion.Forexample,HTTPv1.1.

RequestHeaderContainsmetadatafortheHTTPRequestmessageaskeyvaluepairs.For
example,clientorbrowser type,formatsupportedbytheclient,formatofthemessagebody,cache
settings,etc.

RequestBodyMessagecontentorResourcerepresentation.

HTTPResponse

AnHTTPResponsehasfourmajorparts

Status/ResponseCodeIndicatestheServerstatusfortherequestedresource.Forexample,404
meansresourcenotfoundand200meansresponseisok.

HTTPVersionIndicatestheHTTPversion.ForexampleHTTPv1.1.

ResponseHeaderContainsmetadatafortheHTTPResponsemessageaskeyvaluepairs.For
example,contentlength,contenttype,responsedate,servertype,etc.

ResponseBodyResponsemessagecontentorResourcerepresentation.

Example

https://www.tutorialspoint.com/cgibin/printpage.cgi 12/27
24/03/2017 RESTfulWebServicesQuickGuide

AswehaveexplainedintheRESTfulWebServicesFirstApplicationchapter,letusput
http://localhost:8080/UserManagement/rest/UserService/usersinthePOSTMANwithaGETrequest.Ifyou
clickonthePreviewbuttonwhichisnearthesendbuttonofPostmanandthenclickontheSendbutton,you
mayseethefollowingoutput.

Hereyoucansee,thebrowsersentaGETrequestandreceivedaresponsebodyasXML.

RESTfulWebServicesAddressing
Addressingreferstolocatingaresourceormultipleresourceslyingontheserver.Itisanalogoustolocatea
postaladdressofaperson.

EachresourceinRESTarchitectureisidentifiedbyitsURIU nif ormResourceI dentif ier.AURIisof


thefollowingformat
<protocol>://<servicename>/<ResourceType>/<ResourceID>

PurposeofanURIistolocatearesources ontheserverhostingthewebservice.Anotherimportantattribute
ofarequestisVERBwhichidentifiestheoperationtobeperformedontheresource.Forexample,in
RESTfulWebServicesFirstApplicationchapter,theURIis
http://localhost:8080/UserManagement/rest/UserService/usersandtheVERBisGET.

ConstructingaStandardURI
ThefollowingareimportantpointstobeconsideredwhiledesigningaURI

UsePluralNounUsepluralnountodefineresources.Forexample,we'veuseduserstoidentify
usersasaresource.

AvoidusingspacesUseunderscore _ orhyphen whenusingalongresourcename.Forexample,


useauthorized_usersinsteadofauthorized%20users.
https://www.tutorialspoint.com/cgibin/printpage.cgi 13/27
24/03/2017 RESTfulWebServicesQuickGuide

UselowercaselettersAlthoughURIiscaseinsensitive,itisagoodpracticetokeeptheurlinlower
caselettersonly.

MaintainBackwardCompatibilityAsWebServiceisapublicservice,aURIoncemadepublic
shouldalwaysbeavailable.Incase,URIgetsupdated,redirecttheolderURItoanewURIusingthe
HTTPStatuscode,300.

UseHTTPVerbAlwaysuseHTTPVerblikeGET,PUTandDELETEtodotheoperationsonthe
resource.ItisnotgoodtouseoperationsnameintheURI.

Example
FollowingisanexampleofapoorURItofetchauser.

http://localhost:8080/UserManagement/rest/UserService/getUser/1

FollowingisanexampleofagoodURItofetchauser.

http://localhost:8080/UserManagement/rest/UserService/users/1

RESTfulWebServicesMethods
AswehavediscussedintheearlierchaptersthatRESTfulWebServiceusesalotofHTTPverbsto
determinetheoperationtobecarriedoutonthespecifiedresources .Thefollowingtablestatestheexamples
ofthemostcommonlyusedHTTPVerbs.

Sr.No. HTTPMethod,URIandOperation

GET

http://localhost:8080/UserManagement/rest/UserService/users
1
Getsthelistofusers.

ReadOnly

GET

http://localhost:8080/UserManagement/rest/UserService/users/1
2
GetstheUserofId1

ReadOnly

PUT

http://localhost:8080/UserManagement/rest/UserService/users/2
3
InsertsUserwithId2

I dempotent

4 POST

http://localhost:8080/UserManagement/rest/UserService/users/2
https://www.tutorialspoint.com/cgibin/printpage.cgi 14/27
24/03/2017 RESTfulWebServicesQuickGuide

UpdatestheUserwithId2

N /A

DELETE

http://localhost:8080/UserManagement/rest/UserService/users/1
5
DeletestheUserwithId1

I dempotent

OPTIONS

http://localhost:8080/UserManagement/rest/UserService/users
6
Listsoutthesupportedoperationsinawebservice.

ReadOnly

HEAD

http://localhost:8080/UserManagement/rest/UserService/users
7
ReturnstheHTTPHeaderonly,noBody.

ReadOnly

Thefollowingpointsaretobeconsidered.

GEToperationsarereadonlyandaresafe.

PUTandDELETEoperationsareidempotent,whichmeanstheirresultwillalwaysbethesame,no
matterhowmanytimestheseoperationsareinvoked.

PUTandPOSToperationarenearlythesamewiththedifferencelyingonlyintheresultwherethe
PUToperationisidempotentandPOSToperationcancauseadifferentresult.

Example

LetusupdateanExamplecreatedintheRESTfulWebServicesFirstApplicationchaptertocreateaWeb
servicewhichcanperformCRUDC reate, Read, U pdate, Deleteoperations.Forsimplicity,wehaveused
afileI/OtoreplaceDatabaseoperations.

LetusupdatetheUser.java,UserDao.javaandUserService.javafilesunderthecom.tutorialspoint
package.

User.java
packagecom.tutorialspoint;

importjava.io.Serializable;
importjavax.xml.bind.annotation.XmlElement;
importjavax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="user")

https://www.tutorialspoint.com/cgibin/printpage.cgi 15/27
24/03/2017 RESTfulWebServicesQuickGuide
publicclassUserimplementsSerializable{
privatestaticfinallongserialVersionUID=1L;
privateintid;
privateStringname;
privateStringprofession;
publicUser(){}

publicUser(intid,Stringname,Stringprofession){
this.id=id;
this.name=name;
this.profession=profession;
}

publicintgetId(){
returnid;
}
@XmlElement
publicvoidsetId(intid){
this.id=id;
}
publicStringgetName(){
returnname;
}
@XmlElement
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetProfession(){
returnprofession;
}
@XmlElement
publicvoidsetProfession(Stringprofession){
this.profession=profession;
}
@Override
publicbooleanequals(Objectobject){
if(object==null){
returnfalse;
}elseif(!(objectinstanceofUser)){
returnfalse;
}else{
Useruser=(User)object;
if(id==user.getId()
&&name.equals(user.getName())
&&profession.equals(user.getProfession())){
returntrue;
}
}
returnfalse;
}
}

UserDao.java
packagecom.tutorialspoint;

importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
importjava.util.ArrayList;
importjava.util.List;

publicclassUserDao{
publicList<User>getAllUsers(){

https://www.tutorialspoint.com/cgibin/printpage.cgi 16/27
24/03/2017 RESTfulWebServicesQuickGuide
List<User>userList=null;
try{
Filefile=newFile("Users.dat");
if(!file.exists()){
Useruser=newUser(1,"Mahesh","Teacher");
userList=newArrayList<User>();
userList.add(user);
saveUserList(userList);
}
else{
FileInputStreamfis=newFileInputStream(file);
ObjectInputStreamois=newObjectInputStream(fis);
userList=(List<User>)ois.readObject();
ois.close();
}
}catch(IOExceptione){
e.printStackTrace();
}catch(ClassNotFoundExceptione){
e.printStackTrace();
}
returnuserList;
}
publicUsergetUser(intid){
List<User>users=getAllUsers();
for(Useruser:users){
if(user.getId()==id){
returnuser;
}
}
returnnull;
}
publicintaddUser(UserpUser){
List<User>userList=getAllUsers();
booleanuserExists=false;
for(Useruser:userList){
if(user.getId()==pUser.getId()){
userExists=true;
break;
}
}
if(!userExists){
userList.add(pUser);
saveUserList(userList);
return1;
}
return0;
}
publicintupdateUser(UserpUser){
List<User>userList=getAllUsers();
for(Useruser:userList){
if(user.getId()==pUser.getId()){
intindex=userList.indexOf(user);
userList.set(index,pUser);
saveUserList(userList);
return1;
}
}
return0;
}
publicintdeleteUser(intid){
List<User>userList=getAllUsers();
for(Useruser:userList){
if(user.getId()==id){
intindex=userList.indexOf(user);
userList.remove(index);
saveUserList(userList);
return1;
}
}

https://www.tutorialspoint.com/cgibin/printpage.cgi 17/27
24/03/2017 RESTfulWebServicesQuickGuide

return0;
}
privatevoidsaveUserList(List<User>userList){
try{
Filefile=newFile("Users.dat");
FileOutputStreamfos;
fos=newFileOutputStream(file);
ObjectOutputStreamoos=newObjectOutputStream(fos);
oos.writeObject(userList);
oos.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
}

UserService.java
packagecom.tutorialspoint;

importjava.io.IOException;
importjava.util.List;
importjavax.servlet.http.HttpServletResponse;
importjavax.ws.rs.Consumes;
importjavax.ws.rs.DELETE;
importjavax.ws.rs.FormParam;
importjavax.ws.rs.GET;
importjavax.ws.rs.OPTIONS;
importjavax.ws.rs.POST;
importjavax.ws.rs.PUT;
importjavax.ws.rs.Path;
importjavax.ws.rs.PathParam;
importjavax.ws.rs.Produces;
importjavax.ws.rs.core.Context;
importjavax.ws.rs.core.MediaType;
@Path("/UserService")

publicclassUserService{

UserDaouserDao=newUserDao();
privatestaticfinalStringSUCCESS_RESULT="<result>success</result>";
privatestaticfinalStringFAILURE_RESULT="<result>failure</result>";
@GET
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
publicList<User>getUsers(){
returnuserDao.getAllUsers();
}
@GET
@Path("/users/{userid}")
@Produces(MediaType.APPLICATION_XML)
publicUsergetUser(@PathParam("userid")intuserid){
returnuserDao.getUser(userid);
}
@PUT
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
publicStringcreateUser(@FormParam("id")intid,
@FormParam("name")Stringname,
@FormParam("profession")Stringprofession,
@ContextHttpServletResponseservletResponse)throwsIOException{
Useruser=newUser(id,name,profession);
intresult=userDao.addUser(user);
if(result==1){
returnSUCCESS_RESULT;

https://www.tutorialspoint.com/cgibin/printpage.cgi 18/27
24/03/2017 RESTfulWebServicesQuickGuide
}
returnFAILURE_RESULT;
}
@POST
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
publicStringupdateUser(@FormParam("id")intid,
@FormParam("name")Stringname,
@FormParam("profession")Stringprofession,
@ContextHttpServletResponseservletResponse)throwsIOException{
Useruser=newUser(id,name,profession);
intresult=userDao.updateUser(user);
if(result==1){
returnSUCCESS_RESULT;
}
returnFAILURE_RESULT;
}
@DELETE
@Path("/users/{userid}")
@Produces(MediaType.APPLICATION_XML)
publicStringdeleteUser(@PathParam("userid")intuserid){
intresult=userDao.deleteUser(userid);
if(result==1){
returnSUCCESS_RESULT;
}
returnFAILURE_RESULT;
}
@OPTIONS
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
publicStringgetSupportedOperations(){
return"<operations>GET,PUT,POST,DELETE</operations>";
}
}

NowusingEclipse,exportyourapplicationasaWARFileanddeploythesameinTomcat.TocreateaWAR
fileusingeclipse,followthispathFileexportWebWarFileandfinallyselectproject
UserManagementandthedestinationfolder.TodeployaWARfileinTomcat,placethe
UserManagement.warintheTomcatInstallationDirectorywebappsdirectoryandthestartTomcat.

TestingtheWebService
JerseyprovidesAPIstocreateaWebServiceClienttotestwebservices.Wehavecreatedasampletestclass
WebServiceTester.javaunderthecom.tutorialspointpackageinthesameproject.

WebServiceTester.java
packagecom.tutorialspoint;

importjava.util.List;
importjavax.ws.rs.client.Client;
importjavax.ws.rs.client.ClientBuilder;
importjavax.ws.rs.client.Entity;
importjavax.ws.rs.core.Form;
importjavax.ws.rs.core.GenericType;
importjavax.ws.rs.core.MediaType;

publicclassWebServiceTester{
privateClientclient;
privateStringREST_SERVICE_URL="
http://localhost:8080/UserManagement/rest/UserService/users";
privatestaticfinalStringSUCCESS_RESULT="<result>success</result>";
privatestaticfinalStringPASS="pass";
privatestaticfinalStringFAIL="fail";
privatevoidinit(){
https://www.tutorialspoint.com/cgibin/printpage.cgi 19/27
24/03/2017 RESTfulWebServicesQuickGuide
this.client=ClientBuilder.newClient();
}
publicstaticvoidmain(String[]args){
WebServiceTestertester=newWebServiceTester();
//initializethetester
tester.init();
//testgetallusersWebServiceMethod
tester.testGetAllUsers();
//testgetuserWebServiceMethod
tester.testGetUser();
//testupdateuserWebServiceMethod
tester.testUpdateUser();
//testadduserWebServiceMethod
tester.testAddUser();
//testdeleteuserWebServiceMethod
tester.testDeleteUser();
}
//Test:Getlistofallusers
//Test:Checkiflistisnotempty
privatevoidtestGetAllUsers(){
GenericType<List<User>>list=newGenericType<List<User>>(){};
List<User>users=client
.target(REST_SERVICE_URL)
.request(MediaType.APPLICATION_XML)
.get(list);
Stringresult=PASS;
if(users.isEmpty()){
result=FAIL;
}
System.out.println("Testcasename:testGetAllUsers,Result:"+result);
}
//Test:GetUserofid1
//Test:Checkifuserissameassampleuser
privatevoidtestGetUser(){
UsersampleUser=newUser();
sampleUser.setId(1);
Useruser=client
.target(REST_SERVICE_URL)
.path("/{userid}")
.resolveTemplate("userid",1)
.request(MediaType.APPLICATION_XML)
.get(User.class);
Stringresult=FAIL;
if(sampleUser!=null&&sampleUser.getId()==user.getId()){
result=PASS;
}
System.out.println("Testcasename:testGetUser,Result:"+result);
}
//Test:UpdateUserofid1
//Test:CheckifresultissuccessXML.
privatevoidtestUpdateUser(){
Formform=newForm();
form.param("id","1");
form.param("name","suresh");
form.param("profession","clerk");
StringcallResult=client
.target(REST_SERVICE_URL)
.request(MediaType.APPLICATION_XML)
.post(Entity.entity(form,
MediaType.APPLICATION_FORM_URLENCODED_TYPE),
String.class);
Stringresult=PASS;
if(!SUCCESS_RESULT.equals(callResult)){
result=FAIL;
}
System.out.println("Testcasename:testUpdateUser,Result:"+result);
}
//Test:AddUserofid2
//Test:CheckifresultissuccessXML.

https://www.tutorialspoint.com/cgibin/printpage.cgi 20/27
24/03/2017 RESTfulWebServicesQuickGuide

privatevoidtestAddUser(){
Formform=newForm();
form.param("id","2");
form.param("name","naresh");
form.param("profession","clerk");
StringcallResult=client
.target(REST_SERVICE_URL)
.request(MediaType.APPLICATION_XML)
.put(Entity.entity(form,
MediaType.APPLICATION_FORM_URLENCODED_TYPE),
String.class);

Stringresult=PASS;
if(!SUCCESS_RESULT.equals(callResult)){
result=FAIL;
}
System.out.println("Testcasename:testAddUser,Result:"+result);
}
//Test:DeleteUserofid2
//Test:CheckifresultissuccessXML.
privatevoidtestDeleteUser(){
StringcallResult=client
.target(REST_SERVICE_URL)
.path("/{userid}")
.resolveTemplate("userid",2)
.request(MediaType.APPLICATION_XML)
.delete(String.class);
Stringresult=PASS;
if(!SUCCESS_RESULT.equals(callResult)){
result=FAIL;
}
System.out.println("Testcasename:testDeleteUser,Result:"+result);
}
}

NowrunthetesterusingEclipse.RightclickonthefileandfollowtheoptionRunasJavaApplication.
YouwillseethefollowingresultintheEclipseconsole

Testcasename:testGetAllUsers,Result:pass
Testcasename:testGetUser,Result:pass
Testcasename:testUpdateUser,Result:pass
Testcasename:testAddUser,Result:pass
Testcasename:testDeleteUser,Result:pass

RESTfulWebServicesStatelessness
AspertheRESTarchitecture,aRESTfulWebServiceshouldnotkeepaclientstateontheserver.This
restrictioniscalledStatelessness.Itistheresponsibilityoftheclienttopassitscontexttotheserverandthen
theservercanstorethiscontexttoprocesstheclient'sfurtherrequest.Forexample,sessionmaintainedby
serverisidentifiedbysessionidentifierpassedbytheclient.

RESTfulWebServicesshouldadheretothisrestriction.WehaveseenthisintheRESTfulWebServices
Methodschapter,thatthewebservicemethodsarenotstoringanyinformationfromtheclienttheyare
invokedfrom.

ConsiderthefollowingURL

https://localhost:8080/UserManagement/rest/UserService/users/1

IfyouhittheaboveurlusingyourbrowserorusingajavabasedclientorusingPostman,resultwillalways
betheUserXMLwhoseIdis1becausetheserverdoesnotstoreanyinformationabouttheclient.

<user>
<id>1</id>
https://www.tutorialspoint.com/cgibin/printpage.cgi 21/27
24/03/2017 RESTfulWebServicesQuickGuide

<name>mahesh</name>
<profession>1</profession>
</user>

AdvantagesofStatelessness
FollowingarethebenefitsofstatelessnessinRESTfulWebServices

Webservicescantreateachmethodrequestindependently.

Webservicesneednotmaintaintheclient'spreviousinteractions.Itsimplifiestheapplicationdesign.

AsHTTPisitselfastatelessnessprotocol,RESTfulWebServicesworkseamlesslywiththeHTTP
protocols.

DisadvantagesofStatelessness
FollowingarethedisadvantagesofstatelessnessinRESTfulWebServices

Webservicesneedtogetextrainformationineachrequestandtheninterprettogettheclient'sstatein
casetheclientinteractionsaretobetakencareof.

RESTfulWebServicesCaching
Cachingreferstostoringtheserverresponseintheclientitself,sothataclientneednotmakeaserver
requestforthesameresourceagainandagain.Aserverresponseshouldhaveinformationabouthowcaching
istobedone,sothataclientcachestheresponseforatimeperiodornevercachestheserverresponse.

Followingaretheheaderswhichaserverresponsecanhaveinordertoconfigureaclient'scaching

Sr.No. Header&Description

Date
1
DateandTimeoftheresourcewhenitwascreated.

LastModified
2
DateandTimeoftheresourcewhenitwaslastmodified.

CacheControl
3
Primaryheadertocontrolcaching.

Expires
4
Expirationdateandtimeofcaching.

Age
5
Durationinsecondsfromwhenresourcewasfetchedfromtheserver.

https://www.tutorialspoint.com/cgibin/printpage.cgi 22/27
24/03/2017 RESTfulWebServicesQuickGuide

CacheControlHeader
FollowingarethedetailsofaCacheControlheader

Sr.No. Directive&Description

Public
1
Indicatesthatresourceiscacheablebyanycomponent.

Private
2
Indicatesthatresourceiscacheableonlybytheclientandtheserver,nointermediarycancachethe
resource.

nocache/nostore
3
Indicatesthataresourceisnotcacheable.

maxage
4
Indicatesthecachingisvaliduptomaxageinseconds.Afterthis,clienthastomakeanother
request.

mustrevalidate
5
Indicationtoservertorevalidateresourceifmaxagehaspassed.

BestPractices
Alwayskeepstaticcontentslikeimages,CSS,JavaScriptcacheable,withexpirationdateof2to3
days.

Neverkeepexpirydatetoohigh.

Dynamiccontentshouldbecachedforafewhoursonly.

https://www.tutorialspoint.com/cgibin/printpage.cgi 23/27
24/03/2017 RESTfulWebServicesQuickGuide

RESTfulWebServicesSecurity
AsRESTfulWebServicesworkwithHTTPURLPaths,itisveryimportanttosafeguardaRESTfulWeb
Serviceinthesamemannerasawebsiteissecured.

FollowingarethebestpracticestobeadheredtowhiledesigningaRESTfulWebService

ValidationValidateallinputsontheserver.ProtectyourserveragainstSQLorNoSQLinjection
attacks.

SessionBasedAuthenticationUsesessionbasedauthenticationtoauthenticateauserwhenevera
requestismadetoaWebServicemethod.

NoSensitiveDataintheURLNeveruseusername,passwordorsessiontokeninaURL,these
valuesshouldbepassedtoWebServiceviathePOSTmethod.

RestrictiononMethodExecutionAllowrestricteduseofmethodslikeGET,POSTandDELETE
methods.TheGETmethodshouldnotbeabletodeletedata.

ValidateMalformedXML/JSONCheckforwellformedinputpassedtoawebservicemethod.

ThrowgenericErrorMessagesAwebservicemethodshoulduseHTTPerrormessageslike403to
showaccessforbidden,etc.

HTTPCode
Sr.No. HTTPCode&Description

200
1
OKshowssuccess.

https://www.tutorialspoint.com/cgibin/printpage.cgi 24/27
24/03/2017 RESTfulWebServicesQuickGuide

2 201

CREATEDwhenaresourceissuccessfullycreatedusingPOSTorPUTrequest.Returnslinkto
thenewlycreatedresourceusingthelocationheader.

204
3
NOCONTENTwhenresponsebodyisempty.Forexample,aDELETErequest.

304
4
NOTMODIFIEDusedtoreducenetworkbandwidthusageincaseofconditionalGETrequests.
Responsebodyshouldbeempty.Headersshouldhavedate,location,etc.

400
5
BADREQUESTstatesthataninvalidinputisprovided.Forexample,validationerror,missing
data.

401
6
UNAUTHORIZEDstatesthatuserisusinginvalidorwrongauthenticationtoken.

403
7
FORBIDDENstatesthattheuserisnothavingaccesstothemethodbeingused.Forexample,
Deleteaccesswithoutadminrights.

404
8
NOTFOUNDstatesthatthemethodisnotavailable.

409
9
CONFLICTstatesconflictsituationwhileexecutingthemethod.Forexample,addingduplicate
entry.

500
10
INTERNALSERVERERRORstatesthattheserverhasthrownsomeexceptionwhileexecuting
themethod.

RESTfulWebServicesJavaJ AX RS
JAXRSstandsforJAVAAPIforRESTfulWebServices.JAXRSisaJAVAbasedprogramminglanguage
APIandspecificationtoprovidesupportforcreatedRESTfulWebServices.Its2.0versionwasreleasedon
the24thMay2013.JAXRSusesannotationsavailablefromJavaSE5tosimplifythedevelopmentofJAVA

https://www.tutorialspoint.com/cgibin/printpage.cgi 25/27
24/03/2017 RESTfulWebServicesQuickGuide

basedwebservicescreationanddeployment.ItalsoprovidessupportsforcreatingclientsforRESTfulWeb
Services.

Specifications
Followingarethemostcommonlyusedannotationstomaparesourceasawebserviceresource.

Sr.No. Annotation&Description

@Path
1
Relativepathoftheresourceclass/method.

@GET
2
HTTPGetrequest,usedtofetchresource.

@PUT
3
HTTPPUTrequest,usedtocreateresource.

@POST
4
HTTPPOSTrequest,usedtocreate/updateresource.

@DELETE
5
HTTPDELETErequest,usedtodeleteresource.

@HEAD
6
HTTPHEADrequest,usedtogetstatusofmethodavailability.

@Produces
7
StatestheHTTPResponsegeneratedbywebservice.Forexample,APPLICATION/XML,
TEXT/HTML,APPLICATION/JSONetc.

@Consumes
8
StatestheHTTPRequesttype.Forexample,application/xwwwformurlencodedtoacceptformdata
inHTTPbodyduringPOSTrequest.

@PathParam
9
Bindstheparameterpassedtothemethodtoavalueinpath.

10 @QueryParam

https://www.tutorialspoint.com/cgibin/printpage.cgi 26/27
24/03/2017 RESTfulWebServicesQuickGuide

Bindstheparameterpassedtomethodtoaqueryparameterinthepath.

@MatrixParam
11
BindstheparameterpassedtothemethodtoaHTTPmatrixparameterinpath.

@HeaderParam
12
BindstheparameterpassedtothemethodtoaHTTPheader.

@CookieParam
13
BindstheparameterpassedtothemethodtoaCookie.

@FormParam
14
Bindstheparameterpassedtothemethodtoaformvalue.

@DefaultValue
15
Assignsadefaultvaluetoaparameterpassedtothemethod.

@Context
16
Contextoftheresource.Forexample,HTTPRequestasacontext.

NoteWehaveusedJersey,areferenceimplementationofJAXRS2.0byOracle,intheRESTfulWeb
ServicesFirstApplicationandRESTfulWebServicesMethodschapters.

https://www.tutorialspoint.com/cgibin/printpage.cgi 27/27

You might also like