ReSTFulWebServicesByRaghuSir PDF
ReSTFulWebServicesByRaghuSir PDF
ReSTFulWebServicesByRaghuSir PDF
Rest Webservice
By : Raghu
1
RaghuSir Sathya Technologies
RestFul Webservices
Integration:
Two or more applications will be connected together to provide service to end
User.
Example:PayTM - Ola PayTM -Swiggy
BookMyShow -netBanking / CC / DC
Connect one application with another is called as Integration.
Based on languages used to develop the application, Integration concept is
divided into two types.
1. Homogeneous Integration:
If two applications are developed using same language and integrated together is
known as Homogeneous Integration.
Example:
ii.Heterogeneous Integration
If two applications are developed in different languages and integrated together
is known as Heterogeneous Integration.
3
RaghuSir Sathya Technologies
WEBSERVICE
“To connect/Integrate two or more Applications”, with each other and exchange
data using request and response, that provides service to end User is known as
Webservice.
Webservice supports Homogeneous and Heterogeneous Integrations.
Webservices are tow two types {Old and New} they are …
5
RaghuSir Sathya Technologies
*Calculation:
6
RaghuSir Sathya Technologies
Design of FrontController:
Server-1 Server-2
Client Server with Front Controller Design:
This design is used to connect two different application which are running
in two different server.
One behaves as Provider Application that must container Provider Logic
under Integration Layer which is implemented using FrontController
Design Pattern.
8
RaghuSir Sathya Technologies
Another application connects with this using it’s IL that must have Client
Programming.
These IL’s connects to their respected SL’s. This design is used by
ReSTWebservices.
ReST Webservices:
ReST/ReSTFul stands for Representation State (Data format) Transfer.
It means transfer data in same format between two applications
(It should be represented in same type)
ReST can be Integrated with any Java API like Servlets , JDBC, JSP, Hibernate
, Spring … etc
It supports even special concept {and API} like CODEC (Coding and
DECoding) Mail Service(Java Mail) … etc.
ReST Architecture supports Easy Modifications in Project like Adding /
removing will not affect other code.
Where in SOAP, any modification we must re-publish, re-generate stubs, re-
write bind.
ReST uses Document concept to provide all resource details of Service
Provider to Service Consumer.
This Document can be in any format example: Text , Image , … etc
Standard Document format is WADL (Web Application Description
Language).
It contains details of Provider Code like URLs, inputs/output to Service and
MediaType (XML / JSON).
This Document will not be used in Programming to generate any classes (or
code). This is only to understand what is available in Provider.
This is even optional Document in ReSTFulWebservice implementation.
To write ReST Programming (Provider and Consumer) we must use one
vendor implementation. Basic API (abstract design) is given by SUN (which
is called as JAX-RS API).
JAX-RS = Java API for XML-ReSTFul Services.
Example vendors for JAX-RS is Jersey, RestEasy, Apache CXF, GlashFish
Basic-RS etc…
Using any API for implementation of ReST differs at only FrontController
not on Service Provider Class coding.
10
RaghuSir Sathya Technologies
11
RaghuSir Sathya Technologies
1. web.xml
2. Define one Service Provider class with ReST Annotations under src
folder.
Eg: src -new - class example: com.app class Name: Message finish.
Ctrl + shift + O to get imports
Above annotations are from “javax.ws.rs” package.
12
RaghuSir Sathya Technologies
Note:
1. URL is case sensitive, if request URL not match with provider code ie code /
spelling is wrong then server return HTTP status 404 not found. Eg:
/Abc and /ABC are different
Eg: @Path(“/ab”), @Path(“/AB”), @Path(“/aB”) are different.
2. If URL matched and HTTP method type (Eg: GET/POST) is not matched, then
server returns 405 method not allowed.
Example request made with GET type but provider is POST then 405.
3. If server raised any exception then HTTP Status is 500 – Internal Server
Error.
4. If request processed successfully then HTTP Status is 200 – OK.
5. Request can be made three ways using Web Browser.
i. Enter URL in Address Bar (GET)
ii. Submit HTML form (GET / POST)
iii. Hyper Links (<a> tags) (GET)
On making request, server provides response with HTTP Status (int)
indicates status of request process.
13
RaghuSir Sathya Technologies
14
RaghuSir Sathya Technologies
Create one Java Project (Standalone).
Add Jar’s to Build Path. (From Jersey lib folder).
CODING:
We must define one ClientTest class, which is used to make a request.
Example: src - class -com.app : package - class : ClientTest
Program:
15
RaghuSir Sathya Technologies
@Path Usages:
@Path is optional at method level, if Provider class contains at max 2
methods. One should be GET type another should be POST type.
3rd method onwards @Path is required. Same path can be used at max for 2
methods but one should be GET another is POST.
If two methods with same URL has same method (name) type like {GET and
GET or POST and POST} no CTE. But on making server returns 500 – Internal
Server Error.
Class level @Path can also be used at method level @Path.
Parameters in ReST Programming:
Parameters are used to send data from Client to Server Application. { or
Consumer to Provider} along with request(URL).
It supports only sending primitive Data like int, double, String, … etc.
It will not support sending data from Sever to Client. Only one Direction.
1. Query Parameters:
This concept is from Servlets, here we can send the data in “key = value”
pair format. Both are type String by default. We can even convert to
another type.
16
RaghuSir Sathya Technologies
To read data at Provider write as below.{inside the method parameter}
@QueryParam(“key”) DT locVar
here DT :DataType, locVar: localVariable.
Example: @QueryParam(“sid”) String id , this line equal meaning is
String pid = request.getParameter(“sid”);
It supports also Type Conversion. (Example : String --int)
@QueryParam(“sid”) int id , equal meaning is
String sid = request.getParameter(“sid”);
int id = Integer.parseInt(sid);
If any Type Conversion problem occurred then Server throws HTTP status –
404.
Example request URL is:
http://localhost:2019/ProjName/FCURL/ClassURL/methodURL?sid=AB
Provider Code is : @QueryParam(“sid”) int id
sid value “AB” can not be stored in id , ERROR -404.
If key is not present in URL then FC provides default values to
parameters.int =0, double =0.0 , String = null. …etc.
In case of multiple parameters order is not required to follow to send data
in request URL for keys. Because binding can be done based on Key, but not
on Order.
Example: url?sid=9&sname=Hareesh&sfee=9.9
url?sname=Hareesh&sfee=9.9&sid=9
url?sid=9&sfee=9.9&sname=Hareesh
All are same (order not required)
If any extra key = value pair is sent in request, that will be ignored by FC, no
error here.
Example for QueryParam:
i. Provider Code
ii. Web.xml {Configure FC ServletContainer}
iii. Service Provider Class.
17
RaghuSir Sathya Technologies
18
RaghuSir Sathya Technologies
19
RaghuSir Sathya Technologies
CaptchWebservice Example:
20
RaghuSir Sathya Technologies
To read data at Provider Syntax is : @MatrixParam(“key”)DT locVar here
DT: dataTypelocVar: localVariable.
Example: @MatrixParam(“sname”) String sn
Both key = value are Type String only. But it also supports type Conversion.
22
RaghuSir Sathya Technologies
Example: Provider Application:
Consumer Application:
I. Logical Form Concept
Use From class object, add data to it in key=value, this object must be
send using POST() call as 2ndparam.
Logical Form is not supported by GET.
23
RaghuSir Sathya Technologies
24
RaghuSir Sathya Technologies
Header Parameters:
These parameters are used in ReST to send data using HTTPRequest, in
key=value format.
This concept is used for Client Identity Process at Provider Application. It is
like username and password, accTocken, CVV, … etc.
In development Header Params concept is used along with CODEC
{Encoding and Decoding} concept.
Header Params follows key=value format, both are type String.
Example: Provider Application:
i. Web.xml configure FC {ServletContainer}
ii. Service Provider Class
25
RaghuSir Sathya Technologies
Consumer Application:
On WebResource object, use method header which contains (key,value)
before making method call.
Example:
26
RaghuSir Sathya Technologies
HTTPRequest Format for Header key=value:
27
RaghuSir Sathya Technologies
Header params concept is used for Client Authorization at Provider
Application.
One example algorithm is “Basic Authentication”.
S#1> Username and password Strings are concatenated using delimiter : (colon)
S#2> Concatenated String is encoded {un-readable String}.
S#3> A prefix “Basic “ is added to above String.
S#4> Converted as a Header Param and updated to HTTPRequest.
28
RaghuSir Sathya Technologies
CODEC:{Encoding and Decoding}
Encoding:
It is a process of converting readable content to unreadable content.
Example: sathya -- @T$&%Q
Decoding:
It is a process of converting unreadable content to readable format back.
Example: @T$&%Q -sathya.
CODEC Design:
29
RaghuSir Sathya Technologies
Converting String to byte[]:
Use method “getBytes()” in String API. It returns String in byte[] format.
Example: String s1 = “Hello”;
byte[] arr = s1.getBytes();
Converting byte[] to String:
By using parameterized constructor of String. We can convert byte[] to
String.
Here parameter is byte[].
Example: byte[] b = …
String s2 = new String(b);
Download Apache commons codec jar to perform CODEC operation.
https://commons.apache.org/proper/commons-
codec/download_codec.cgi
Goto Binaries -- choose “Zip”
Extract Zip to see Jar File.
Class: Base64
Method: (static)
encodeBase64(byte[] nrml) : byte[] encoded
Decodebase64(byte[] encoded) : byte[] nrml
Example:
30
RaghuSir Sathya Technologies
Provider Code:
31
RaghuSir Sathya Technologies
32
RaghuSir Sathya Technologies
33
RaghuSir Sathya Technologies
MediaType in Webservices:
Every request and response contains one header key (Pre-defined header)
“Content-Type”.
Here Content means data. It means providing dataType or details of data, in
request to Service Provider or providing dataType or details in response to
Service Consumer.
Design:
For basic operation HTTP uses default “Content-Type” value as “text/plain”.
Some other example Content-Type values
image/jpg,image/png,application/xml,application/json,application/winwor
d. Etc.
34
RaghuSir Sathya Technologies
It stores data in key = value format key must be quoted, value will be
quoted if type String only.
One {} (pair of braces) indicates one object.
Key = value are comma separated.
JSON object is String type in languages.
JSON can converted to any high level language.
Comparing to xml, JSON is light weight and faster in conversion.
JSON can be converted to Java Object format (one Object/Collection …)
using JACKSON conversion API. Which is built-in with Jersey (or any ReST
API).
JSON Example compared with Java Object:
35
RaghuSir Sathya Technologies
Example:
36
RaghuSir Sathya Technologies
37
RaghuSir Sathya Technologies
38
RaghuSir Sathya Technologies
Consumer Example:
39
RaghuSir Sathya Technologies
Output:
Consumer Example:
40
RaghuSir Sathya Technologies
Output:
MediaTypes:
In Webservices two applications (Consumer and Provider) will exchange
data in global format.
Example JSON or XML are global formats.
ReSTWebservices has given two annotations to automate data conversion
and exchange between Provider and Consumer.
Those are @Consumes and @Produces from javax.ws.rs package.
@Consumes:
This annotation is used to convert Request data (Global Format) to Object
in Provider.
@Produces:
This annotation is used to convert Object in Provider to Response data
(Global Format).
41
RaghuSir Sathya Technologies
Design #1 :
Design #2 :
Design #3 :
42
RaghuSir Sathya Technologies
Data (Global Format) XML or JSON will be carried using Http ( Request /
Response) Body.
In Http header “Content-Type” provides details about data available in
Bodys.
Example:
43
RaghuSir Sathya Technologies
@Produces Example:
This annotation will convert Provider method returnType to Global format
and places under HttpResponse Body.
It also add Http Header key “Content-Type:------” in HttpResponse Head
area, to specify Body contains what format.
Example Provider Class:
44
RaghuSir Sathya Technologies
45
RaghuSir Sathya Technologies
46
RaghuSir Sathya Technologies
47
RaghuSir Sathya Technologies
49
RaghuSir Sathya Technologies
50
RaghuSir Sathya Technologies
Design: #1
Make a request from valid client which has valid “Authorization” and
“Content-Type”.
In HttpRequest Body send JSON of Employee, this must be converted to
object format and store in DB as a Row.
In case of invalid request, return with error message
i. 401 – UnAuthorization
ii. 404 – Not Found
iii. 405 – Method not Support
iv. 415 – Unsupported MediaType
If successfully executed or id already exist returns message with 200- OK
51
RaghuSir Sathya Technologies
Design: #2
To implement Provider Application we are using 3 Layers.
1. Integration Layer
2. Service Layer
3. DataAccess Layer
If request is made by Client Application, it will be submitted to
FrontController.
FC identify the Provider Class based on Path and HttpRequest is given to it.
HttpRequest contains two header params, One is Authorization, 2nd is
Content-Type.
If Content-Type not matched with Provider (JSON) it returns 415.
Authorization valus is sent to ClientAuth Class for validate Client.
It returns Boolean, ie true – valid Client, false – invalid Client return with
401.
In case of valid Client(true), continue to Service Layer Class. Here JSON -
Object verify object id already exist in DB or not? Using DAL with select
Query ….
Select …. --true – exist , false -- not exist.
If true don’t save return with error message else save into DB as row (
insert … into …). Return final response object back to Client Application.
Here also define one ConnectionUtil to get one Connection Object
(Singleton Design).
52
RaghuSir Sathya Technologies
53