what design pattern to use in restful web services
Prior to the year 2000, Application Plan Interface, which is now usually called APIs, were designed to be secure which were also very complex to develop, harder to develop, and even harder to maintain. They were not meant to be accessible. In 2000, a grouping of researchers headed by Roy Fielding came up with the idea of REST (REpresentational Land Transfer) which brought out the truthful ability and potential of APIs. The purpose of REST was to create standards for advice between 2 servers that are located anywhere in the world. They came upward with various principles, constraints, and backdrop that constituted a resource-oriented architecture, client-server-based architecture, and interface uniformity that required no state preservation. These were hands cacheable, uncomplicated to develop, and could exist implemented past means of Hypertext Transfer Protocol(HTTP). The rules seemed many, but the purpose was universal. The onset of REST became a true game-changer for the API mural as the APIs adult under REST used less bandwidth, were elementary to develop and the communication was supported via the internet thereby not requiring the servers to be connected physically.
RESTful APIs have also given nascency to diverse trends like deject computing and microservices-based compages. They take made communication and computing over the internet seem piece of cake. Hence, it is important for whatsoever programmer to know what Balance is, how information technology works, what are its features and how can y'all develop services in a secure manner to go with the trend. Many companies prefer developers with Residual knowledge as they can help them develop products that are scalable, easy to maintain and make their products reach out to the earth due to the power of the internet.
In the below department, nosotros volition see what are the virtually commonly asked questions on RESTful web services during an interview and some questions on the JAX-RS library, and some on RESTful web services implemented using the Leap MVC framework.
REST API Bones Interview Questions
1. What do you empathise past RESTful Web Services?
RESTful web services are services that follow REST architecture. Residuum stands for Representational Country 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 spider web browser by means of asking headers, request body, response body, status codes, etc.
2. What is a REST Resources?
Every content in the Residue architecture is considered a resource. The resource is coordinating to the object in the object-oriented programming world. They can either be represented equally text files, HTML pages, images, or any other dynamic data.
- The Residuum Server provides access to these resources whereas the Remainder client consumes (accesses and modifies) these resources. Every resources is identified globally by ways of a URI.
3. What is URI?
Compatible Resources Identifier is the full form of URI which is used for identifying each resources of the REST architecture. URI is of the format:
<protocol>://<service-name>/<ResourceType>/<ResourceID> In that location are 2 types of URI:
- URN: Uniform Resource Name identifies the resource by means of a proper name that is both unique and persistent.
- URN doesn't always specify where to locate the resource on the internet. They are used as templates that are used past other parsers to identify the resources.
- These follow the
urnscheme and usually prefixed withurn:. Examples include-
urn:isbn:1234567890is used for identification of volume based on the ISBN number in a library awarding. -
urn:mpeg:mpeg7:schema:2001is the default namespace rules for metadata of MPEG-seven video.
-
- Whenever a URN identifies a document, they are easily translated into a URL past using "resolver" after which the certificate can be downloaded.
- URL: Compatible Resource Locator has the information regarding fetching of a resource from its location.
- Examples include:
-
http://abc.com/samplePage.html -
ftp://sampleServer.com/sampleFile.zip -
file:///dwelling house/interviewbit/sampleFile.txt
-
- URLs start with a protocol (like ftp, http etc) and they have the data of the network hostname (sampleServer.com) and the path to the certificate(/samplePage.html). It can also have query parameters.
- Examples include:
4. 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 whatsoever other functions.
- The medium of advice betwixt the client and server is called "Messaging".
- Resource are attainable 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 full 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 likewise apply SOAP services as implementation protocol to Residual architectural pattern.
five. What is the concept of statelessness in Residuum?
The Remainder compages is designed in such a fashion that the client land is not maintained on the server. This is known every bit statelessness. The context is provided by the customer to the server using which the server processes the client's request. The session on the server is identified past the session identifier sent past the client.
6. What exercise yous sympathise past JAX-RS?
As the name itself stands (JAX-RS= Java API for RESTful Web Services) is a Coffee-based specification divers by JEE for the implementation of RESTful services. The JAX-RS library makes usage of annotations from Coffee 5 onwards to simplify the process of web services development. The latest version is three.0 which was released in June 2020. This specification also provides necessary back up to create REST clients.
7. 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
Almost normally used condition codes are:
- 200 - success/OK
- 201 - CREATED - used in POST or PUT methods.
- 304 - Not MODIFIED - used in conditional Go requests to reduce the bandwidth use of the network. Here, the body of the response sent should be empty.
- 400 - BAD Request - This tin exist due to validation errors or missing input information.
- 401- UNAUTHORIZED - This is returned when there is no valid authentication credentials sent forth with the request.
- 403 - FORBIDDEN - sent when the user does not take access (or is forbidden) to the resources.
- 404 - NOT Institute - Resource method is not bachelor.
- 500 - INTERNAL SERVER ERROR - server threw some exceptions while running the method.
- 502 - BAD GATEWAY - Server was non able to get the response from some other upstream server.
8. What are the HTTP Methods?
HTTP Methods are besides known as HTTP Verbs. They grade a major portion of uniform interface restriction followed by the Residuum that specifies what activeness has to be followed to get the requested resource. Beneath are some examples of HTTP Methods:
- Get: This is used for fetching details from the server and is basically a read-only functioning.
- Post: This method is used for the cosmos of new resources on the server.
- PUT: This method is used to update the old/existing resources 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 resources on the server.
- OPTIONS: This fetches the listing 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 normally called Crud Operations.
GET, HEAD, OPTIONS are prophylactic and idempotent methods whereas PUT and DELETE methods are only idempotent. Mail and PATCH methods are neither safe nor idempotent.
9. 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 responsibleness lies on the client-side to pass the session id)
- Residue does non 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.
x. Ascertain 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 establish the information and the metadata well-nigh the message.
Residuum API Experienced Interview Questions
11. Differentiate between SOAP and Balance?
| Soap | Rest |
|---|---|
| SOAP - Simple Object Access Protocol | Remainder - Representational Country Transfer |
| Soap is a protocol used to implement web services. | REST is an architectural design pattern for developing spider web services |
| SOAP cannot utilise Remainder equally it is a protocol. | REST architecture tin can have Soap protocol equally part of the implementation. |
| Soap specifies standards that are meant to be followed strictly. | REST defines standards but they need not be strictly followed. |
| SOAP client is more tightly coupled to the server which is similar to desktop applications having strict contracts. | The Residuum client is more flexible like a browser and does non depend on how the server is adult unless it follows the protocols required for establishing communication. |
| SOAP supports but XML transmission between the customer and the server. | REST supports data of multiple formats like XML, JSON, MIME, Text, etc. |
| Lather reads are not cacheable. | REST read requests tin can be buried. |
| Lather uses service interfaces for exposing the resource logic. | REST uses URI to expose the resource logic. |
| Lather is slower. | Remainder is faster. |
| Since Soap is a protocol, it defines its own security measures. | Residuum only inherits the security measures based on what protocol it uses for the implementation. |
| Soap is not unremarkably preferred, just they are used in cases which require stateful data transfer and more reliability. | REST is commonly preferred by developers these days as information technology provides more scalability and maintainability. |
12. While creating URI for spider web services, what are the all-time practices that needs to be followed?
Beneath is the list of all-time practices that demand to exist considered with designing URI for web services:
- While defining resources, use plural nouns. Example: To identify user resource, use the name "users" for that resources.
- While using the long proper noun for resource, use underscore or hyphen. Avoid using spaces between words. For case, to define authorized users resource, the name can be "authorized_users" or "authorized-users".
- The URI is example-insensitive, only equally role of all-time practice, it is recommended to apply 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 condition lawmaking 300.
- Use advisable HTTP methods like Get, PUT, DELETE, PATCH, etc. It is not needed or recommended to use these method names in the URI. Example: To go user details of a item 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 become the accost of the user of a detail id, we tin can apply:
/users/{id}/address
13. What are the best practices to develop RESTful web services?
RESTful web services employ Balance API as means of implementation using the HTTP protocol. REST API is nothing merely an application programming interface that follows REST architectural constraints such equally statelessness, cacheability, maintainability, and scalability. It has become very popular amid the developer community due to its simplicity. Hence, it is very of import to develop safe and secure Remainder APIs that follow good conventions. Beneath are some best practices for developing REST APIs:
- Since Balance supports multiple data formats, information technology is however good practice to develop REST APIs that have and responds with JSON data format whenever possible. This is because a majority of the client and server technologies take inbuilt back up to read and parse JSON objects with ease, thereby making JSON the standard object notation.
- To ensure that the application responds using JSON information format, the response header should take Content-Type set to as
awarding/JSON, this is because certain HTTP clients look at the value of this response header to parse the objects appropriately. - To ensure that the request sends the data in JSON format, again the Content-Type must be set to
application/JSONon the asking header.
- To ensure that the application responds using JSON information format, the response header should take Content-Type set to as
- While naming the resource endpoints, ensure to use plural nouns and not verbs. The API endpoints should exist clear, brief, easy to sympathize, and informative. Using verbs in the resource name doesn't contribute much information because an HTTP request already has what the request is doing in its HTTP method/verb. An appropriate HTTP verb should be used to represent the task of the API endpoint.
- Beneath are the well-nigh ordinarily used HTTP methods to define the verb:
- Become - indicates get/think the resource data
- Mail - indicates create new resource data
- PUT - indicates update the existing resource information
- DELETE - indicates remove the resources information
- Beneath are the well-nigh ordinarily used HTTP methods to define the verb:
- To represent the hierarchy of resources, use the nesting in the naming convention of the endpoints. In case, you lot want to call back data of i object residing in another object, the endpoint should reflect this to communicate what is happening. For instance, to become the address of an writer, we can apply the GET method for the URI
/authors/:id/address'- Please ensure there are no more than 2 or three levels of nesting as the name of the URI can become too long and unwieldy.
- Error Handling should be done gracefully past returning appropriate error codes the awarding has encountered. REST has divers standard HTTP Status codes that tin can be sent forth with the response based on the scenario.
- Error codes should also be accompanied by advisable error messages that can help the developers to have corrective deportment. However, the bulletin should not exist too elaborate equally well which tin can help the hacker to hack your application.
- Common status codes are:
- 400 - Bad Request – customer-side mistake - failed input validation.
- 401 - Unauthorized – The user is not authenticated and hence does not have say-so to access the resource.
- 403 - Forbidden – User is authenticated just is not authorized to access the resource.
- 404 - Not Found – The resource is not found.
- 500 - Internal server error – This is a very generic server-side mistake that is thrown when the server goes down. This shouldn't be returned by the programmer explicitly.
- 502 - Bad Gateway – Server did not receive a valid response from the upstream server.
- 503 - Service Unavailable – Some unexpected things happened on the server such as system failure, overload, etc.
- While retrieving huge resource data, it is advisable to include filtering and pagination of the resources. This is considering returning huge data all at one time tin can slow downward the organisation and reduce the application performance. Hence, filter some items reduces the data to some extent. Pagination of data is done to ensure only some results are sent at a time. Doing this can increment the server performance and reduce the burden of the server resources.
- Skilful security practices are a must while developing Residue APIs. The client-server communication must be individual due to the nature of data sensitivity. Hence, incorporating SSL/TLS becomes the most important step while developing APIs every bit they facilitate establishing secure communication. SSL certificates are easier to get and load on the server.
- Apart from the secure channels, we need to ensure that not everyone should be able to access the resource. For example, normal users should not access the information of admins or another user. Hence, office-based access controls should be in identify to make certain only the right prepare of users can access the right set of data.
- Since REST supports the characteristic of caching, we can use this feature to cache the data in guild to ameliorate the application performance. Caching is done to avoid querying the database for a request repeated times. Caching makes data retrieval fast. Notwithstanding, care must be taken to ensure that the cache has updated data and not outdated ones. Frequent cache update measures need to exist incorporated. There are many cache providers like Redis that tin can assist in caching.
- API Versioning: Versioning needs to be done in case we are planning to brand any changes with the existing endpoints. We do not want to intermission communication between our application and the apps that consume our application while we are working on the API release. The transition has to be seamless. Semantic versioning can be followed. For instance, 3.0.ane represents 3rd major version with the kickoff patch. Ordinarily, in the API endpoints, we ascertain
/v1,/v2, etc at the beginning of the API path.
xiv. What are Idempotent methods? How is it relevant in RESTful spider web services domain?
The pregnant of idempotent is that fifty-fifty after calling a single request multiple times, the effect of the request should exist the aforementioned. While designing REST APIs, we need to proceed in mind to develop idempotent APIs. This is because the consumers can write client-side code which can result in indistinguishable requests intentionally or not. Hence, error-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 one time or x times or more than that remain the aforementioned. This is equivalent to calculation any number with 0.
- Balance provides idempotent methods automatically. Become, PUT, DELETE, Caput, OPTIONS, and TRACE are the idempotent HTTP methods. POST is not idempotent.
- POST is not idempotent because Postal service APIs are usually used for creating a new resource on the server. While calling Post methods N times, in that location volition exist N new resources. This does non result in the same outcome at a time.
- Methods like Get, OPTIONS, TRACE, and HEAD are idempotent considering they do not change the state of resource on the server. They are meant for resource retrieval whenever chosen. They do non issue in write operations on the server thereby making it idempotent.
- PUT methods are generally used for updating the state of resource. If you call PUT methods N times, the kickoff request updates the resource and the subsequent requests will be overwriting the same resources again and again without irresolute anything. Hence, PUT methods are idempotent.
- DELETE methods are said to be idempotent considering when calling them for N times, the showtime request results in successful deletion (Condition Code 200), and the adjacent subsequent requests result in zilch - Status Code 204. The response is different, but at that place is no change of resources on the server-side.
- Even so, if you are attempting to delete the resources nowadays, at last, every time you hit the API, such as the request
DELETE /user/terminalwhich deletes the last user record, then calling the asking N times would delete N resources on the server. This does non brand DELETE idempotent. In such cases, equally part of expert practices, it is advisable to use Mail requests.
- Even so, if you are attempting to delete the resources nowadays, at last, every time you hit the API, such as the request
xv. What are the differences between Residuum and AJAX?
| Residue | AJAX |
|---|---|
| REST- Representational State Transfer | AJAX - Asynchronous javascript and XML |
| Residuum has a URI for accessing resource by means of a request-response design. | AJAX uses XMLHttpRequest object to send requests to the server and the response is interpreted by the Javascript lawmaking dynamically. |
| REST is an architectural pattern for developing customer-server communication systems. | AJAX is used for dynamic updation of UI without the need to reload the page. |
| REST requires the interaction between client and server. | AJAX supports asynchronous requests thereby eliminating the necessity of constant client-server interaction. |
16. Tin can you tell what constitutes the core components of HTTP Request?
In Residue, any HTTP Request has 5 master components, they are:
- Method/Verb − This office tells what methods the request operation represents. Methods like Become, PUT, POST, DELETE, etc are some examples.
- URI − This role is used for uniquely identifying the resources on the server.
- HTTP Version − This function indicates what version of HTTP protocol y'all are using. An instance can exist HTTP v1.i.
- Request Header − This role has the details of the request metadata such every bit client type, the content format supported, bulletin format, cache settings, etc.
- Request Body − This role represents the actual message content to be sent to the server.
17. What constitutes the cadre components of HTTP Response?
HTTP Response has 4 components:
- Response Status Code − This represents the server response status code for the requested resource. Instance- 400 represents a client-side mistake, 200 represents a successful response.
- HTTP Version − Indicates the HTTP protocol version.
- Response Header − This part has the metadata of the response message. Data tin 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.
18. Define Addressing in terms of RESTful Spider 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 full general format of URI is
<protocol>://<application-proper noun>/<blazon-of-resource>/<id-of-resource> 19. What are the differences between PUT and Postal service in Remainder?
| PUT | POST |
|---|---|
| PUT methods are used to request the server to store the enclosed entity in asking. In case, the request does not exist, so new resource has to be created. If the resource exists, then the resources should get updated. | Post method is used to request the server to store the enclosed entity in the request as a new resource. |
The URI should have a resource identifier. Example: PUT /users/{user-id} | The POST URI should indicate the collection of the resources. Instance: POST /users |
| PUT methods are idempotent. | Postal service methods are non idempotent. |
| PUT is used when the client wants to modify a single resource that is role of the collection. If a function of the resource has to be updated, and so PATCH needs to be used. | Postal service methods are used to add a new resources to the collection. |
| The responses are not cached hither despite the idempotency. | Responses are non cacheable unless the response explicitly specifies Cache-Command fields in the header. |
| In general, PUT is used for UPDATE operations. | Mail is used for CREATE operations. |
xx. What makes Rest services to exist 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 information technology easier to scale horizontally considering the servers need not communicate much with each other while serving requests.
21. Based on what factors, you tin decide which type of web services yous need to use - SOAP or REST?
REST services take gained popularity due to the nature of simplicity, scalability, faster speed, improved performance, and multiple data format support. But, SOAP has its own advantages also. Developers employ Lather where the services require advanced security and reliability.
Following are the questions y'all need to ask to help you decide which service tin be used:
- Do y'all want to betrayal resource information or business concern logic?
- Lather is commonly used for exposing business organisation logic and Residuum for exposing data.
- Does the customer require a formal strict contract?
- If yes, Soap provides strict contracts past using WSDL. Hence, SOAP is preferred here.
- Does your service crave support for multiple formats of data?
- If yep, Residual supports multiple information formats which is why it is preferred in this example.
- Does your service crave AJAX call support?
- If yes, Residue tin exist used equally it provides the XMLHttpRequest.
- Does your service crave 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, Lather is preferred. REST inherits the security holding based on the underlying implementation of the protocol. Hence, it can't be preferred at all times.
- Does your service require back up for transactions?
- If yes, SOAP is preferred every bit it is adept 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 information technology consumes a lot of bandwidth.
- Residual makes use of less bandwidth for data transmission.
- Do you desire services that are easy to develop, exam, and maintain frequently?
- Residuum is known for simplicity, hence it is preferred.
22. We can develop webservices using web sockets also as Remainder. What are the differences between these two?
| REST | Web Socket |
|---|---|
| REST follows stateless compages, significant it won't shop any session-based data. | Web Socket APIs follow the stateful protocol equally it necessitates session-based data storage. |
| The mode of communication is uni-directional. At a time, only the server or the client volition communicate. | The communication is bi-directional, advice tin can be done past both client or server at a time. |
| Rest is based on the Request-Response Model. | Web Socket follows the full-duplex model. |
| Every asking will accept sections like header, title, body, URL, etc. | Web sockets practise non have any overhead and hence suited for real-time communication. |
| For every HTTP request, a new TCP connection is fix upward. | There will exist merely one TCP connection and then the client and server tin starting time communicating. |
| Rest web services back up both vertical and horizontal scaling. | Web socket-based services only support vertical scaling. |
| REST depends on HTTP methods to get the response. | Spider web Sockets depend on the IP accost and port number of the arrangement to get a response. |
| Communication is slower hither. | Message transmission happens very faster than REST API. |
| Memory/Buffers are not needed to store data here. | Retention is required to store information. |
The request flow difference between the Rest and Web Socket is shown below:
23. Can nosotros implement ship layer security (TLS) in REST?
Yes, we tin can. TLS does the chore of encrypting the communication betwixt the REST client and the server and provides the means to cosign the server to the client. Information technology is used for secure communication as it is the successor of the Secure Socket Layer (SSL). HTTPS works well with both TLS and SSL thereby making it effective while implementing RESTful web services. One point to mention here is, the REST inherits the belongings of the protocol it implements. So security measures are dependent on the protocol REST implements.
25. What is Payload in terms of RESTful web services?
Payload refers to the information passes in the request trunk. It is not the aforementioned as the asking parameters. The payload can be sent only in Mail methods as role of the asking body.
26. Is it possible to ship payload in the Become and DELETE methods?
No, the payload is not the same every bit the asking parameters. Hence, it is non possible to send payload data in these methods.
27. How tin you test RESTful Web Services?
RESTful spider web services can be tested using various tools similar 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 similar Postman and it provides the facility of documentation of the endpoints too. We can also use tools like Jmeter for functioning and load testing of APIs.
28. 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 1 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 tin impact the server performance.
29. How does HTTP Basic Authentication work?
While implementing Basic Authentication as part of APIs, the user must provide the username and password which is so concatenated by the browser in the form of "username: password" and then perform base64 encoding on it. The encoded value is and so sent every bit the value for the "Dominance" header on every HTTP request from the browser. Since the credentials are only encoded, it is advised to utilize this class when requests are sent over HTTPS as they are not secure and tin can be intercepted by anyone if secure protocols are not used.
30. What is the deviation 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 exist called multiple times without any change in the responses.
According to restcookbook.com, the following is the table that describes what methods are idempotent and what is rubber.
| HTTP Methods | Idempotent | Safe |
|---|---|---|
| OPTIONS | yes | yes |
| GET | yep | aye |
| Head | yes | yep |
| PUT | yes | no |
| POST | no | no |
| DELETE | yeah | no |
| PATCH | no | no |
JAX-RS Interview Questions
31. What are the central features provided by JAX-RS API in Java EE?
JAX-RS stands for Java API for RESTful Spider web services. They are nothing but a fix of Java-based APIs that are provided in the Coffee 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 deportment and the API classes.
- Format Independent: They tin be used to work with a wide range of data types that are supported by the HTTP body content.
- Container Contained: The APIs can exist deployed in the Java EE container or a servlet container such every bit Tomcat or they can also exist plugged into JAX-WS (Java API for XML-based web services) providers.
32. 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.
Example:
import javax.ws.rs.Path; /** * InterviewBitService is a root resource class that is exposed at 'resource_service' path */ @Path('resource_service') public form InterviewBitService { // Defined methods } 33. What do y'all sympathize 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 brand. They are @Go, @POST, @PUT, @DELETE, @HEAD.
Usage Example:
import javax.ws.rs.Path; /** * InterviewBitService is a root resource class that is exposed at 'resource_service' path */ @Path('resource_service') public class InterviewBitService { @Go public String getRESTQuestions () { // some operations } } 34. How tin the JAX-RS applications be configured?
JAX-RS applications have the root resource classes packaged in a war file. There are 2 ways of configuring JAX-RS applications.
- Use @ApplicationPath note in a bracket of
javax.ws.rs.core.Applicationthat is packaged in the WAR file. - Utilise the <servlet-mapping> tag inside the web.xml of the War. spider web.xml is the deployment descriptor of the application where the mappings to the servlets can exist defined.
35. Is information technology 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 amalgam client requests that demand to be executed asynchronously. Invoking a request asynchronously does the task of returning the control to the caller by returning with datatype coffee.util.concurrent.Hereafter whose type is set up to return the service call type. Future objects are used because they have the required methods to check whether the asynchronous calls accept 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.
Let united states empathise this with the help of a random example. We know that the Futurity interface from the java.util.concurrent has the below functions bachelor:
parcel java.util.concurrent; public interface Future<V> { // informs the executor to stop the thread execution boolean cancel (boolean mayInterruptIfRunning) ; // indicates whether the Hereafter was cancelled or non boolean isCancelled () ; // indicates if the executor has completed the task boolean isDone () ; // gets the bodily result from the process. // This blocks the program execution until the result is prepare. Five go () throws InterruptedException, ExecutionException; // also gets actual issue from the process but it throws // the TimeoutException in instance the result is not obtained before specified timeout V become (long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; } Let us consider we accept this function beneath which is used for processing 2 Ids parallelly.
public void processIds (String userId1, String questionId) { Client customer = ClientBuilder.newClient(); Future<Response> futureResponse1 = client.target("http://interviewbitserver.com/users/"+userId).request().async().go(); Future<Guild> futureResponse2 = client.target("http://interviewbitserver.com/questions/"+questionId).request().async().go(Question.class); // block the process until complete Response response1 = futureResponse1.get(); User userObject = response1.readEntity(User.class); //Do processing of userObject // Wait for 2 seconds before fetching record attempt { Question question = futureResponse2.go(ii, TimeUnit.SECONDS); //Exercise Processing of question } take hold of (TimeoutException timeoutException ) { //handle exceptions } return; } In the above case, we see that there are 2 separate requests getting executed parallelly. For the first time to come object, we look the javax.ws.rs.core.Response indefinitely using the go() method until we become the response. For the second future object, we expect for the response merely for ii seconds and if we exercise not get within 2 seconds, then the get() method throws TimeoutException. We tin can likewise use the isDone() method or isCancelled() method to find out whether the executors have completed or cancelled.
36. List the primal annotations that are nowadays in the JAX-RS API?
- @Path - This specifies the relative URI path to the Balance resource.
- @GET - This is a request method designator which is corresponding to the HTTP GET requests. They process Become requests.
- @Postal service - This is a request method designator which is corresponding to the HTTP Postal service requests. They process Post requests.
- @PUT - This is a asking method designator which is corresponding to the HTTP PUT requests. They procedure PUT requests.
- @DELETE - This is a request method designator which is respective to the HTTP DELETE requests. They process DELETE requests.
- @HEAD - This is a request method designator which is corresponding to the HTTP Caput requests. They process Caput requests.
- @PathParam - This is the URI path parameter that helps developers to excerpt the parameters from the URI and use them in the resource course/methods.
- @QueryParam - This is the URI query parameter that helps developers excerpt the query parameters from the URI and utilise them in the resource class/methods.
- @Produces - This specifies what MIME media types of the resources representations are produced and sent to the customer as a response.
- @Consumes - This specifies which MIME media types of the resource representations are accepted or consumed by the server from the client.
Leap RESTful Web Services Interview Questions
37. Ascertain RestTemplate in Spring.
The RestTemplate is the main class meant for the client-side access for Leap-based RESTful services. The communication to the server is accomplished using the REST constraints. This is like to other template classes such as JdbcTemplate, HibernateTemplate, etc provided by Spring. The RestTemplate provides loftier-level implementation details for the HTTP Methods like GET, Mail, PUT, etc, and gives the methods to communicate using the URI template, URI path params, asking/response types, asking object, etc every bit part of arguments.
- Ordinarily used annotations similar
@GetMapping,@PostMapping,@PutMapping, etc are provided by this grade from Spring 4.three. Prior to that, Jump provided (and nonetheless provides)@RequestMappingannotation to indicate what methods were existence used.
38. What is the apply of @RequestMapping?
- The annotation is used for mapping requests to specific handler classes or methods.
- In spring, all the incoming web asking routing is handled past Dispatcher Servlet. When it gets the request, information technology determines which controller is meant for processing the request past ways of asking handlers. The Dispatcher Servlet scans all the classes annotated with @Controller. The process of routing requests depends on @RequestMapping annotations that are declared within the controller classes and their methods.
39. What are the differences between the annotations @Controller and @RestController?
| @Controller | @RestController |
|---|---|
| Mostly used traditional Spring MVC service. | Represents RESTful web service in Leap. |
| It is mostly used in Jump MVC service where model data needs to rendered using view. | It is used in case of RESTful web service that returns object values bound to response body. |
| If response values demand to be converted through HttpMessageConverters and sent via response object, extra note @ResponseBody needs to be used on the class or the method handlers. | The default behavior of the @RestController needs to be written on the response body because it is the combination of @Controller and @ResponseBody. |
| @Controller provides control and flexibility over how the response needs to be sent. | @RestController annotation has no such flexibility and writes all the results to the response body. |
40. What does the annotation @PathVariable exercise?
@PathVariable annotation is used for passing the parameter with the URL that is required to get the data. Jump MVC provides support for URL customization for data retrieval using @PathVariable note.
41. Is it necessary to proceed Leap MVC in the classpath for developing RESTful web services?
Yes. Spring MVC needs to exist on the classpath of the application while developing RESTful web services using Spring. This is because, the Bound MVC provides the necessary annotations similar @RestController, @RequestBody, @PathVariable, etc. Hence the spring-mvc.jar needs to be on the classpath or the corresponding Maven entry in the pom.xml.
42. Ascertain HttpMessageConverter in terms of Bound Residue?
HttpMessageConverter is a strategic interface that specified a converter for conversion between HTTP Requests and responses. Spring Balance uses the HttpMessageConverter for converting responses to diverse information formats like JSON, XML, etc. Spring makes apply of the "Have" header for determining the type of content the customer expects. Based on this, Spring would find the registered message converter interface that is capable of this conversion.
Conclusion
43. Conclusion
We have seen what are the almost commonly asked questions on RESTful web services during an interview. REST APIs accept become a very important tool in the software industry. Developing RESTful web services that are scalable and easily maintainable is considered an art. As the manufacture trends increase, the Balance compages would get more concrete and the need for developers who know the evolution of RESTful web services would increase steadily.
References:
To larn more than virtually REST, you can refer to the below 2 links:
https://restcookbook.com/
https://www.restapitutorial.com/
REST API MCQ
ashworthsiverprours.blogspot.com
Source: https://www.interviewbit.com/rest-api-interview-questions/
0 Response to "what design pattern to use in restful web services"
Enregistrer un commentaire