Rest services interview

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

While creating URI for web services, what are the best practices that needs to be followed?

Below is the list of best practices that need to be considered with designing URI for web services: While defining resources, use plural nouns. Example: To identify user resource, use the name "users" for that resource. While using the long name for resources, use underscore or hyphen. Avoid using spaces between words. For example, to define authorized users resource, the name can be "authorized_users" or "authorized-users". The URI is case-insensitive, but as part of best practice, it is recommended to use lower case only. While developing URI, the backward compatibility must be maintained once it gets published. When the URI is updated, the older URI must be redirected to the new one using the HTTP status code 300. Use appropriate HTTP methods like GET, PUT, DELETE, PATCH, etc. It is not needed or recommended to use these method names in the URI. Example: To get user details of a particular ID, use /users/{id}instead of /getUser Use the technique of forward slashing to indicate the hierarchy between the resources and the collections. Example: To get the address of the user of a particular id, we can use: /users/{id}/address

What are the features of RESTful web services?

Every RESTful web service has the following features: - The service is based on the Client-Server model. - The service uses HTTP Protocol for fetching data/resources, query execution, or any other functions. - The medium of communication between the client and server is called "Messaging". - Resources are accessible to the service by means of URIs. - It follows the statelessness concept where the client request and response are not dependent on others and thereby provides total assurance of getting the required data. - These services also use the concept of caching to minimize the server calls for the same type of repeated requests. - These services can also use SOAP services as implementation protocol to REST architectural pattern.

What is REST resource?

Every content in the REST architecture is considered a resource. The resource is analogous to the object in the object-oriented programming world. They can either be represented as text files, HTML pages, images, or any other dynamic data. The REST Server provides access to these resources whereas the REST client consumes (accesses and modifies) these resources. Every resource is identified globally by means of a URI.

What are the HTTP Methods?

HTTP Methods are also known as HTTP Verbs. They form a major portion of uniform interface restriction followed by the REST that specifies what action has to be followed to get the requested resource. Below are some examples of HTTP Methods: GET: This is used for fetching details from the server and is basically a read-only operation. POST: This method is used for the creation of new resources on the server. PUT: This method is used to update the old/existing resource on the server or to replace the resource. DELETE: This method is used to delete the resource on the server. PATCH: This is used for modifying the resource on the server. OPTIONS: This fetches the list of supported options of resources present on the server. The POST, GET, PUT, DELETE corresponds to the create, read, update, delete operations which are most commonly called CRUD Operations. GET, HEAD, OPTIONS are safe and idempotent methods whereas PUT and DELETE methods are only idempotent. POST and PATCH methods are neither safe nor idempotent.

What constitutes the core components of HTTP Response?

HTTP Response has 4 components: Response Status Code − This represents the server response status code for the requested resource. Example- 400 represents a client-side error, 200 represents a successful response. HTTP Version − Indicates the HTTP protocol version. Response Header − This part has the metadata of the response message. Data can describe what is the content length, content type, response date, what is server type, etc. Response Body − This part contains what is the actual resource/message returned from the server.

Define HttpMessageConverter in terms of Spring REST?

HttpMessageConverter is a strategic interface that specified a converter for conversion between HTTP Requests and responses. Spring REST uses the HttpMessageConverter for converting responses to various data formats like JSON, XML, etc. Spring makes use of the "Accept" header for determining the type of content the client expects. Based on this, Spring would find the registered message converter interface that is capable of this conversion

Can you tell what constitutes the core components of HTTP Request?

In REST, any HTTP Request has 5 main components, they are: Method/Verb − This part tells what methods the request operation represents. Methods like GET, PUT, POST, DELETE, etc are some examples. URI − This part is used for uniquely identifying the resources on the server. HTTP Version − This part indicates what version of HTTP protocol you are using. An example can be HTTP v1.1. Request Header − This part has the details of the request metadata such as client type, the content format supported, message format, cache settings, etc. Request Body − This part represents the actual message content to be sent to the server.

How can the JAX-RS applications be configured?

JAX-RS applications have the root resource classes packaged in a war file. There are 2 means of configuring JAX-RS applications. Use @ApplicationPath annotation in a subclass of javax.ws.rs.core.Application that is packaged in the WAR file. Use the <servlet-mapping> tag inside the web.xml of the WAR. web.xml is the deployment descriptor of the application where the mappings to the servlets can be defined.

What are the key features provided by JAX-RS API in java EE?

JAX-RS stands for Java API for RESTful Web services. They are nothing but a set of Java-based APIs that are provided in the Java EE which is useful in the implementation and development of RESTful web services. Features of JAX-RS are: POJO-based: The APIs in the JAX-RS is based on a certain set of annotations, classes, and interfaces that are used with POJO (Plain Old Java Object) to expose the services as web services. HTTP-based: The JAX-RS APIs are designed using HTTP as their base protocol. They support the HTTP usage patterns and they provide the corresponding mapping between the HTTP actions and the API classes. Format Independent: They can be used to work with a wide range of data types that are supported by the HTTP body content. Container Independent: The APIs can be deployed in the Java EE container or a servlet container such as Tomcat or they can also be plugged into JAX-WS (Java API for XML-based web services) providers.

Is it possible to send payload in the GET and DELETE methods?

No, the payload is not the same as the request parameters. Hence, it is not possible to send payload data in these methods.

What are the differences between PUT and POST in REST?

PUT: - PUT methods are used to request the server to store the enclosed entity in request. In case, the request does not exist, then new resource has to be created. If the resource exists, then the resource should get updated. - The URI should have a resource identifier. Example: PUT /users/{user-id} - PUT methods are idempotent - PUT is used when the client wants to modify a single resource that is part of the collection. If a part of the resource has to be updated, then PATCH needs to be used. - The responses are not cached here despite the idempotency. - In general, PUT is used for update operations. POST:

What is payload in terms of RESTful web services?

Payload refers to the data passes in the request body. It is not the same as the request parameters. The payload can be sent only in POST methods as part of the request body.

What makes REST services to be easily scalable?

REST services follow the concept of statelessness which essentially means no storing of any data across the requests on the server. This makes it easier to scale horizontally because the servers need not communicate much with each other while serving requests.

Based on what factors, you can decide which type of web services you need to use- SOAP or REST?

REST services have gained popularity due to the nature of simplicity, scalability, faster speed, improved performance, and multiple data format support. But, SOAP has its own advantages too. Developers use SOAP where the services require advanced security and reliability. Do you want to expose resource data or business logic?SOAP is commonly used for exposing business logic and REST for exposing data. Does the client require a formal strict contract?If yes, SOAP provides strict contracts by using WSDL. Hence, SOAP is preferred here. Does your service require support for multiple formats of data?If yes, REST supports multiple data formats which is why it is preferred in this case. Does your service require AJAX call support?If yes, REST can be used as it provides the XMLHttpRequest. Does your service require both synchronous and asynchronous requests?SOAP has support for both sync/async operations.REST only supports synchronous calls. Does your service require statelessness?If yes, REST is suitable. If no, SOAP is preferred. Does your service require a high-security level?If yes, SOAP is preferred. REST inherits the security property based on the underlying implementation of the protocol. Hence, it can't be preferred at all times. Does your service require support for transactions?If yes, SOAP is preferred as it is good in providing advanced support for transaction management. What is the bandwidth/resource required?SOAP involves a lot of overhead while sending and receiving XML data, hence it consumes a lot of bandwidth.REST makes use of less bandwidth for data transmission. Do you want services that are easy to develop, test, and maintain frequently?REST is known for simplicity, hence it is preferred.

We can develop webservices using web sockets as well as REST. What are the differences between these two?

REST: REST follows stateless architecture, meaning it won't store any session-based data. The mode of communication is uni-directional. At a time, only the server or the client will communicate. REST is based on the Request-Response Model. Every request will have sections like header, title, body, URL, etc. For every HTTP request, a new TCP connection is set up. REST web services support both vertical and horizontal scaling. REST depends on HTTP methods to get the response. Communication is slower here. Memory/Buffers are not needed to store data here. Web Socket: Web Socket APIs follow the stateful protocol as it necessitates session-based data storage. The communication is bi-directional, communication can be done by both client or server at a time. Web Socket follows the full-duplex model. Web sockets do not have any overhead and hence suited for real-time communication. There will be only one TCP connection and then the client and server can start communicating. Web socket-based services only support vertical scaling. Web Sockets depend on the IP address and port number of the system to get a response. Message transmission happens very faster than REST API. Memory is required to store data.

What do you understand by RESTful web service?

RESTful web services are services that follow REST architecture. REST stands for Representational State Transfer and uses HTTP protocol (web protocol) for implementation. These services are lightweight, provide maintainability, scalability, support communication among multiple applications that are developed using different programming languages. They provide means of accessing resources present at server required for the client via the web browser by means of request headers, request body, response body, status codes, etc.

How can you test RESTful web services?

RESTful web services can be tested using various tools like Postman, Swagger, etc. Postman provides a lot of features like sending requests to endpoints and show the response which can be converted to JSON or XML and also provides features to inspect request parameters like headers, query parameters, and also the response headers. Swagger also provides similar features like Postman and it provides the facility of documentation of the endpoints too. We can also use tools like Jmeter for performance and load testing of APIs.

What is the difference between idempotent and safe HTTP methods?

Safe methods are those that do not change any resources internally. These methods can be cached and can be retrieved without any effects on the resource. Idempotent methods are those methods that do not change the responses to the resources externally. They can be called multiple times without any change in the responses. HTTP Methods | Idempotent | Safe Options yes. yes GET. yes. yes HEAD. yes yes PUT yes no POST. no no DELETE yes no PATCH no no

What is the concept of statelessness in REST?

The REST architecture is designed in such a way that the client state is not maintained on the server. This is known as statelessness. The context is provided by the client to the server using which the server processes the client's request. The session on the server is identified by the session identifier sent by the client.

Define RestTemplate in Spring.

The RestTemplate is the main class meant for the client-side access for Spring-based RESTful services. The communication to the server is accomplished using the REST constraints. This is similar to other template classes such as JdbcTemplate, HibernateTemplate, etc provided by Spring. The RestTemplate provides high-level implementation details for the HTTP Methods like GET, POST, PUT, etc, and gives the methods to communicate using the URI template, URI path params, request/response types, request object, etc as part of arguments. Commonly used annotations like @GetMapping, @PostMapping, @PutMapping, etc are provided by this class from Spring 4.3. Prior to that, Spring provided (and still provides) @RequestMapping annotation to indicate what methods were being used.

What is the use of @RequestMapping?

The annotation is used for mapping requests to specific handler classes or methods. In spring, all the incoming web request routing is handled by Dispatcher Servlet. When it gets the request, it determines which controller is meant for processing the request by means of request handlers. The Dispatcher Servlet scans all the classes annotated with @Controller. The process of routing requests depends on @RequestMapping annotations that are declared inside the controller classes and their methods.

Can you tell the disadvantages of RESTful web services?

The disadvantages are: As the services follow the idea of statelessness, it is not possible to maintain sessions. (Session simulation responsibility lies on the client-side to pass the session id) REST does not impose security restrictions inherently. It inherits the security measures of the protocols implementing it. Hence, care must be chosen to implement security measures like integrating SSL/TLS based authentications, etc.

What are Idempotent methods? How is it relevant in RESTful web services domain?

The meaning of idempotent is that even after calling a single request multiple times, the outcome of the request should be the same. While designing REST APIs, we need to keep in mind to develop idempotent APIs. This is because the consumers can write client-side code which can result in duplicate requests intentionally or not. Hence, fault-tolerant APIs need to be designed so that they do not result in erroneous responses. - Idempotent methods ensure that the responses to a request if called once or ten times or more than that remain the same. This is equivalent to adding any number with 0. - REST provides idempotent methods automatically. GET, PUT, DELETE, HEAD, OPTIONS, and TRACE are the idempotent HTTP methods. POST is not idempotent. POST is not idempotent because POST APIs are usually used for creating a new resource on the server. While calling POST methods N times, there will be N new resources. This does not result in the same outcome at a time.

Define Messaging in terms of RESTful web services.

The technique of sending a message from the REST client to the REST server in the form of an HTTP request and the server responding back with the response as HTTP Response is called Messaging. The messages contained constitute the data and the metadata about the message.

What is the maximum payload size that can be sent in POST methods?

Theoretically, there is no restriction on the size of the payload that can be sent. But one must remember that the greater the size of the payload, the larger would be the bandwidth consumption and time taken to process the request that can impact the server performance.

Should we make the resources thread safe explicitly if they are made to share across multiple clients?

There is no need to explicitly making the resources thread-safe because, upon every request, new resource instances are created which makes them thread safe by default

What are HTTP Status codes?

These are the standard codes that refer to the predefined status of the task at the server. Following are the status codes formats available: 1xx - represents informational responses 2xx - represents successful responses 3xx - represents redirects 4xx - represents client errors 5xx - represents server errors

What do you understand by request method designator annotations?

They are the runtime annotations in the JAX-RS library that are applied to Java methods. They correspond to the HTTP request methods that the clients want to make. They are @GET, @POST, @PUT, @DELETE, @HEAD.

How does HTTP Basic Authentication work?

While implementing Basic Authentication as part of APIs, the user must provide the username and password which is then concatenated by the browser in the form of "username: password" and then perform base64 encoding on it. The encoded value is then sent as the value for the "Authorization" header on every HTTP request from the browser. Since the credentials are only encoded, it is advised to use this form when requests are sent over HTTPS as they are not secure and can be intercepted by anyone if secure protocols are not used.

Is it necessary to keep Spring MVC in the classpath for developing RESTful web services?

Yes. Spring MVC needs to be on the classpath of the application while developing RESTful web services using Spring. This is because, the Spring MVC provides the necessary annotations like @RestController, @RequestBody, @PathVariable, etc. Hence the spring-mvc.jar needs to be on the classpath or the corresponding Maven entry in the pom.xml.

Is it possible to make asynchronous requests in JAX-RS?

Yes. the JAX-RS Client API provides a method called Invocation.Builder.async() that is used for constructing client requests that need to be executed asynchronously. Invoking a request asynchronously does the task of returning the control to the caller by returning with datatype java.util.concurrent.Future whose type is set to return the service call type. Future objects are used because they have the required methods to check whether the asynchronous calls have been completed and if yes, then retrieve the responses. They also provide the flexibility to cancel the request invocations and also check if the cancellation has been successful.

What are the differences between the annotations @Controller and @RestController?

@Controller Mostly used traditional Spring MVC service. It is mostly used in Spring MVC service where model data needs to rendered using view. If response values need to be converted through HttpMessageConverters and sent via response object, extra annotation @ResponseBody needs to be used on the class or the method handlers. @Controller provides control and flexibility over how the response needs to be sent. @RestController Represents RESTful web service in Spring. It is used in case of RESTful web service that returns object values bound to response body. The default behavior of the @RestController needs to be written on the response body because it is the combination of @Controller and @ResponseBody. @RestController annotation has no such flexibility and writes all the results to the response body.

List the key annotations that are present in the JAX-RS API?

@Path - This specifies the relative URI path to the REST resource. @GET - This is a request method designator which is corresponding to the HTTP GET requests. They process GET requests. @POST - This is a request method designator which is corresponding to the HTTP POST requests. They process POST requests. @PUT - This is a request method designator which is corresponding to the HTTP PUT requests. They process PUT requests. @DELETE - This is a request method designator which is corresponding to the HTTP DELETE requests. They process DELETE requests. @HEAD - This is a request method designator which is corresponding to the HTTP HEAD requests. They process HEAD requests. @PathParam - This is the URI path parameter that helps developers to extract the parameters from the URI and use them in the resource class/methods. @QueryParam - This is the URI query parameter that helps developers extract the query parameters from the URI and use them in the resource class/methods. @Produces - This specifies what MIME media types of the resource representations are produced and sent to the client as a response. @Consumes - This specifies which MIME media types of the resource representations are accepted or consumed by the server from the client.

What does the annotation @PathVariable do?

@PathVariable annotation is used for passing the parameter with the URL that is required to get the data. Spring MVC provides support for URL customization for data retrieval using @PathVariable annotation.

Define RESTful Root Resource Classes in the JAX-RS API?

A resource class is nothing but a Java class that uses JAX-RS provided annotations for implementing web resources. They are the POJOs that are annotated either with @Path or have at least one method annotated with @Path, @GET, @POST, @DELETE, @PUT, etc.

Define Addressing in terms of RESTful Web Services.

Addressing is the process of locating a single/multiple resources that are present on the server. This task is accomplished by making use of URI (Uniform Resource Identifier). The general format of URI is <protocol>://<application-name>/<type-of-resource>/<id-of-resource>

What do you understand by JAX-RS?

As the name itself stands (JAX-RS= Java API for RESTful Web Services) is a Java-based specification defined by JEE for the implementation of RESTful services. The JAX-RS library makes usage of annotations from Java 5 onwards to simplify the process of web services development. The latest version is 3.0 which was released in June 2020. This specification also provides necessary support to create REST clients.


Ensembles d'études connexes

BA 1500 - Fundamentals of the business world

View Set

1. Foundations: Data, Data, Everywhere

View Set

HESI Review Question Combined Pt. 2

View Set