banner



How You Will Develop A Rest Web Service End To End Interview

Prior to the year 2000, Application Programme Interface, which is now usually called APIs, were designed to be secure which were also very circuitous to develop, harder to develop, and fifty-fifty harder to maintain. They were non meant to exist accessible. In 2000, a group of researchers headed past Roy Fielding came upwards with the thought of REST (REpresentational Land Transfer) which brought out the truthful power and potential of APIs. The purpose of REST was to create standards for communication between ii servers that are located anywhere in the world. They came up with various principles, constraints, and backdrop that constituted a resources-oriented architecture, client-server-based architecture, and interface uniformity that required no state preservation. These were easily cacheable, simple to develop, and could be implemented past means of Hypertext Transfer Protocol(HTTP). The rules seemed many, but the purpose was universal. The onset of Remainder became a true game-changer for the API mural as the APIs adult under REST used less bandwidth, were simple to develop and the communication was supported via the net thereby not requiring the servers to be connected physically.

RESTful APIs have also given birth to various trends like deject computing and microservices-based architecture. They take made advice and computing over the cyberspace seem easy. Hence, it is important for whatever programmer to know what REST is, how it works, what are its features and how can you develop services in a secure manner to get with the trend. Many companies adopt developers with REST knowledge equally they can help them develop products that are scalable, easy to maintain and make their products reach out to the earth due to the ability of the cyberspace.

In the below section, we volition meet what are the most 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 Spring MVC framework.

REST API Basic Interview Questions

1. What do you understand past RESTful Spider web Services?

RESTful web services are services that follow Remainder 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 unlike programming languages. They provide means of accessing resources present at server required for the client via the web browser by means of asking headers, request torso, response body, status codes, etc.

two. What is a Remainder Resource?

Every content in the Balance architecture is considered a resource. The resource is analogous to the object in the object-oriented programming earth. They can either be represented as text files, HTML pages, images, or any other dynamic data.

  • The Residue Server provides access to these resources whereas the REST customer consumes (accesses and modifies) these resources. Every resource is identified globally by means of a URI.

3. What is URI?

Uniform Resource Identifier is the total form of URI which is used for identifying each resource of the Residual compages. URI is of the format:

                  <protocol>://<service-name>/<ResourceType>/<ResourceID>                

There are 2 types of URI:

  • URN: Compatible Resource Proper name identifies the resources past means of a 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 by other parsers to identify the resources.
    • These follow the urn scheme and ordinarily prefixed with urn:. Examples include
      • urn:isbn:1234567890 is used for identification of book based on the ISBN number in a library application.
      • urn:mpeg:mpeg7:schema:2001 is the default namespace rules for metadata of MPEG-7 video.
    • Whenever a URN identifies a document, they are easily translated into a URL by using "resolver" afterward which the document can exist downloaded.
  • URL: Uniform 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:///home/interviewbit/sampleFile.txt
    • URLs start with a protocol (like ftp, http etc) and they have the information of the network hostname (sampleServer.com) and the path to the document(/samplePage.html). It can also have query parameters.

four. What are the features of RESTful Web Services?

Every RESTful spider web service has the following features:

  • The service is based on the Client-Server model.
  • The service uses HTTP Protocol for fetching information/resources, query execution, or any other functions.
  • The medium of communication between the customer 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 balls of getting the required data.
  • These services also use the concept of caching to minimize the server calls for the same blazon of repeated requests.
  • These services tin also utilise SOAP services as implementation protocol to REST architectural blueprint.

5. What is the concept of statelessness in Rest?

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

6. What do you empathize by JAX-RS?

Every bit 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 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 back up to create REST clients.

7. What are HTTP Status codes?

These are the standard codes that refer to the predefined condition of the job at the server. Following are the condition codes formats available:

  • 1xx - represents advisory responses
  • 2xx - represents successful responses
  • 3xx - represents redirects
  • 4xx - represents client errors
  • 5xx - represents server errors

Virtually normally used status codes are:

  • 200 - success/OK
  • 201 - CREATED - used in Post or PUT methods.
  • 304 - NOT MODIFIED - used in provisional Get requests to reduce the bandwidth utilize of the network. Here, the torso of the response sent should be empty.
  • 400 - BAD Asking - This can be due to validation errors or missing input data.
  • 401- UNAUTHORIZED - This is returned when there is no valid hallmark credentials sent along with the request.
  • 403 - FORBIDDEN - sent when the user does not have access (or is forbidden) to the resource.
  • 404 - Not FOUND - Resource method is non available.
  • 500 - INTERNAL SERVER ERROR - server threw some exceptions while running the method.
  • 502 - BAD GATEWAY - Server was not able to go the response from another upstream server.

8. What are the HTTP Methods?

HTTP Methods are likewise known as HTTP Verbs. They form a major portion of uniform interface restriction followed by the REST that specifies what activity 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.
  • Postal service: This method is used for the creation of new resources on the server.
  • PUT: This method is used to update the quondam/existing resource on the server or to supercede the resources.
  • DELETE: This method is used to delete the resources on the server.
  • PATCH: This is used for modifying the resources on the server.
  • OPTIONS: This fetches the list of supported options of resources present on the server.

The Mail service, Become, PUT, DELETE corresponds to the create, read, update, delete operations which are most unremarkably called Grime Operations.

Go, Caput, OPTIONS are safe and idempotent methods whereas PUT and DELETE methods are only idempotent. Mail service and PATCH methods are neither safe nor idempotent.

ix. Can you tell the disadvantages of RESTful web services?

The disadvantages are:

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

x. Define Messaging in terms of RESTful web services.

The technique of sending a bulletin from the Balance client to the REST server in the form of an HTTP request and the server responding back with the response every bit HTTP Response is called Messaging. The messages independent institute the data and the metadata most the message.

REST API Experienced Interview Questions

xi. Differentiate betwixt Soap and REST?

Soap REST
Soap - Simple Object Access Protocol Balance - Representational Land Transfer
Lather is a protocol used to implement web services. Residue is an architectural design pattern for developing web services
SOAP cannot employ Rest every bit information technology is a protocol. REST architecture can have SOAP protocol as part of the implementation.
Lather specifies standards that are meant to be followed strictly. REST defines standards merely they need not be strictly followed.
SOAP customer is more tightly coupled to the server which is like to desktop applications having strict contracts. The Residuum client is more than flexible like a browser and does not depend on how the server is developed unless information technology follows the protocols required for establishing advice.
Lather supports only XML transmission betwixt the client and the server. REST supports data of multiple formats like XML, JSON, MIME, Text, etc.
Soap reads are not cacheable. REST read requests can be cached.
SOAP uses service interfaces for exposing the resource logic. Residual uses URI to expose the resource logic.
Soap is slower. REST is faster.
Since Lather is a protocol, it defines its ain security measures. REST simply inherits the security measures based on what protocol it uses for the implementation.
SOAP is non commonly preferred, merely they are used in cases which require stateful information transfer and more than reliability. REST is commonly preferred by developers these days as it provides more scalability and maintainability.

12. While creating URI for web services, what are the all-time practices that needs to be followed?

Below is the listing of all-time practices that need to be considered with designing URI for web services:

  • While defining resources, use plural nouns. Example: To place user resource, utilize the proper name "users" for that resource.
  • While using the long proper noun for resources, use underscore or hyphen. Avoid using spaces between words. For case, to define authorized users resources, 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 information technology gets published. When the URI is updated, the older URI must be redirected to the new ane using the HTTP status code 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 get user details of a particular ID, employ /users/{id} instead of /getUser
  • Use the technique of forward slashing to bespeak the bureaucracy between the resource and the collections. Example: To get the address of the user of a detail id, we can use: /users/{id}/address

13. What are the all-time practices to develop RESTful web services?

RESTful web services use REST API as means of implementation using the HTTP protocol. Residual API is naught but an awarding programming interface that follows Remainder architectural constraints such as statelessness, cacheability, maintainability, and scalability. Information technology has get very pop among the programmer community due to its simplicity. Hence, it is very important to develop prophylactic and secure REST APIs that follow good conventions. Beneath are some best practices for developing Residual APIs:

  • Since REST supports multiple information formats, it is however good exercise to develop REST APIs that accept and responds with JSON data format whenever possible. This is because a majority of the client and server technologies have 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 data format, the response header should have Content-Type prepare to equally application/JSON, this is because sure 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-Blazon must be set to awarding/JSON on the asking header.
  • While naming the resource endpoints, ensure to apply plural nouns and not verbs. The API endpoints should exist clear, brief, like shooting fish in a barrel to empathise, and informative. Using verbs in the resource name doesn't contribute much data because an HTTP asking already has what the request is doing in its HTTP method/verb. An advisable HTTP verb should exist used to correspond the chore of the API endpoint.
    • Below are the most commonly used HTTP methods to define the verb:
      • Get - indicates get/call back the resource data
      • Post - indicates create new resources data
      • PUT - indicates update the existing resource data
      • DELETE - indicates remove the resources data
  • To represent the hierarchy of resources, use the nesting in the naming convention of the endpoints. In example, you lot want to call back data of 1 object residing in another object, the endpoint should reverberate this to communicate what is happening. For example, to get the address of an author, we tin can use the GET method for the URI /authors/:id/address'
    • Please ensure in that location are no more than 2 or 3 levels of nesting every bit the proper name of the URI can become too long and unwieldy.
  • Fault Handling should be done gracefully by returning advisable mistake codes the application has encountered. Balance has defined standard HTTP Status codes that can exist sent along with the response based on the scenario.
    • Error codes should as well be accompanied by appropriate fault messages that can help the developers to accept corrective actions. Yet, the message should non be too elaborate as well which can help the hacker to hack your application.
    • Mutual status codes are:
      • 400 - Bad Request – client-side error - failed input validation.
      • 401 - Unauthorized – The user is non authenticated and hence does not have authority to access the resource.
      • 403 - Forbidden – User is authenticated but is not authorized to access the resource.
      • 404 - Non Found – The resource is not constitute.
      • 500 - Internal server error – This is a very generic server-side fault that is thrown when the server goes down. This shouldn't exist returned past 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 resource. This is because returning huge data all at once can wearisome down the system and reduce the application performance. Hence, filter some items reduces the information to some extent. Pagination of data is done to ensure but some results are sent at a fourth dimension. Doing this can increment the server performance and reduce the brunt of the server resources.
  • Proficient security practices are a must while developing REST APIs. The client-server communication must exist private due to the nature of data sensitivity. Hence, incorporating SSL/TLS becomes the well-nigh important pace while developing APIs equally they facilitate establishing secure communication. SSL certificates are easier to go and load on the server.
    • Apart from the secure channels, we need to ensure that non everyone should exist able to access the resources. For example, normal users should not admission the data of admins or another user. Hence, role-based admission controls should exist in identify to make sure just the right fix of users can access the correct set of information.
  • Since REST supports the feature of caching, we can utilise this feature to enshroud the data in order to improve the application performance. Caching is done to avoid querying the database for a request repeated times. Caching makes data retrieval fast. Still, intendance must be taken to ensure that the cache has updated data and not outdated ones. Frequent cache update measures need to be incorporated. There are many cache providers like Redis that can assist in caching.
  • API Versioning: Versioning needs to be washed in case nosotros are planning to brand whatsoever changes with the existing endpoints. We do non want to intermission advice 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 tin can be followed. For example, 3.0.ane represents 3rd major version with the outset patch. Usually, in the API endpoints, nosotros ascertain /v1,/v2, etc at the offset of the API path.

14. What are Idempotent methods? How is information technology relevant in RESTful web services domain?

The meaning of idempotent is that even later calling a single request multiple times, the consequence of the request should be the same. While designing REST APIs, we demand to keep in heed to develop idempotent APIs. This is considering the consumers can write client-side lawmaking which tin can result in duplicate requests intentionally or not. Hence, error-tolerant APIs need to be designed and then that they practice not consequence in erroneous responses.

  • Idempotent methods ensure that the responses to a request if called one time or ten times or more than that remain the same. This is equivalent to adding any number with 0.
  • Remainder provides idempotent methods automatically. GET, PUT, DELETE, Head, OPTIONS, and TRACE are the idempotent HTTP methods. Mail is non idempotent.
    • POST is not idempotent because POST APIs are usually used for creating a new resources on the server. While calling Mail methods N times, in that location will be Due north new resource. This does non result in the same outcome at a fourth dimension.
    • Methods like Get, OPTIONS, TRACE, and HEAD are idempotent because they do not modify the land of resources on the server. They are meant for resource retrieval whenever called. They do not consequence in write operations on the server thereby making it idempotent.
    • PUT methods are generally used for updating the state of resources. If you lot call PUT methods N times, the first request updates the resource and the subsequent requests volition be overwriting the same resource again and once again without changing anything. Hence, PUT methods are idempotent.
    • DELETE methods are said to be idempotent because when calling them for North times, the commencement request results in successful deletion (Condition Lawmaking 200), and the adjacent subsequent requests result in nix - Status Code 204. The response is different, but there is no change of resources on the server-side.
      • All the same, if you are attempting to delete the resource nowadays, at last, every fourth dimension y'all hitting the API, such equally the request DELETE /user/last which deletes the last user tape, and then calling the request Northward times would delete Due north resources on the server. This does non make DELETE idempotent. In such cases, as part of good practices, information technology is advisable to apply POST requests.

15. What are the differences between Balance and AJAX?

REST AJAX
REST- Representational State Transfer AJAX - Asynchronous javascript and XML
REST has a URI for accessing resources by means of a request-response pattern. AJAX uses XMLHttpRequest object to send requests to the server and the response is interpreted by the Javascript code dynamically.
REST is an architectural blueprint for developing client-server communication systems. AJAX is used for dynamic updation of UI without the need to reload the page.
Residue requires the interaction between client and server. AJAX supports asynchronous requests thereby eliminating the necessity of constant client-server interaction.

sixteen. Can you tell what constitutes the core components of HTTP Asking?

In Remainder, any HTTP Request has 5 main components, they are:

  • Method/Verb − This office tells what methods the request performance represents. Methods like GET, PUT, POST, DELETE, etc are some examples.
  • URI − This office is used for uniquely identifying the resource 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 role has the details of the request metadata such as client blazon, the content format supported, message format, cache settings, etc.
  • Asking Body − This part 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 Condition Code − This represents the server response status code for the requested resource. Case- 400 represents a client-side fault, 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 appointment, what is server type, etc.
  • Response Torso − This part contains what is the actual resource/message returned from the server.

18. Define Addressing in terms of RESTful Web Services.

Addressing is the process of locating a single/multiple resources that are nowadays on the server. This job is achieved by making utilise of URI (Compatible Resource Identifier). The general format of URI is

                  <protocol>://<application-proper name>/<type-of-resource>/<id-of-resource>                

19. What are the differences betwixt PUT and Post in REST?

PUT Mail service
PUT methods are used to asking the server to store the enclosed entity in request. In case, the request does non be, and then new resource has to be created. If the resource exists, and so the resource should get updated. POST method is used to asking the server to shop the enclosed entity in the asking every bit a new resources.
The URI should have a resource identifier. Example: PUT /users/{user-id} The Mail service URI should indicate the collection of the resource. Example: POST /users
PUT methods are idempotent. Mail methods are not idempotent.
PUT is used when the customer wants to alter a single resource that is part of the collection. If a office of the resources has to be updated, so PATCH needs to be used. Postal service methods are used to add together a new resource to the drove.
The responses are not cached hither despite the idempotency. Responses are non cacheable unless the response explicitly specifies Cache-Control fields in the header.
In general, PUT is used for UPDATE operations. Postal service is used for CREATE operations.

20. What makes REST services to exist hands scalable?

Rest services follow the concept of statelessness which essentially ways no storing of whatever data across the requests on the server. This makes information technology easier to scale horizontally because the servers need not communicate much with each other while serving requests.

21. Based on what factors, y'all can make up one's mind which type of spider web services you lot need to employ - SOAP or Residue?

REST services have gained popularity due to the nature of simplicity, scalability, faster speed, improved functioning, and multiple data format back up. But, SOAP has its ain advantages as well. Developers use SOAP where the services require advanced security and reliability.

Following are the questions you need to ask to aid you decide which service can be used:

  • Do yous want to betrayal resource information or business logic?
    • Lather is ordinarily used for exposing business logic and REST for exposing data.
  • Does the client 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 yes, Balance supports multiple information formats which is why it is preferred in this case.
  • Does your service require AJAX call support?
    • If yes, REST tin be used as it provides the XMLHttpRequest.
  • Does your service require both synchronous and asynchronous requests?
    • SOAP has support for both sync/async operations.
    • Residuum merely supports synchronous calls.
  • Does your service require statelessness?
    • If yep, REST is suitable. If no, SOAP is preferred.
  • Does your service crave a high-security level?
    • If aye, SOAP is preferred. Residuum inherits the security property based on the underlying implementation of the protocol. Hence, it tin can't be preferred at all times.
  • Does your service require support for transactions?
    • If yes, Lather is preferred as information technology is proficient in providing avant-garde support for transaction management.
  • What is the bandwidth/resource required?
    • Lather involves a lot of overhead while sending and receiving XML information, hence information technology consumes a lot of bandwidth.
    • Residue makes utilize of less bandwidth for data transmission.
  • Do y'all want services that are easy to develop, test, and maintain frequently?
    • REST is known for simplicity, hence it is preferred.

22. We can develop webservices using web sockets too every bit REST. What are the differences between these two?

REST Web Socket
REST follows stateless architecture, pregnant it won't store any session-based data. Web Socket APIs follow the stateful protocol as information technology necessitates session-based data storage.
The mode of advice is uni-directional. At a fourth dimension, only the server or the customer will communicate. The communication is bi-directional, communication tin be done by both client or server at a time.
REST is based on the Request-Response Model. Spider web Socket follows the total-duplex model.
Every request will have sections like header, title, body, URL, etc. Spider web sockets do not have whatsoever overhead and hence suited for real-time communication.
For every HTTP request, a new TCP connection is gear up. There volition be just ane TCP connexion so the client and server can beginning communicating.
Remainder web services support both vertical and horizontal scaling. Web socket-based services only support vertical scaling.
Residual depends on HTTP methods to get the response. Web Sockets depend on the IP address and port number of the organization to become a response.
Communication is slower here. Message transmission happens very faster than Residual API.
Memory/Buffers are not needed to store information hither. Memory is required to shop data.

The request period difference between the REST and Spider web Socket is shown below:

23. Can we implement transport layer security (TLS) in REST?

Yes, we can. TLS does the task of encrypting the communication betwixt the REST client and the server and provides the means to authenticate the server to the client. It is used for secure communication equally it is the successor of the Secure Socket Layer (SSL). HTTPS works well with both TLS and SSL thereby making information technology constructive while implementing RESTful web services. One point to mention hither is, the Balance inherits the property of the protocol information technology implements. And so security measures are dependent on the protocol REST implements.

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

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

25. What is Payload in terms of RESTful web services?

Payload refers to the data passes in the asking body. It is not the aforementioned equally the request parameters. The payload tin can exist sent only in Postal service methods every bit part of the asking body.

26. Is information technology possible to send payload in the Get and DELETE methods?

No, the payload is non the same every bit the request parameters. Hence, information technology is not possible to transport payload data in these methods.

27. How can you test RESTful Spider web Services?

RESTful spider web services tin exist tested using diverse 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 asking parameters like headers, query parameters, and likewise the response headers. Swagger also provides similar features like Postman and it provides the facility of documentation of the endpoints too. We tin can also use tools similar Jmeter for performance and load testing of APIs.

28. What is the maximum payload size that tin can exist sent in Postal service methods?

Theoretically, there is no brake on the size of the payload that can exist 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 operation.

29. How does HTTP Basic Hallmark piece of work?

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

30. What is the difference between idempotent and rubber HTTP methods?

  • Safe methods are those that do not modify any resources internally. These methods can exist cached and tin be retrieved without any effects on the resource.
  • Idempotent methods are those methods that do not change the responses to the resources externally. They tin can be called multiple times without any modify in the responses.

According to restcookbook.com, the following is the table that describes what methods are idempotent and what is safety.

HTTP Methods Idempotent Safe
OPTIONS yeah yeah
Become yes yeah
Head yes yes
PUT yep no
POST no no
DELETE yes no
PATCH no no

JAX-RS Interview Questions

31. What are the key features provided past JAX-RS API in Java EE?

JAX-RS stands for Java API for RESTful Web services. They are zilch just a set of Java-based APIs that are provided in the Java EE which is useful in the implementation and evolution of RESTful web services.

Features of JAX-RS are:

  • POJO-based: The APIs in the JAX-RS is based on a sure set of annotations, classes, and interfaces that are used with POJO (Plain Old Java Object) to betrayal the services as spider web services.
  • HTTP-based: The JAX-RS APIs are designed using HTTP as their base protocol. They back up the HTTP usage patterns and they provide the corresponding mapping between the HTTP actions 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 trunk content.
  • Container Independent: The APIs can exist deployed in the Java EE container or a servlet container such equally Tomcat or they can as well be plugged into JAX-WS (Java API for XML-based web services) providers.

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

  • A resources 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, @Become, @Postal service, @DELETE, @PUT, etc.

Case:

                                      import                    javax.ws.rs.Path;                    /** * InterviewBitService is a root resource grade that is exposed at 'resource_service' path */                    @Path('resource_service')                    public                                          grade                      InterviewBitService                    {                    // Divers methods                    }                

33. What do y'all understand past asking 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 desire to brand. They are @Get, @Mail, @PUT, @DELETE, @Head.

Usage Instance:

                                      import                    javax.ws.rs.Path;                    /** * InterviewBitService is a root resource class that is exposed at 'resource_service' path */                    @Path('resource_service')                    public                                          grade                      InterviewBitService                    {                    @GET                                          public                      String                      getRESTQuestions                      ()                    {                    // some operations                    }  }                

34. How can the JAX-RS applications be configured?

JAX-RS applications accept the root resource classes packaged in a war file. At that place are two means of configuring JAX-RS applications.

  1. Use @ApplicationPath note in a subclass of javax.ws.rs.core.Application that is packaged in the WAR file.
  2. Use the <servlet-mapping> tag within the web.xml of the WAR. web.xml is the deployment descriptor of the awarding where the mappings to the servlets can be defined.

35. 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 amalgam customer requests that need to exist executed asynchronously. Invoking a request asynchronously does the chore of returning the control to the caller by returning with datatype java.util.concurrent.Future whose blazon is ready to render the service telephone call blazon. Hereafter objects are used because they have the required methods to cheque whether the asynchronous calls have been completed and if yep, then call back the responses. They also provide the flexibility to abolish the request invocations and also check if the cancellation has been successful.

Let us understand this with the help of a random example. Nosotros know that the Future interface from the java.util.concurrent has the below functions bachelor:

                                      package                    java.util.concurrent;                    public                                          interface                      Time to come<V>                    {                    // informs the executor to stop the thread execution                                          boolean                      cancel                      (boolean                        mayInterruptIfRunning)                    ;                    // indicates whether the Future was cancelled or not                                          boolean                      isCancelled                      ()                    ;                    // indicates if the executor has completed the task                                          boolean                      isDone                      ()                    ;                    // gets the actual result from the procedure.                                        // This blocks the plan execution until the result is prepare.                    V                      become                      ()                      throws                      InterruptedException, ExecutionException;                    // besides gets actual result from the process but information technology throws                                        // the TimeoutException in case the result is not obtained before specified timeout                    5                      get                      (long                        timeout, TimeUnit unit of measurement)                      throws                      InterruptedException, ExecutionException, TimeoutException; }                

Let united states consider we take this function below which is used for processing 2 Ids parallelly.

                                                            public                      void                      processIds                      (String userId1, Cord questionId)                    {    Client customer = ClientBuilder.newClient();    Future<Response> futureResponse1 = client.target("http://interviewbitserver.com/users/"+userId).request().async().become();    Futurity<Order> futureResponse2 = client.target("http://interviewbitserver.com/questions/"+questionId).request().async().get(Question.class);                    // block the procedure until complete                    Response response1 = futureResponse1.get();    User userObject = response1.readEntity(User.class);                    //Do processing of userObject                    // Look for 2 seconds before fetching record                    endeavor                    {       Question question = futureResponse2.get(2, TimeUnit.SECONDS);                    //Practice Processing of question                    }                    take hold of                    (TimeoutException timeoutException ) {                    //handle exceptions                    }                    render; }                

In the above example, nosotros see that in that location are 2 separate requests getting executed parallelly. For the first future object, nosotros expect the javax.ws.rs.cadre.Response indefinitely using the become() method until nosotros get the response. For the second hereafter object, we await for the response merely for 2 seconds and if we do non go within 2 seconds, then the get() method throws TimeoutException. Nosotros can also use the isDone() method or isCancelled() method to observe out whether the executors have completed or cancelled.

36. List the central 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 Go requests. They procedure Get requests.
  • @Postal service - 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 respective to the HTTP DELETE requests. They procedure DELETE requests.
  • @Caput - This is a request method designator which is corresponding to the HTTP Caput requests. They process Head requests.
  • @PathParam - This is the URI path parameter that helps developers to extract the parameters from the URI and apply them in the resource class/methods.
  • @QueryParam - This is the URI query parameter that helps developers extract the query parameters from the URI and employ them in the resource class/methods.
  • @Produces - This specifies what MIME media types of the resource 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 customer.

Spring RESTful Web Services Interview Questions

37. Define RestTemplate in Spring.

The RestTemplate is the main course meant for the client-side access for Bound-based RESTful services. The advice 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, asking/response types, request object, etc every bit part of arguments.

  • Commonly used annotations like @GetMapping, @PostMapping, @PutMapping, etc are provided by this class from Spring 4.3. Prior to that, Leap provided (and still provides) @RequestMapping annotation to point what methods were beingness used.

38. 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 asking routing is handled by Dispatcher Servlet. When it gets the asking, information technology 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 alleged within the controller classes and their methods.

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

@Controller @RestController
Mostly used traditional Bound MVC service. Represents RESTful web service in Leap.
It is mostly used in Spring MVC service where model data needs to rendered using view. Information technology is used in case of RESTful web service that returns object values bound to response body.
If response values need to be converted through HttpMessageConverters and sent via response object, extra notation @ResponseBody needs to be used on the grade 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.

twoscore. What does the annotation @PathVariable do?

@PathVariable annotation is used for passing the parameter with the URL that is required to go the information. Spring MVC provides back up for URL customization for data retrieval using @PathVariable annotation.

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

Yeah. Spring MVC needs to be on the classpath of the application while developing RESTful spider web services using Jump. This is because, the Leap 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.

42. Define HttpMessageConverter in terms of Bound Residuum?

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

Determination

43. Conclusion

We take seen what are the most commonly asked questions on RESTful web services during an interview. REST APIs have become a very important tool in the software manufacture. Developing RESTful web services that are scalable and easily maintainable is considered an art. As the industry trends increase, the Balance compages would get more physical and the demand for developers who know the development of RESTful spider web services would increment steadily.

References:

To larn more about REST, yous can refer to the beneath two links:
https://restcookbook.com/
https://www.restapitutorial.com/

REST API MCQ

How You Will Develop A Rest Web Service End To End Interview,

Source: https://www.interviewbit.com/rest-api-interview-questions/

Posted by: heathhichit.blogspot.com

0 Response to "How You Will Develop A Rest Web Service End To End Interview"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel