0% found this document useful (0 votes)
81 views31 pages

Restful Webservies

REST or Representational State Transfer is a architectural style for providing standards between computer systems on the web. It uses HTTP requests to POST, GET, PUT, and DELETE data in a stateless manner. Resources are uniquely identified through URIs and manipulated through HTTP requests and standard response codes. RESTful systems aim to have clear guidelines and specifications for how data is accessed and transferred between clients and servers through simple and uniform interfaces.

Uploaded by

Lathasri Koyya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views31 pages

Restful Webservies

REST or Representational State Transfer is a architectural style for providing standards between computer systems on the web. It uses HTTP requests to POST, GET, PUT, and DELETE data in a stateless manner. Resources are uniquely identified through URIs and manipulated through HTTP requests and standard response codes. RESTful systems aim to have clear guidelines and specifications for how data is accessed and transferred between clients and servers through simple and uniform interfaces.

Uploaded by

Lathasri Koyya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

REST[Representational State transfer]

 REST[Representational State transfer]- specification is JAX-RS - sending or transferring the


representational response to client
 introduced by Roy Fielding in 2000
 brief overview of restful web services: https://www.journaldev.com/9170/restful-
web-services-tutorial-java
 detailed info of restful web services: tutorials point and jav4s
(https://www.java4s.com/web-services/)

characteristics:
HTTP exchange : the exchange of data through HTTP(request send through HTTP and get response through
HTTP)
Protocol: rest client can send request in any format : XML, JSON, Text... there is no protocol to send request
like SOAP protocol in SOAP web services.
HTTP method: messages can be exchanges in any methods depending on choosing of operations.
service definition: when we are coding in java, if we need to call a specific class, then we need to know little
bit about AP ,jars libraries ,parameters... of that class. similarly we should know something about the
webservice when we are calling a service like we do in soap services, we should know about the soap protocol
specifications. but there are no such service specifications in rest when we are using web services.
To sum up, restful webservices have no certain rules/specifications such as protocol, service and so on ..like
we have in SOAP services.

Restful Architecture
An application or architecture considered RESTful or REST-style has the following characteristics

1. State and functionality are divided into distributed resources – This means that every resource should be
accessible via the normal HTTP commands of GET, POST, PUT, or DELETE. So if someone wanted to get a file from
a server, they should be able to issue the GET request and get the file. If they want to put a file on the server,
they should be able to either issue the POST or PUT request. And finally, if they wanted to delete a file from the
server, they an issue the DELETE request.
2. The architecture is client/server, stateless, layered, and supports caching –
3. Client-server is the typical architecture where the server can be the web server hosting the application, and the
client can be as simple as the web browser.
4. Stateless means that the state of the application is not maintained in REST.
a. For example, if you delete a resource from a server using the DELETE command, you cannot expect that
delete information to be passed to the next request.
b. In order to ensure that the resource is deleted, you would need to issue the GET request. The GET
request would be used to first get all the resources on the server. After which one would need to see if
the resource was actually deleted.

To work with REST, there is a need to learn about following.


HTTP(Hyper Text Transfer Protocol):
it is a way to transform the communication between 2 applications.
the information will be in hyper text format. it is a structured format which contains links to other texts. and
the links are hyper links.
the language on HTTP will be the HTLM(Hyper Text Mark up Language)

Resource based URI'S:(links)


this is used to locate the resource of client request based on link .
before resource based URI that are easy which is like /messages/10, we used action based URI that are web
application URI's which is like
/getmessages.do?id-=10

designing links as follows will be good practice:


 the links we provide must be unique and meaningful to user the naming doesn't matters
 URI's contain nouns and plurals.
 every messages will have message ID's to make messages to be unique
 for example messages and comments are related in messenger , in this case the URI designed as
messages/comments/{MESSAGE_ID}. the relation between resources should be well established.
There are 2 types of URI's:
1. instance resource URI's - identify instance of specific resource eg: /mess
2. collection resource URI's- which represent collections of URI's
syntax of URI:
instance resource URI/collection resource URI/unique identifier
/message - returns only one message , /messages - returns all messages which is called collection
URI's
standard practice is pagination using parameter query to filter the results. example if user want all
messages , results will be 1-10 in on page and 2-20 be in 2nd page
/messages ? offset=20 limit=10 (give 10 -20 records )
custom filters : messages ?/year 2004 offset=20 limit=10 (give 10 -20 records )[ filtered by user with
year]

Example for resource based URI's:


action based URI:
/get messages.do?id-=10
/delete messages.do?id-=10
resource base URI:
/messages/10 - same URI for all actions(use get request of HTTP method to get messages , use delete request
to delete the resources , use put request to replace a content)
Ex of URI - to create message :
we use post method for creating new messages when client request for new message , that request contains
message body
post request : /messages /ID [id will ake care by application]
message ID for creating new resources will be managed by application basically finds the existing ID's and
assign new ID's because we don't know about the ID that are in application.

HTTP methods:
the most common used methods are
 get - read only method- because it is only to fetch messages. when we use this request no changes in
server because fetching the information
 post- write method
 put-write method- to update the details
 delete-write method- to delete the details
post, put, delete are write methods because when we use to write data with this methods , the
server changes will be take place when we write to server. but make safer not to be duplicate data.
if we accidently make requests repeatedly , no issues because once it deleted when we make another
request , there will be no data to delete when we use put request to replace data noting will be
effected.
but when we use post request multiple times, changes will be affected by creating new resources.
so get , put, delete are safely repeatable(idempotent) but post cannot be safely repeated called as
non idempotent

difference between put and post is :


put is idempotent (safely repeatable )and post (non idempotent).
when we use refresh button in browser , it will submit the latest get request successfully , but if we
submit post request with refresh button it will give a pop up are you surely want this submission to
confirm because it will create duplicate resources in application.
Meta Data: when client send request , the Http response will contain message headers that contains
content type ,metadata .
in action based URI's we go for different links to get delete the data, but in resource based URI we only one
URI for all and it is possible by HTTP methods.

HTTP status codes:


To provide readability to user. there are 100 - 599 codes
the digits starting with 1 are acknowledged codes
the status code starting with 2 are successful responses
the status code starting with 3 are redirection code used by server to ask client for further action to complete
request
the status code starting with 4 are client error codes
the status code starting with 5 are server error
200-success
201- resource created successfully
204- no content
307 - temporary redirect
304- not modified(when client asks to get a resource already given by server)
40 - bad request
401 -unauthorized
403 - forbidden
404 - not found
415 - unsupported media type
500- Internal server error
404-not found(when page not found)
Request Headers – These are additional instructions sent with the request. These might define
the type of response required or the authorization details.

Request Body - Data is sent with the request. Data is normally sent in the request when a POST
request is made to the REST web service. In a POST call, the client actually tells the web service
that it wants to add a resource to the server. Hence, the request body would have the details of
the resource which is required to be added to the server.

Response Body – This is the main body of the response.

REST RESPONSE:

no need of styling like other web applications but only required data that to be sent through
request in restful services. It is possible by using JSON formats. a client is a piece of code running in
a background to send request ad get response through JSON.
we can also use XML format not only JSON depends of client requirement.
client should be aware of the response format that is available at server before requesting . user can
be known by using HTTP request .
if user wants XML format ,if it should be available in XML then client gets the xml response, if not
available and there is only JSON available , even though he requested for xml format , he receives
JSON format which is available. so not possible to create both formats and give the response on
client requirement w ca crate either one and client has to request for that then only he get that
available format even though if he asks for unavailable format , client gets response in available
format. .in this case if user aware of that available format to request, it will possible by HTTP
request headers. header contains the information of available format (either JSON or XML)
every HTTP request and response has message body and header.
header contains the meta data of length, date, content.
content will explain the data in available format whether JSON or XML.
message will be like :
JSON response:

XML response:

header contains the respone

Links:
The resource URI is the property in a message
<a href=""></a> - it is used to provide the link property(links) -it is anchor tag
<rel> - it is also used for links. this is used when to specify the relation between the current page
and the other linked page(linked page is the page that will be redirected when we click on that link)
the rel attribute is to write as

so we can add extra information in this REL attribute


if we use links as properties instead of directly providing links. so the use can just remind the
property names instead of all the links . please find the below screenshot for reference. we can
structure links in different ways depending on our requirement and ease of usage.
the below screenshot represents the links as property names:
RESTFul Principles and Constraints

The REST architecture is based on a few characteristics which are elaborated below. Any RESTful web service has to comply
with the below characteristics in order for it to be called RESTful. These characteristics are also known as design principles
which need to be followed when working with RESTful based services.

1. RESTFul Client-Server

This is the most fundamental requirement of a REST based architecture. It means that the server will have a
RESTful web service which would provide the required functionality to the client. The client send's a request to
the web service on the server. The server would either reject the request or comply and provide an adequate
response to the client.

2. Stateless

The concept of stateless means that it's up to the client to ensure that all the required information is provided to the
server. This is required so that server can process the response appropriately. The server should not maintain any sort of
information between requests from the client. It's a very simple independent question-answer sequence. The client asks a
question, the server answers it appropriately. The client will ask another question. The server will not remember the
previous question-answer scenario and will need to answer the new question independently.

3. Cache

The Cache concept is to help with the problem of stateless which was described in the last point. Since each server client
request is independent in nature, sometimes the client might ask the server for the same request again. This is even
though it had already asked for it in the past. This request will go to the server, and the server will give a response. This
increases the traffic across the network. The cache is a concept implemented on the client to store requests which have
already been sent to the server. So if the same request is given by the client, instead of going to the server, it would go to
the cache and get the required information. This saves the amount of to and fro network traffic from the client to the
server.

4. Layered System

The concept of a layered system is that any additional layer such as a middleware layer can be inserted between the client
and the actual server hosting the RESTFul web service (The middleware layer is where all the business logic is created. This
can be an extra service created with which the client could interact with before it makes a call to the web service.). But the
introduction of this layer needs to be transparent so that it does not disturb the interaction between the client and the
server.

5. Interface/Uniform Contract

This is the underlying technique of how RESTful web services should work. RESTful basically works on the HTTP web layer
and uses the below key verbs to work with resources on the server

 POST - To create a resource on the server


 GET - To retrieve a resource from the server
 PUT - To change the state of a resource or to update it
 DELETE - To remove or delete a resource from the server
SOAP vs. REST

Let' have a quick overview of SOAP and REST before we do a deep dive into the key differences between them.

SOAP – SOAP is a protocol which was designed before REST and came into the picture. The main idea behind designing
SOAP was to ensure that programs built on different platforms and programming languages could exchange data in an easy
manner.

REST – This was designed specifically for working with components such as media components, files, or even objects on a
particular hardware device. Any web service that is defined on the principles of REST can be called a RestFul web service. A
Restful service would use the normal HTTP verbs of GET, POST, PUT and DELETE for working with the required components.

differences b/wn SOAP and REST :

https://www.guru99.com/comparison-between-web-services.html

https://www.javatpoint.com/soap-vs-rest-web-services

When to use REST and when to use SOAP

One of the most highly debatable topics is when REST should be used or when to use SOAP while designing web services.

Below are some of the key factors that determine when each technology should be used for web services REST services
should be used in the following instances

 Limited resources and bandwidth – Since SOAP messages are heavier in content and consume a far greater
bandwidth, REST should be used in instances where network bandwidth is a constraint.

 Statelessness – If there is no need to maintain a state of information from one request to another then REST
should be used. If you need a proper information flow wherein some information from one request needs to flow
into another then SOAP is more suited for that purpose. We can take the example of any online purchasing site.
These sites normally need the user first to add items which need to be purchased to a cart. All of the cart items
are then transferred to the payment page in order to complete the purchase. This is an example of an application
which needs the state feature. The state of the cart items needs to be transferred to the payment page for
further processing.

https://www.tutorialspoint.com/restful/restful_statelessness.htm

 Caching – If there is a need to cache a lot of requests then REST is the perfect solution. At times, clients could
request for the same resource multiple times. This can increase the number of requests which are sent to the
server. By implementing a cache, the most frequent queries results can be stored in an intermediate location. So
whenever the client requests for a resource, it will first check the cache. If the resources exist then, it will not
proceed to the server. So caching can help in minimizing the amount of trips which are made to the web server.

https://www.tutorialspoint.com/restful/restful_caching.htm

 Ease of coding – Coding REST Services and subsequent implementation is far easier than SOAP. So if a quick win
solution is required for web services, then REST is the way to go.

 message -https://www.tutorialspoint.com/restful/restful_messages.htm

 addressing-https://www.tutorialspoint.com/restful/restful_addressing.htm

SOAP should be used in the following instances


1. Asynchronous processing and subsequent invocation – if there is a requirement that the client needs a
guaranteed level of reliability and security then the new SOAP standard of SOAP 1.2 provides a lot of additional
features, especially when it comes to security.

2. A Formal means of communication – if both the client and server have an agreement on the exchange format
then SOAP 1.2 gives the rigid specifications for this type of interaction. An example is an online purchasing site in
which users add items to a cart before the payment is made. Let's assume we have a web service that does the
final payment. There can be a firm agreement that the web service will only accept the cart item name, unit
price, and quantity. If such a scenario exists then, it's always better to use the SOAP protocol.

3. Stateful operations – if the application has a requirement that state needs to be maintained from one request to
another, then the SOAP 1.2 standard provides the WS* structure to support such requirements.

SOAP vs. REST API challenges

API is known as the Application Programming Interface and is offered by both the client and the server. In the client world,
this is offered by the browser whereas in the server world it's what is provided by the web service which can either be
SOAP or REST.

Challenges with the SOAP API

1. WSDL file - One of the key challenges of the SOAP API is the WSDL document itself. The WSDL document is what
tells the client of all the operations that can be performed by the web service. The WSDL document will contain
all information such as the data types being used in the SOAP messages and what all operations are available via
the web service. The below code snippet is just part of a sample WSDL file.

<?xml version="1.0"?>
<definitions name="Tutorial"
targetNamespace=http://demo.guru99.com/Tutorial.wsdl
xmlns:tns=http://demo.guru99.com/Tutorial.wsdl
xmlns:xsd1=http://demo.guru99.com/Tutorial.xsd
xmlns:soap=http://schemas.xmlsoap.org/wsdl/soap/
xmlns="http://schemas.xmlsoap.org/wsdl/">

<types>
<schema targetNamespace=http://Demo.guru99.com/Tutorial.xsd
xmlns="http://www.w3.org/2000/10/XMLSchema">

<element name="TutorialNameRequest">
<complexType>
<all>
<element name="TutorialName" type="string"/>
</all>
</complexType>
</element>
<element name="TutorialIDRequest">
<complexType>
<all>
<element name="TutorialID" type="number"/>
</all>
</complexType>
</element>
</schema>
</types>

As per the above WSDL file, we have an element called "TutorialName" which is of the type String which is part of the
element TutorialNameRequest.

Now, suppose if the WSDL file were to change as per the business requirements and the TutorialName has to become
TutorialDescription. This would mean that all the clients who are currently connecting to this web service would then need
to make this corresponding change in their code to accommodate the change in the WSDL file.
This shows the biggest challenge of the WSDL file which is the tight contract between the client and the server and that
one change could cause a large impact, on the whole, client applications.

2. Document size – The other key challenge is the size of the SOAP messages which get transferred from the client
to the server. Because of the large messages, using SOAP in places where bandwidth is a constraint can be a big
issue.

Challenges with the REST API

1. Lack of Security – REST does not impose any sort of security like SOAP. This is why REST is very appropriate for
public available URL's, but when it comes down to confidential data being passed between the client and the
server, REST is the worst mechanism to be used for web services.
2. Lack of state – Most web applications require a stateful mechanism. For example, if you had a purchasing site
which had the mechanism of having a shopping cart, it is required to know the number of items in the shopping
cart before the actual purchase is made. Unfortunately, the burden of maintaining this state lies with the client,
which just makes the client application heavier and difficult to maintain.

Security Threats and Countermeasure

To understand security threats which can be hostile to a web application, let's look at a simple scenario of a web
application and see how it works in terms of Security.

One of the security measures available for the HTTP is the HTTPS protocol. HTTPS is the secure way of communication
between the client and the server over the web. HTTPS makes use of the Secure Sockets layer or SSL for secure
communication. Both the client and the server will have a digital certificate to identify themselves as genuine when any
communication happens between the client and the server.

In a standard HTTPS communication between the client and the server, the following steps take place

1. The client sends a request to the server via the client certificate. When the server sees the client certificate, it
makes a note in its cache system so that it knows the response should only go back to this client.
2. The server then authenticates itself to the client by sending its certificate. This ensures that the client is
communicating with the right server.
3. All communication thereafter between the client and server is encrypted. This ensures that if any other users try
to break the security and get the required data, they would not be able to read it because it would be encrypted.

But the above type of security will not work in all situations. There can come a time when the client can talk to multiple
servers. An example given below shows a client talking to both a database and a web server at a time. In such cases, not all
information can pass through the https protocol.

This is where SOAP comes in action to overcome such obstacles by having the WS Security specification in place. With this
specification, all security related data is defined in the SOAP header element.

The header element can contain the below-mentioned information

1. If the message within the SOAP body has been signed with any security key, that key can be defined in the
header element.
2. If any element within the SOAP Body is encrypted, the header would contain the necessary encryptions keys so
that the message can be decrypted when it reaches the destination.

In a multiple server environments, the above technique of SOAP authentication helps in the following way.

 Since the SOAP body is encrypted, it will only be able to be decrypted by the web server that hosts the web
service. This is because of how the SOAP protocol is designed.
 Suppose if the message is passed to the database server in an HTTP request, it cannot be decrypted because the
database does not have right mechanisms to do so.
 Only when the request actually reaches the Web server as a SOAP protocol, it will be able to decipher the
message and send the appropriate response back to the client.
We will see in the subsequent topics on how the WS Security standard can be used for SOAP.

Web Service Security Standards

As discussed in the earlier section, the WS-Security standard revolves around having the security definition included in the
SOAP Header.

The credentials in the SOAP header is managed in 2 ways.

First, it defines a special element called UsernameToken. This is used to pass the username and password to the web
service.

The other way is to use a Binary Token via the BinarySecurityToken. This is used in situations in which encryption
techniques such as Kerberos or X.509 is used.

Below are the steps which take place in the above workflow

1. A request can be sent from the Web service client to Security Token Service. This service can be an intermediate
web service which is specifically built to supply usernames/passwords or certificates to the actual SOAP web
service.
2. The security token is then passed to the Web service client.
3. The Web service client then called the web service, but, this time, ensuring that the security token is embedded
in the SOAP message.
4. The Web service then understands the SOAP message with the authentication token and can then contact the
Security Token service to see if the security token is authentic or not.

The below snippet shows the format of the authentication part which is part of the WSDL document. Now based on the
below snippet, the SOAP message will contain 2 additional elements, one being the Username and the other being the
Password.

<xs:element name="UsernameToken">
<xs:complexType>
<xs:sequence>
<xs:element ref="Username"/>
<xs:element ref="Password" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="Id" type="xs:ID"/>
</xs:complexType></xs:element>

When the SOAP Message is actually passed between the clients and the server, the part of the message which contains the
user credentials could look like the one shown above. The wsse element name is a special element named defined for
SOAP and means that it contains security based information.
HOW CAN WE SAY THST API IS RESTFUL?
This can be identified by using Richardson model introduced by Leo Richardson.
The Richardson Maturity Model has 4 levels numbered from 0 to 3. Level 0 is not RESTful while Level 4 means your API is fully RESTful.

There are the following levels in the models:


level 0 : not restful API - it is called swamp of POX(plain old XML). there is no involvement of HTTP
concepts and only used XML or communication between request and response.
This will use only one URI to expose the whole API and generally uses only one HTTP method. If we take example of our registration API we
see that that every resource has its own URI. The student resource has a different URI, the course resource has a different URI and the
registration resource has a different URI.
SOAP based web services are the example of this level. This level of API doesn't leverage the full concepts of the HTTP specification. For
example: Every request will be POST request, so if someone wants to delete a student record they will have send the action also in the
request.

level 1 : if there is individual URI's usage for every resources, then it is level 1
In this level every resource has its own URI. This level uses multiple URI where every URI is an entry point to a specific resource. Still this
level uses only POST method for operation.

level 2:if there is usage of standard API HTTP methods (GET,POST,PUT, DELETE) and standard status
codes, then it is level 2
This level says that your API should use protocol properties as much as possible. You must not use single  POST method for all the
operations, but make use of GET when you are requesting a resource, use a DELETE method when you want to delete a resource.
The use of proper response codes is also essential. Use 201 Created response code when a post request comes and resource is created.
Use 200 Ok response for the get request and so on.

level 3: if responses have links that clients use , then it is level 3


This level suggests to use the concept of HATEOAS. The response should contain the logical links of all the resources which the current
resource is related to.
For Example: In case of when the client request for the student information with the roll number 1, then in the response along with the
response of the student, a link of all the URI of all the courses which that student has registered should also be sent.
If an API is at the level 3 this will be known as fully RESTful. This Richardson Model should be used while designing the REST API to make
sure the web services are fully RESTful.
JAX - RX:
tutorialspoint.com/restful/restful_jax_rs.htm
Java API for RESTful Web Services (JAX-RS) is a Java programming language specification that supports creating web services according to
the REST architectural pattern in Java. JAX-RS uses annotations, included in Java SE-5, to simplify the deployment of web service clients
and the end points.
It provides annotations to help in mapping a resource class (a POJO) as a web resource. These annotations include:

 @Path specifies the relative path for a resource class or method.


 @GET, @PUT, @POST, @DELETE specify the HTTP request methods.
 @Produces specify the response type (internet media types), that a particular service will return.
 @Consumes specify the accepted request (internet media types), that a particular service will accept.
 https://www.java4s.com/web-services/restful-web-services-jax-rs-annotations/
 https://www.java4s.com/web-services/how-restful-web-services-extract-input-parameters/

In addition to these, it provides several other annotations, which are also quite useful when it comes to the development of web service.
It is important to note that JAX-RS is just a specification. It needs some implementation to work. JAX-RS can be seen as the interface, which
contains all the specifications, more like a function which is exposed using a URI on Internet. But this function needs a
definition/implementation, which contains the actual logic.
There are several implementation of the JAX-RS. Some famous one includes:

1. Apache CXF, an open source Web Service Framework.


2. Jersey, the reference implementation from SUN.
3. Resteasy, this is JBoss implementation.
4. Restlet

it is a library for rest API which let u to write code for REST applications that makes us ease of
coding. there are many libraries , like jersey, RESTEasy... and are all almost same , if we remove one
API and inserted another library also that application works, this is due to the connection with
common API that s JAX- RX.

JAX-RS contains interface and annotations. all these will be in the package - javax.ws.rs.*
classes will be written to implement all these interfaces and to read annotations from that package.
in this case
these libraries look at our code and works actual work where the JAX-RX API presents in our code.
to build application ,we need to deploy the server like tomcat and we need to include these libraries
to our application .
we need to write our application with JAX-RS API and the we need to deploy the tomcat server with
instance of any libraries(RESTEasy, Apachewing or jersey)
but the good thing here is the API ties up with libraries and then we can get them so we can build
our application with API that also contains libraries.

JERSEY:
we usually use jersey library which is reference to all , lot of people will use as it is basic
Jersey is the reference implementation of the JAX-RS annotations. The Java API for RESTful Web Services,
Jersey implements support for the annotation defined in the JSR-311, making it easy for the developers to
build RESTful web services with Java and Java JVM. Jersey also specifies client libraries to help communicate
with RESTful webservices.

the tomcat server that is deployed inside web.xml will help the jersey to develop the API
jersey will handle the request and handover the response.
the name of packages can be looked into the init param tag of web.xml file.
Creating the REST Resources
The two important points that must be kept in mind while making the bean class are:

1. It should have a default Constructor.


2. The bean class is annotated with the annotation @XmlRootElement. This will convert the java object
to xml and vice versa.

Annotations:

 @Path annotation: This annotation will configure the path of the resource.


 @GET annotation: This annotation will configure that which method will be called at the corresponding path. For example: in
below case getAllStudents() method will be called when a GET request is made for the /students path.
 @Produces annotation: This annotation will configure in which all formats this method can return the response. In the current
example, it can just return application_xml.
 In JAX-RS, you can use @PathParam annotation to extract the parameter from the request URI and map it to any method.
 https://www.javatpoint.com/jax-rs-annotations-example

HATEOAS - Important Concept For REST API


HATEOAS stands for Hypertext As The Engine Of Application State.
 A Rest API is said to be perfect if it doesn't need any documentation at all. It should be so crystal clear to the developer who is consuming
the service that he/she should not even refer to the documentation. It should be designed like a website, like once we go to the Home
page we can navigate to the different resources with the help of hyperlinks.
Now the question is how to achieve this? The simple answer is providing as much related links as possible about the resource in the
response. Lets take the case of our registration application.
A GOOD REST API DOES NOT NEED ANY DOCUMENTATION

https://www.studytonight.com/rest-web-service/hateoas
sample rest example by creating model class:
create model class that is message class and
create message service class to create list of objects
message resource class to call the message service
we can also get JSON , XML response by changing the media type to JSON , XML.
Example of XML response:
@path(/messages) - the http link to hit the messages
@produces - to give response by server
media.type.TEST.PLAIN - it represents the response is in text format

Installing REST Client(PLUGINS:)


A browser can only make a GET request to the serve and receive response in HTML form. So how will you test your newly coded web
services, as you will have to run POST, PUT and DELETE HTTP requests.
There are many options available for the REST client. However, the POSTMAN is simplest to use.
POSTMAN is available as Google extension which you can easily add in your Google Chrome browser.

we have many plugins for different web browser. we use postmanfor google chrome.the UI for this
plugin is as below screenshot
we just pass the link and set the options as required and then hit the send button , then we can see
response in this plugin
to get xml response by changing media type to xml , we also have to change the dependencies in
our web.xml as follows:
Examples of get,put,post,delete:
FILTRATION AND PAGINATION:
pagination means displaying the messages by dividing into no. of. pages ad filtration is getting the
messages by filtering with parameters like year, day or date...
example for filteration:
we can write in 2 ways as mentioned in 2 screenshots depends on our logic
example for pagination:

PARAMETERS:
there are some more multiple path parameters ;
matrix param - to pass the values in link itself
cookies param - to get cookies values
header values - to get header parameters.

instead of writing all parameters no . of .times individually we can take a bean class and write all the
parameters in the class and we will use that class where we need parameters. with @beanparam
@xmltransient is the annotation used before get methods in model class to make that field invisible
in xml response.
instead of writing produces and @ consumes all the time at method level , we can use only once at
class level
new response like creating new message can be done as follows in addmessage method:

handling exceptions:
while writing custom exception we implements exception mapper class and we over ride the
method to handle the custom exceptions.
instead of writing different exceptions for every status ode individually we can create all codes in
generic exception
generic exception:

JAX-RS doesn't know to map the exceptions to status codes with exception mapper.
we have web application exceptions where we create own customized exceptions and match them
with status codes.
the methods for JSON response in media type are in below:

CONTENT NEGOTIATION:
It is a communication between client and server about the format of response in header should
generate based on client requirement
https://www.studytonight.com/rest-web-service/introduction

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy