Sei sulla pagina 1di 35

1. What is a Web Service?

Web Services work on client-server model where client applications can access
web services over the network. Web services provide endpoint URLs and expose
methods that can be accessed over network through client programs written in
java, shell script or any other different technologies.
Web services are stateless and doesnt maintain user session like web
applications.

2. What are the advantages of Web Services?


Some of the advantages of web services are:

o Interoperability: Web services are accessible over network and runs on


HTTP/SOAP protocol and uses XML/JSON to transport data, hence it can be
developed in any programming language. Web service can be written in java
programming and client can be PHP and vice versa.

o Reusability: One web service can be used by many client applications at


the same time.

o Loose Coupling: Web services client code is totally independent with


server code, so we have achieved loose coupling in our application.

o Easy to deploy and integrate, just like web applications.

o Multiple service versions can be running at same time.

What are different types of Web Services?


There are two types of web services:

o SOAP Web Services: Runs on SOAP protocol and uses XML technology
for sending data.

o Restful Web Services: Its an architectural style and runs on HTTP/HTTPS


protocol almost all the time. REST is a stateless client-server architecture
where web services are resources and can be identified by their URIs.
Client applications can use HTTP GET/POST methods to invoke Restful
web services.

What is SOAP?
SOAP stands for Simple Object Access Protocol. SOAP is an XML based industry
standard protocol for designing and developing web services. Since its XML
based, its platform and language independent. So our server can be based on
JAVA and client can be on .NET, PHP etc. and vice versa.

1. What are advantages of SOAP Web Services?


SOAP web services have all the advantages that web services has, some of the
additional advantages are:

o WSDL document provides contract and technical details of the web


services for client applications without exposing the underlying
implementation technologies.

o SOAP uses XML data for payload as well as contract, so it can be easily
read by any technology.

o SOAP protocol is universally accepted, so its an industry standard


approach with many easily available open source implementations.

What are disadvantages of SOAP Web


Services?
Some of the disadvantages of SOAP protocol are:

o Only XML can be used, JSON and other lightweight formats are not
supported.

o SOAP is based on the contract, so there is a tight coupling between client


and server applications.

o SOAP is slow because payload is large for a simple string message, since
it uses XML format.

o Anytime there is change in the server side contract, client stub classes
need to be generated again.

o Cant be tested easily in browser

What is WSDL?
WSDL stands for Web Service Description Language. WSDL is an XML based
document that provides technical details about the web service. Some of the
useful information in WSDL document are: method name, port types, service end
point, binding, method parameters etc.

What are different components of WSDL?


Some of the different tags in WSDL xml are:

o xsd:import namespace and schemaLocation: provides WSDL URL and


unique namespace for web service.

o message: for method arguments

o part: for method argument name and type

o portType: service name, there can be multiple services in a wsdl


document.

o operation: contains method name

o soap:address for endpoint URL.

What is UDDI?
UDDI is acronym for Universal Description, Discovery and Integration. UDDI is a
directory of web services where client applications can lookup for web services.
Web Services can register to the UDDI server and make them available to client
applications.

What is difference between Top Down and


Bottom Up approach in SOAP Web Services?
In Top Down approach first WSDL document is created to establish the contract
between web service and client and then code is written, its also termed as
contract first approach. This is hard to implement because classes need to be
written to confirm the contract established in WSDL. Benefit of this approach is
that both client and server code can be written in parallel.

In Bottom Up approach, first web service code is written and then WSDL is
generated. Its also termed as contract last approach. This approach is easy to
implement because WSDL is generated based on code. In this approach client
code have to wait for WSDL from server side to start their work.

What is REST Web Services?


REST is the acronym for REpresentational State Transfer. REST is an
architectural style for developing applications that can be accessed over the
network. REST architectural style was brought in light by Roy Fielding in his
doctoral thesis in 2000.

REST is a stateless client-server architecture where web services are resources


and can be identified by their URIs. Client applications can use HTTP GET/POST
methods to invoke Restful web services. REST doesnt specify any specific
protocol to use, but in almost all cases its used over HTTP/HTTPS. When
compared to SOAP web services, these are lightweight and doesnt follow any
standard. We can use XML, JSON, text or any other type of data for request and
response.

What are advantages of REST web services?


Some of the advantages of REST web services are:

o Learning curve is easy since it works on HTTP protocol

o Supports multiple technologies for data transfer such as text, xml, json,
image etc.

o No contract defined between server and client, so loosely coupled


implementation.

o REST is a lightweight protocol

o REST methods can be tested easily over browser.

What are disadvantages of REST web


services?
Some of the disadvantages of REST are:

o Since there is no contract defined between service and client, it has to be


communicated through other means such as documentation or emails.
o Since it works on HTTP, there cant be asynchronous calls.

o Sessions cant be maintained.

What is a Resource in Restful web services?


Resource is the fundamental concept of Restful architecture. A resource is an
object with a type, relationship with other resources and methods that operate on
it. Resources are identified with their URI, HTTP methods they support and
request/response data type and format of data.

What are different HTTP Methods supported


in Restful Web Services?
Restful web services supported HTTP methods are GET, POST, PUT, DELETE
and HEAD.

Compare SOAP and REST web services?


SOAP REST

SOAP is a standard protocol for creating web services. REST is an architectural style to create web service

SOAP is acronym for Simple Object Access Protocol. REST is acronym for REpresentational State Trans

SOAP uses WSDL to expose supported methods and REST exposes methods through URIs, there are n

technical details. details.

SOAP web services and client programs are bind with REST doesnt have any contract defined between s

WSDL contract client


SOAP web services and client are tightly coupled with REST web services are loosely coupled.

contract.

SOAP learning curve is hard, requires us to learn about REST learning curve is simple, POJO classes can

WSDL generation, client stubs creation etc. generated easily and works on simple HTTP metho

SOAP supports XML data format only REST supports any data type such as XML, JSON

etc.

SOAP web services are hard to maintain, any change in REST web services are easy to maintain when com

WSDL contract requires us to create client stubs again SOAP, a new method can be added without any ch

and then make changes to client code. client side for existing resources.

SOAP web services can be tested through programs or REST can be easily tested through CURL comman

software such as Soap UI. Browsers and extensions such as Chrome Postma

What are different ways to test web services?


SOAP web services can be tested programmatically by generating client stubs
from WSDL or through software such as Soap UI.

REST web services can be tested easily with program, curl commands and
through browser extensions. Resources supporting GET method can be tested
with browser itself, without any program.

Can we maintain user session in web


services?
Web services are stateless so we cant maintain user sessions in web services.

1. What is difference between SOA and Web


Services?
Service Oriented Architecture (SOA) is an architectural pattern where applications
are designed in terms of services that can be accessed through communication
protocol over network. SOA is a design pattern and doesnt go into
implementation.

Web Services can be thought of as Services in SOAP architecture and providing


means to implement SOA pattern.

2. What is the use of Accept and Content-Type


Headers in HTTP Request?
These are important headers in Restful web services. Accept headers tells web
service what kind of response client is accepting, so if a web service is capable of
sending response in XML and JSON format and client sends Accept header as
application/xml then XML response will be sent. For Accept header
application/json, server will send the JSON response.

Content-Type header is used to tell server what is the format of data being sent in
the request. If Content-Type header is application/xml then server will try to
parse it as XML data. This header is useful in HTTP Post and Put requests.

3. How would you choose between SOAP and REST


web services?
Web Services work on client-server model and when it comes to choose between
SOAP and REST, it all depends on project requirements. Lets look at some of the
conditions affecting our choice:

o Do you know your web service clients beforehand? If Yes, then you can
define a contract before implementation and SOAP seems better choice. But
if you dont then REST seems better choice because you can provide
sample request/response and test cases easily for client applications to use
later on.
o How much time you have? For quick implementation REST is the best
choice. You can create web service easily, test it through browser/curl and
get ready for your clients.

o What kind of data format are supported? If only XML then you can go with
SOAP but if you think about supporting JSON also in future then go with
REST.

What is JAX-WS API?


JAX-WS stands for Java API for XML Web Services. JAX-WS is XML based Java
API to build web services server and client application. Its part of standard Java
API, so we dont need to include anything else which working with it. Refer to JAX-
WS Tutorial for a complete example.

Name some frameworks in Java to implement


SOAP web services?
We can create SOAP web services using JAX-WS API, however some of the other
frameworks that can be used are Apache Axis and Apache CXF. Note that they
are not implementations of JAX-WS API, they are totally different framework that
work on Servlet model to expose your business logic classes as SOAP web
services. Read more at Java SOAP Web Service Eclipse example.

Name important annotations used in JAX-WS


API?
Some of the important annotations used in JAX-WS API are:

o @WebService

o @SOAPBinding

o @WebMethod

What is use
of javax.xml.ws.Endpoint class?
Endpoint class provides useful methods to create endpoint and publish existing
implementation as web service. This comes handy in testing web services before
making further changes to deploy it on actual server.
What is the difference between RPC Style and
Document Style SOAP web Services?
RPC style generate WSDL document based on the method name and its
parameters. No type definitions are present in WSDL document.
Document style contains type and can be validated against predefined schema.
Lets look at these with a simple program. Below is a simple test program where I
am using Endpoint to publish my simple SOAP web service.

TestService.java

package com.journaldev.jaxws.service;

import javax.jws.WebMethod;

import javax.jws.WebService;

import javax.jws.soap.SOAPBinding;

import javax.xml.ws.Endpoint;

@WebService

@SOAPBinding(style = SOAPBinding.Style.RPC)

public class TestService {

@WebMethod

public String sayHello(String msg){

return "Hello "+msg;

public static void main(String[] args){

Endpoint.publish("http://localhost:8888/testWS",
new TestService());
}

When I run above program and then access the WSDL, it gives me below XML.

rpc.xml

<?xml version='1.0' encoding='UTF-8'?>

<!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's


version is JAX-WS RI 2.2.10 svn-
revision#919b322c92f13ad085a933e8dd6dd35d4947364b. --><!--
Generated by JAX-WS RI (http://jax-ws.java.net). RI's
version is JAX-WS RI 2.2.10 svn-
revision#919b322c92f13ad085a933e8dd6dd35d4947364b. -->

<definitions xmlns:wsu="http://docs.oasis-
open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-
1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy"
xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy"
xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://service.jaxws.journaldev.com/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://service.jaxws.journaldev.com/"
name="TestServiceService">

<types/>

<message name="sayHello">

<part name="arg0" type="xsd:string"/>

</message>

<message name="sayHelloResponse">

<part name="return" type="xsd:string"/>

</message>

<portType name="TestService">

<operation name="sayHello">
<input
wsam:Action="http://service.jaxws.journaldev.com/TestServic
e/sayHelloRequest" message="tns:sayHello"/>

<output
wsam:Action="http://service.jaxws.journaldev.com/TestServic
e/sayHelloResponse" message="tns:sayHelloResponse"/>

</operation>

</portType>

<binding name="TestServicePortBinding"
type="tns:TestService">

<soap:binding
transport="http://schemas.xmlsoap.org/soap/http"
style="rpc"/>

<operation name="sayHello">

<soap:operation soapAction=""/>

<input>

<soap:body use="literal"
namespace="http://service.jaxws.journaldev.com/"/>

</input>

<output>

<soap:body use="literal"
namespace="http://service.jaxws.journaldev.com/"/>

</output>

</operation>

</binding>

<service name="TestServiceService">

<port name="TestServicePort"
binding="tns:TestServicePortBinding">

<soap:address location="http://localhost:8888/testWS"/>

</port>
</service>

</definitions>

Notice that types element is empty and we cant validate it against any schema.
Now just change the SOAPBinding.Style.RPC to SOAPBinding.Style.DOCUMENT and
you will get below WSDL.

document.xml

<?xml version='1.0' encoding='UTF-8'?>

<!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's


version is JAX-WS RI 2.2.10 svn-
revision#919b322c92f13ad085a933e8dd6dd35d4947364b. --><!--
Generated by JAX-WS RI (http://jax-ws.java.net). RI's
version is JAX-WS RI 2.2.10 svn-
revision#919b322c92f13ad085a933e8dd6dd35d4947364b. -->

<definitions xmlns:wsu="http://docs.oasis-
open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-
1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy"
xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy"
xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://service.jaxws.journaldev.com/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://service.jaxws.journaldev.com/"
name="TestServiceService">

<types>

<xsd:schema>

<xsd:import
namespace="http://service.jaxws.journaldev.com/"
schemaLocation="http://localhost:8888/testWS?xsd=1"/>

</xsd:schema>

</types>

<message name="sayHello">

<part name="parameters" element="tns:sayHello"/>


</message>

<message name="sayHelloResponse">

<part name="parameters" element="tns:sayHelloResponse"/>

</message>

<portType name="TestService">

<operation name="sayHello">

<input
wsam:Action="http://service.jaxws.journaldev.com/TestServic
e/sayHelloRequest" message="tns:sayHello"/>

<output
wsam:Action="http://service.jaxws.journaldev.com/TestServic
e/sayHelloResponse" message="tns:sayHelloResponse"/>

</operation>

</portType>

<binding name="TestServicePortBinding"
type="tns:TestService">

<soap:binding
transport="http://schemas.xmlsoap.org/soap/http"
style="document"/>

<operation name="sayHello">

<soap:operation soapAction=""/>

<input>

<soap:body use="literal"/>

</input>

<output>

<soap:body use="literal"/>

</output>

</operation>
</binding>

<service name="TestServiceService">

<port name="TestServicePort"
binding="tns:TestServicePortBinding">

<soap:address location="http://localhost:8888/testWS"/>

</port>

</service>

</definitions>

Open schemaLocation URL in browser and you will get below XML.

schemaLocation.xml

<?xml version='1.0' encoding='UTF-8'?>

<!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's


version is JAX-WS RI 2.2.10 svn-
revision#919b322c92f13ad085a933e8dd6dd35d4947364b. -->

<xs:schema xmlns:tns="http://service.jaxws.journaldev.com/"
xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0"
targetNamespace="http://service.jaxws.journaldev.com/">

<xs:element name="sayHello" type="tns:sayHello"/>

<xs:element name="sayHelloResponse"
type="tns:sayHelloResponse"/>

<xs:complexType name="sayHello">

<xs:sequence>

<xs:element name="arg0" type="xs:string" minOccurs="0"/>

</xs:sequence>
</xs:complexType>

<xs:complexType name="sayHelloResponse">

<xs:sequence>

<xs:element name="return" type="xs:string" minOccurs="0"/>

</xs:sequence>

</xs:complexType>

</xs:schema>

So here WSDL document can be validated against the schema definintion.

How to get WSDL file of a SOAP web service?


WSDL document can be accessed by appending ?wsdl to the SOAP endoint URL.
In above example, we can access it at http://localhost:8888/testWS?
wsdl location.

What is sun-jaxws.xml file?


This file is used to provide endpoints details when JAX-WS web services are
deployed in servlet container such as Tomcat. This file is present in WEB-INF
directory and contains endpoint name, implementation class and URL pattern. For
example;

sun-jaxws.xml

<?xml version="1.0" encoding="UTF-8"?>

<endpoints xmlns="http://java.sun.com/xml/ns/jax-
ws/ri/runtime" version="2.0">

<endpoint

name="PersonServiceImpl"
implementation="com.journaldev.jaxws.service.PersonServiceI
mpl"

url-pattern="/personWS"/>

</endpoints>

What is JAX-RS API?


Java API for RESTful Web Services (JAX-RS) is the Java API for creating REST
web services. JAX-RS uses annotations to simplify the development and
deployment of web services. JAX-RS is part of JDK, so you dont need to include
anything to use its annotations.

Name some implementations of JAX-RS API?


There are two major implementations of JAX-RS API.

o Jersey: Jersey is the reference implementation provided by Sun. For using


Jersey as our JAX-RS implementation, all we need to configure its servlet in
web.xml and add required dependencies. Note that JAX-RS API is part of
JDK not Jersey, so we have to add its dependency jars in our application.

o RESTEasy: RESTEasy is the JBoss project that provides JAX-RS


implementation.

2. What is wsimport utility?


We can use wsimport utility to generate the client stubs. This utility comes with
standard installation of JDK. Below image shows an example execution of this
utility for one of JAX-WS project.
3. Name important annotations used in JAX-RS
API?
Some of the important JAX-RS annotations are:

o @Path:
used to specify the relative path of class and methods. We can get
the URI of a webservice by scanning the Path annotation value.

o @GET, @PUT, @POST, @DELETE and @HEAD: used to specify the HTTP request
type for a method.

o @Produces, @Consumes: used to specify the request and response types.

o @PathParam: used to bind the method parameter to path value by parsing


it.

What is the use of @XmlRootElement


annotation?
XmlRootElement annotation is used by JAXB to transform java object to XML and
vice versa. So we have to annotate model classes with this annotation.

How to set different status code in HTTP


response?
For setting HTTP status code other than 200, we have to
use javax.ws.rs.core.Response class for response. Below are some of the
sample return statements showing its usage.

return Response.status(422).entity(exception).build();

return Response.ok(response).build(); //200

1. What is REST?
REST is an architectural style which was brought in by Roy Fielding in 2000 in his
doctoral thesis.

In the REST architecture style, clients and servers exchange representations of


resources by using a standardized interface and protocol.REST isn't protocol
specific, but when people talk about REST they usually mean REST over HTTP.

2. What are Restful web services?


In the web services terms, REpresentational State Transfer (REST) is a stateless
client-server architecture in which the web services are viewed as resources and
can be identified by their URIs. Web services client uses that URI to access the
resource.
It consists of two components REST server which provides access to the resources
and a REST client which accesses and modify the REST resources.

3. What are important features of Restful web services?


Some important features of Restful web services are:
Resource identification through URI:Resources are identified by their URIs
(typically links on internet). So, a client can directly access a RESTful Web Services
using the URIs of the resources (same as you put a website address in the browsers
address bar and get some representation as response).
Uniform interface: Resources are manipulated using a fixed set of four create,
read, update, delete operations: PUT, GET, POST, and DELETE.
Client-Server: A clear separation concerns is the reason behind this constraint.
Separating concerns between the Client and Server helps improve portability in the
Client and Scalability of the server components.
Stateless: each request from client to server must contain all the information
necessary to understand the request, and cannot take advantage of any stored
context on the server.
Cache: to improve network efficiency responses must be capable of being labeled
as cacheable or non-cacheable.
Named resources - the system is comprised of resources which are named using a
URL.
Interconnected resource representations - the representations of the resources
are interconnected using URLs, thereby enabling a client to progress from one state
to another.
Layered components - intermediaries, such as proxy servers, cache servers,
gateways, etc, can be inserted between clients and resources to support
performance, security, etc.
Self-descriptive messages: Resources are decoupled from their representation so
that their content can be accessed in a variety of formats, such as HTML, XML, plain
text, PDF, JPEG, JSON, and others.

4. What are HTTP methods that can be used in Restful web services?
RESTful web services use HTTP protocol methods for the operations they perform.
Some important Methods are:
GET : It defines a reading access of the resource without side-effects.This operation
is idempotent i.e.they can be applied multiple times without changing the result
PUT : It is generally used for updating resource. It must also be idempotent.
DELETE : It removes the resources. The operations are idempotent i.e. they can get
repeated without leading to different results.
POST : It is used for creating a new resource. It is not idempotent.

5. What do you mean by Idempotent and which HTTP methods are idempotent?
Idempotent means result of multiple successful request will not change state of
resource after initial application
For example : Delete is idempotent method because when you first time use delete,
it will delete the resource (initial application) but after that, all other request will
have no result because resource is already deleted. Get, put and delete are HTTP
Idempotent methods.

6. What are differences between Post and Put Http methods?


POST :It is used for creating a new resource. It is not idempotent.
PUT : It is generally used for updating resource. It is idempotent.
Idempotent means result of multiple successful request will not change state of
resource after initial application

7. What happens if resources are shared by multiple clients? Do you need to make
it thread safe explicitly?
New resource instance is created for each request, so you don't need to implement
thread safety or synchronization aid. It is by default thread safe.

8. What is JAX-RS?
Java API for RESTful Web Services (JAX-RS), is a set if APIs to developer REST
service. JAX-RS is part of the Java EE6, and make developers to develop REST web
application easily.
9. What are REST frameworks that you are aware of and which can be used to
create Restful webservices?
There are multiple Rest framework that can be used to create Restful web services
such as

Jersey

RestEasy

Restlet

CFX

Spring Rest webservices

10. What are some important annotations which you use to create Restful web
services?
Some of important annotations which are used for creating web services are:
@Path : This is used to set path for URI at class level or method level
@GET,@POST,@PUT,@DELETE : There are annotations corresponds to HTTP
methods
@Produces(MediaType.TEXT_XML [, more-types ]): @Produces defines which
MIME type is delivered by a method
@PathParam: Used to inject values from the URL into a method parameter.
@Consumes(MediaType.TEXT_XML) : @Cosumes defines which MIME type will be
consumed by the method .

11. Can you use get method to create Resources rather than post?
No, Get should be used only for resource retrieval and not for resource creation.

12. What are ways to test Restful web services?


You require a restful client to test restful web services. You can use:

Postman for chrome browser

poster for firefox

What is a REST Web Service?


There are a set of architectural constraints (we will discuss them shortly) called Rest Style

Constraints. Any service which satisfies these constraints is called RESTful Web Service.

There are a lot of misconceptions about REST Web Services : They are over HTTP , based on

JSON etc. Yes : More than 90% of RESTful Web Services are JSON over HTTP. But these are not

necessary constraints. We can have RESTful Web Services which are not using JSON and which

are not over HTTP.

What are important constraints for a RESTful Web


Service?
The five important constraints for RESTful Web Service are
Client - Server : There should be a service producer and a service consumer.
The interface (URL) is uniform and exposing resources. Interface uses nouns (not
actions)
The service is stateless. Even if the service is called 10 times, the result must be the
same.
The service result should be Cacheable. HTTP cache, for example.
Service should assume a Layered architecture. Client should not assume direct
connection to server - it might be getting info from a middle layer - cache.

What is Richardson Maturity Model?


Richardson Maturity Model defines the maturity level of a Restful Web Service. Following are the

different levels and their characteristics.


Level 0 : Expose SOAP web services in REST style. Expose action based services
(http://server/getPosts, http://server/deletePosts, http://server/doThis, http://server/doThat etc)
using REST.
Level 1 : Expose Resources with proper URIs (using nouns). Ex: http://server/accounts,
http://server/accounts/10. However, HTTP Methods are not used.
Level 2 : Resources use proper URI's + HTTP Methods. For example, to update an
account, you do a PUT to . The create an account, you do a POST to . Uris look like
posts/1/comments/5 and accounts/1/friends/1.
Level 3 : HATEOAS (Hypermedia as the engine of application state). You will tell not only
about the information being requested but also about the next possible actions that the service
consumer can do. When requesting information about a facebook user, a REST service can
return user details along with information about how to get his recent posts, how to get his
recent comments and how to retrieve his friends list.
What are the best practices in designing RESTful APIs?
While designing any API, the most important thing is to think about the api consumer i.e.
the client who is going to use the service. What are his needs? Does the service uri make
sense to him? Does the request, response format make sense to him?
In Rest, we think Nouns (resources) and NOT Verbs (NOT actions). So, URIs should
represent resources. URIs should be hierarchical and as self descriptive as possible. Prefer
plurals.
Always use HTTP Methods. Best practices with respect to each HTTP method is
described in the next question.

What are the best practices in using HTTP methods with


Restful Web Services?
GET : Should not update anything. Should be idempotent (same result in multiple calls).
Possible Return Codes 200 (OK) + 404 (NOT FOUND) +400 (BAD REQUEST)
POST : Should create new resource. Ideally return JSON with link to newly created
resource. Same return codes as get possible. In addition : Return code 201 (CREATED) is
possible.
PUT : Update a known resource. ex: update client details. Possible Return Codes :
200(OK)
DELETE : Used to delete a resource.

Can you explain a little bit about JAX-RS?


JAX-RS is the JEE Specification for Restful web services implemented by all JEE compliant web

servers (and application servers).

Important Annotations:
@ApplicationPath("/"). @Path("users") : used on class and methods to define the url
path.
@GET @POST : Used to define the HTTP method that invokes the method.
@Produces(MediaType.APPLICATION_JSON) : Defines the output format of Restful
service.
@Path("/{id}") on method (and) @PathParam("id") on method parameter : This helps in
defining a dynamic parameter in Rest URL. @Path("{user_id}/followers/{follower_id}") is a
more complicated example.
@QueryParam("page") : To define a method parameter ex: /users?page=10.

Useful methods:
Response.OK(jsonBuilder.build()).build() returns json response with status code.
Json.createObjectBuilder(). add("id",user.getId()); creates a user object.
What are the advantages of Restful web services?
Lightweight : Easy to consume from mobile devices also.
Easy to expose : Little or no restrictions on output format and communication protocol.
Most Restful services use HTTP protocol : Entire web is based on HTTP and is built for
efficiency of HTTP. Things like HTTP caching enable Restful services to be effective.
High Performance : Less xml & soap overhead and More caching enable Restful services
to be highly performant.
REST Interview Question 1:
What is the Caching mechanism that a RESTful service would provide?

This is how I would answer this question
As RESTful service uses HTTP as transport protocol, it can leverage caching
features from HTTP specification as well.

HTTP 1.0 specification has Expires header that can be used to indicate ways
to client side for the appropriate caching intentions of server.
HTTP 1.1 specification however has more caching related features to choose
from.
These are in form of various directives used along with header such as Cache-
Control.

---------------------------------------------------------------------------------------
REST interview question 2:
What are those comma separated directives of Cache-Control header?

This is how I would answer this question
The comma separated directives of Cache-Control headers are
private, public, no-cache, no-store, no-transform, max-age, s-maxage.

---------------------------------------------------------------------------------------
REST interview question 3:

What are the differences between no-cache, and no-store directives used
along with
Cache-Control header?

This is how I would answer this question
no-cache can be set in response in order to inform client/browser that this
response
should not be used for caching content and any of the cache data should not
be sent to
server without revalidation from server.

While no-store is to inform client/browser as not to store any data in response


in local
hard disk of the machine that is used for sending the request.

In case of no-cache, one can use data with revalidation, but in no-store that is
no ways
any data can be retrieved locally from the hard disk and data won't be
available when machine
if restarted.

---------------------------------------------------------------------------------------
REST interview question 4:

If any intermediary proxy is not used to server any response to client's


request,
is there any difference between private and public directives of Cache-
Control?

This is how I would answer this question


No, as private directive may be used to restrict cahing at proxy/CDN server
that could
be some intermediary destinations while serving response.

---------------------------------------------------------------------------------------
REST interview question 5:

What is the difference in usage for the s-maxage and max-age directives?

This is how I would answer this question


s-maxage may be used for the proxy/CDN server to know that this is the
directive
for as maximum age for the data that is sent as response.
While max-age is used as a directive to the client as the maximum age for the
data
that is sent along with response.

---------------------------------------------------------------------------------------
REST interview question 6:

What are the various annotations available from JAX-RS api specification,
for sending data from client-side to service endpoint?

This is how I would answer this question


JAX-RS has provided various annotations for passing data from client-side
code
to service are @PathParam, @FormParam, @MatrixParam, @QueryParam,
@HeaderParam, @CookieParam.
These annotations are also known as Injection Annotations from JAX-RS API.

---------------------------------------------------------------------------------------
REST interview question 7:

How to inject Web container related values and configurations to the JAX-
RS service
implementation instance

This is how I would answer this question


There is an annotation @Context provided by JAX-RS specification for the
REST service
Implemntation to be able to receive helper and web container specific
configuration values.

---------------------------------------------------------------------------------------
REST interview question 8:

Can you write-down an example of MatrixParam expression?

This is how I would answer this question

For example, for the following URI:

/employees/name=Ishtek;age=34

@MatrixParam("age") would return 34 as value, as matrix param precedes with


a ';' as
separator.

---------------------------------------------------------------------------------------

Are you aware of @BeanParam annotation?

Auther's View point/Answer to above question:


Yes, @BeanParam annotation is added in JAX-RS 2.0 version. This annotation
can be used
along with a Bean class for using other annotation types such as
@FormParam, @HeaderParam etc.
as the field level, for using an application specific bean class as argument in
the service
method, rather than using a long list of argument parameters for each of the
different type of
attributes used along with a request.

---------------------------------------------------------------------------------------

Can you elaborate on usage of @BeanParam with an example?

Auther's answer to above question:


Suppose there is a HTML form with ten fields/attributes that is used to receive
input from user,
and this data/fields are to be submitted to the service method, then the REST
service method would
require to define all the ten attributes as arguments for the service method
along with @FormParam
annotation. Instead @BeanParam can be used to declare an application/user
defined bean class with
all these ten attributes as fields. This user defined class can be a single
argument to the REST
service method argument. This way there could be minimal impact when
number of fields changes while
using POST as HTTP method.

---------------------------------------------------------------------------------------

How to approach for change in attributes to the service method in a


Webservice ?

Auther's view/answer :
In order to minimize change/impact on the client side of code, when there is a
change in
argument parameters of the service method, one can choose to use user
defined bean class
as argument to service method, rather than using all the arguments directly in
the service
method definition. In this way, if there is a need for addition or removal of any
attribute/argument
from the service method, no change to the service method definition would be
needed.

---------------------------------------------------------------------------------------

What are the major differences you can state while using SOAP or REST,
in terms of
applicability as concern?

Some of the differences that may be observed in applicability of SOAP or


REST as the
service language/specification :

1. When requirement is to provide a business process as a service, then SOAP


may get
little more attention than RESTful services.
2. When we are exposing a server side object as many different type of
representations
for the client, such as JSON, TXT, XML, Audio, Video and many more (HTTP
content types)
etc. RESTful services can be used/more appropriate than SOAP.
3. In case of contract/interface based service definitions are to be used, then
SOAP can be used.
4. In case of exposing a service for any type of devices, be it
Desktop/Laptop/Netbook, Tablet,
Mobile phones, Kindle etc., and consumer can be a browser (Thin client) or a
native application
(Thick client). In this circumstances we can opt for RESTful services.
5. In case of many different types of transports are to be used for using a
service, then SOAP would
be appropriate over RESTful service.
6. For looking for standards-based service declarations and usage, SOAP has
many standards to use,
such as WS-* standards. Whereas RESTful services would be a specification
way of exposing and
using any service.
7. Looking at slightly more technical aspects of SOAP, SOAP supports custom
objects definitions using
XML Schema and marshalling/unmashalling of various datatypes to
communicate across diverse platforms.

---------------------------------------------------------------------------------------

How can you apply security to RESTful services

Some of the options available to use for securing a RESTful service, for now,
are
1. Basic Authentication
This type of Authentication will require transport level encryption(SSL), as
user
credentials are to be sent via wire in plain text.

2. OAuth 1.0a / OAuth 2.0


OAuth 1.0a is using advanced encryption for passing token for authentication
purposes.
OAuth 2.0 is using SSL for transport level security.

3. Custom/Third-party security protocol

---------------------------------------------------------------------------------------

What is the main factor to consider while choosing OAuth version to use,
whether to use
OAuth 1.0a or OAuth 2.0?

The main reson is the sensitivity of the data that is exchanged, and transport
level
security related considerations. If the application data is less sensitive,
the OAuth 1.0a could be well enough for use, and OAuth 1.0a specification
can be applied
without much of encryptions on transport. But OAuth 2.0 would rely on HTTPS
transport
level security/encryption for communication.

---------------------------------------------------------------------------------------

What are the various credential types used along with OAuth 2.0?

There are three types of credentials available to use along with OAuth 2.0,
such as
Bearer Token, MAC token, SAML.

---------------------------------------------------------------------------------------

What are the HTTP methods corresponding to CRUD operations?

POST - Create
GET - Read
PUT - Update
DELETE - Delete

are the corresponding HTTP method used for CRUD operations with
resource(s).

---------------------------------------------------------------------------------------

Can you write a very simple code showing resource being exposed as
RESTful service?

@Path("/book")
public class Book {

@GET
@Path("{id}")
public Book getBookInfo(@PathParam("id") String bookId) {
//return Book Instance by using value bookId.
return new Book();
}
}

Acessing this Book resource by using an URI as


<<WEB_APP_NAME>>/book/b001

---------------------------------------------------------------------------------------

What are the annotations that can be used for specifying content-type that
is supported
by any RESTful service?

@Produces("text/xml") and @Consumes("text/xml") are the annotations that


are used for specifying
ways of defining any restrictions that can be defined at method-level for any
RESTful service.

---------------------------------------------------------------------------------------

For using JAXB supported XML to Custom-object and Custom-object to


XML mapping/conversion,
along with RESTful service, what are the annotations those can be used
along with custom object?

@XmlRootElement, @XmlElement, @XmlAttribute, @XmlAccessorType etc.,


are the annotations from JAXB
can be used along with custom class for defining class, field level fields.

---------------------------------------------------------------------------------------

As @FormParam can be used for passing form parameters in request, but


in case parameter
set is likely to change (parameters can be added or removed), then how to
insulate RESTful service
method definition from change?

MultivaluedMap<String, String> type can be used to define argument


parameter for the RESTful method
signature for passing key and value pair in request.

---------------------------------------------------------------------------------------

Is there any ways to provide custom/own JAXBContext for


marshalling/unmarshalling XML to Object
and vice versa, rather than using default JAXBContext as available with
JAX-RS provider?

Yes, by implementing class file that implements


ContextResolver<JAXBContext> and overriddes
public getContext (Class<?>) method for returning custom implementation of
JAXBContext.

Added on this page, as of 03-July-2014:


Have you used Jersey framework or any other implementation for JAX-RS
specification?

Answer :
Jersey Framework can be used along with web container that is having support
for JAX-RS
or not. Where as any web container that has support for JAX-RS specification,
can be used
to provide a resource as RESTful web service.
---------------------------------------------------------------------------------------

Is there any ways to code so as to provide HTTP headers to a method in


the main RESOURCE class
file?

Answer :
Yes, by using @Context as argument type for the method that is exposed as
REST uri.

import javax.ws.rs.core.HttpHeaders;
...
...
@GET
@Path("abc")
public void getValue(@Context HttpHeaders headers) {
...
...
}
---------------------------------------------------------------------------------------

Have you used Maven to generate Jersey based RESTful services? if yes,
how?

Answer :
I have used a archetype from Maven repository, called as 'jersey-quickstart-
webapp',
for generating a web application, just to start head's up on using Jersey for
creating
RESTful services.
---------------------------------------------------------------------------------------

Can you be able to provide certain context-level parameters in web.xml,


and receiving
parameter value in the resource method?

Answer :
One can define context parameter in web.xml file and corresponding value of
the parameter
in the resource method, by using @Context annotations with instance level
variable of
ServletContext type.
---------------------------------------------------------------------------------------

What are the headers types from HTTP request, those can be used for
mapping same URI
but different resource methods?

Answer :
One can use Accept, Accept-Language, Accept-Encoding, Content-Type with
appropriate values
for mapping same URI but different methods. Appropriate method would be
called that is
receiving corresponding values in form of those headers, in the HTTP
REQUEST.

Please keep visiting this page... as more questions will be added here,
as and when available.
---------------------------------------------------------------------------------------

Is that any ways to approach so that changes(addition/deletion) in the


form-level parameters
would not have impact on the Resource method signature/arguments

Answer :
One can explore javax.ws.rs.core.MultivaluedMap<Object, Object> and its
implementations
for providing ways to pass form-level POST parameters and corresponding
values. This way
additions and deletions won't effect method signature to some level.
---------------------------------------------------------------------------------------

What is the encoding media type associated with a FORM data?

application/x-www-form-urlencoded is the media type of the FORM data

---------------------------------------------------------------------------------------
As per JAX-RS specification, what are the corresponding annotations
used for various HTTP operations,
such as GET, PUT, POST, DELETE, HEAD etc.?

Answer :
Various annotations for these operations are
@javax.ws.rs.GET for HTTP GET Operation
@javax.ws.rs.PUT for HTTP PUT Operation
@javax.ws.rs.POST for HTTP POST Operation
@javax.ws.rs.DELETE for HTTP DELETE Operation
@javax.ws.rs.HEAD for HTTP HEAD Operation

---------------------------------------------------------------------------------------

For an example, if the requirement is to retrieve all the books in a library


and the result would be in
XML format, how would you write a code for this in simplest form, or just
write the Java class that does this mapping ?

Answer :
The main class file would have to have a Path configured, here I shall show
this using annotations,
@Path("/library")
public class LibraryDemoService {
//Then I shall provide a method with public as access modifier and with
appropriate annotations
//such as GET and Produces
//GET for making this method ready to receive any HTTP GET method request
and Produces denotes that
//this method would return a result in Text/XML as return type.

@GET
@Path("books")
@Produces("application/xml")
public String retrieveAllBookInLibrary() {
return "<books><book></book><books/>"; //or any other ways of forming
the actual return result
}
}

---------------------------------------------------------------------------------------

In the code that you have just written, can you add a separate method for
retrieving a selected book with a ISBN code?

Answer
Sure, we can add another method with a path for book and a parameter for
ISBN code, may be something like as shown below,

@GET
@Path("books/book/{isbnCode}")
@Produces("text/xml")
public String retriveBook(@PathParam("isbnCode") String isbnCode) {
return "<book></book>"; //or any other ways of forming the actual return
result
}

---------------------------------------------------------------------------------------

Potrebbero piacerti anche