Showing posts with label HTTP methods. Show all posts
Showing posts with label HTTP methods. Show all posts

Thursday, 18 July 2019

REST API interview Questions


In this post, I'm going to share REST API interview questions actually asked in I.T. companies.

Question 1:

What exactly is RESTful programming?


Answer:
 
REST stands for Representational State Transfer. It is an architectural style for designing distributed systems, particularly web services.

RESTful services generally use HTTP as their communication protocol.  They expose resources through URLs and use standard HTTP methods to perform operations on those resources.

The commonly used HTTP methods are:

HTTP Method                         purpose                                          Example
GET                                    Retrieve a resource                           Get user details
POST                                Create a resource or submit data        Create a new user
PUT                                  Replace a resource completely           Replace user details
PATCH                             Partially modify a resource                 Update user's first name
DELETE                          Delete a resource                                     Delete a user


Important REST principles:

  1. Client server architecture: The client and server have separate responsibilities. The client handles the user interface, while the server manages application data and business logic.
  2. Stateless Communication: Each request should contain the information required to process it. The server should not depend on stored client-session context to understand a request.
  3. Cachability: Responses should indicate whether they can be cached.
  4. Uniform interface: Resources are identified through URI's and accessed through a consistent interface.
  5. Layered System: A client does not necessarily know whether it communicates directly with the application server.



Programmatic Explanation:

Create a user with three properties:

POST /user
fname=Johnny&lname=Joe&age=30

The server responds:
200 OK
location: /user/321

Now, we can retrieve the user information:

GET /user/321

The server responds:

200 OK
<fname>johnny</fname><lname>Joe</lname><age>30</age>

To modify the record (age and lname will remain unchanged)

PATCH /user/321
fname=john


To update the record (lname and age will become NULL)

PUT /user/321
fname=john


Question 2:

What is the difference between REST Endpoints and REST resources?


Answer:

A REST resource represents an entity or concept that an API makes available to clients. Example include users, books, orders and products.

A resource is identified by a URI (Uniform Resource Identifier).
An endpoint is commonly understood as the API address and HTTP method through which a particular operation can be performed.

In simple terms:
Resource: What data or entity are we working with?
Endpoint: Where and how can we access or operate on it?

Example 1: User Resource
GET /api/users/321

Here:
Resource: User with ID 321.
Endpoint: GET /api/users/321
HTTP method: GET

The server returns the representation of the  requested user.

Example 2: Book Resource
GET /api/v2/books/4321

Here:

Resource: Book with ID 4321
Endpoint: GET /api/v2/books/4321

API version: V2.
The server returns information about the requested book.

Can multiple endpoints access the same resource?
Yes.

For example:
GET /api/users/321
PUT /api/users/321
PATCH /api/users/321
DELETE /api/users/321

All these operations target the same user resource, but each uses a different HTTP method and performs a different operation.
Therefore a resource and an endpoint are related concepts, but they are not the same thing. 


Question 3:

What is the most popular way to present a resource in REST?


Answer:

JSON(JavaScript Object Notation) and XML (Extensible Markup Language)  are two commonly used formats for representing REST resources.

1. JSON representation
JSON is lightweight , easy to read and widely used in modern web applications and microservices.

Example:
{
    "id": 321,
    "fname": "John",
    "lname": "Joe",
    "age": 30 

} 

2. XML representation

XML uses tags to represent structured information.

Example:
<user>
    <id>321</id>
    <fname>John</fname>
    <lname>Joe</lname>
    <age>30</age>

</user>

JSON is generally preferred in modern REST APIs because it is relatively compact and convenient to process in many programming languages.

The response format can be negotiated using HTTP headers such as Accept and Content-Type.

 


Question 4:

What are the core components of an HTTP request?


Answer:

An HTTP request contains the following major components:
  1. HTTP method
  2. Request URI  or request target
  3. HTTP version
  4. Request headers
  5. Request body (optional)

Let's understand each component.

1. HTTP Method
The method specifies the intended operation.
Examples: GET, POST, PUT, DELETE, PATCH

2. Request URI
The URI identifies the resource being accessed.

Example:
/api/users/321

3. HTTP version
It indicates the HTTP protocol version being used, such as HTTP/1.1 or HTTP/2.

4. Request Headers
Headers carry additional information about the request.

Examples:
Content-Type: application/json
Accept: application/json
Authorization: Bearer Token

5. Request Body
The body contains data sent to the server. It is commonly used with POST, PUT and PATCH requests.

Example:

{
    "fname": "John",
    "lname": "Joe",
    "age": 30
}

Example: HTTP/1.1 request:

POST /api/users HTTP/1.1
Host: example.com
Content-Type: application/json
Accept: application/json

{
    "fname": "John",
    "lname": "Joe",
    "age": 30
}



Question 5:

What are the core components of an HTTP response?

Answer:

An HTTP response includes 4 key elements:

  • Status/Response code: indicates server status for the resource present in HTTP request. e.g. 404 means "resource not found"  and 200 means , "response is OK".
  • HTTP Version
  • Response Header: contains metadata for HTTP response
  • Response Body: Indicates response message content

Question 6:

What is the difference between PUT and POST operations?

Answer:

                    PUT                                                                                        POST

PUT is used for update operation                                    POST is used for create operation

PUT method is idempotent                                              POST is not idempotent

Use PUT when you want to modify a singular                Use POST when you want to add a
resource which is already a part of resources                   child resource under resources
collection. PUT replaces the resource in its                      collection
entirety. Use PATCH if request updates part
of the resource.                            
                                                                                          
PUT is idempotent, so you can cache the                         Responses to this method are not
response                                                                             cacheable, unless the response
                                                                                          includes appropriate  Cache-Control
                                                                                          fields.

Generally, always use PUT for update                             Always use POST for create
operations.                                                                         operations.


Question 7:

What are the tools available for testing Web services?


Answer:
  • SOAP UI tool
  • Poster for Firefox Browser
  • The Postman extension for Chrome.

Question 8:

Which Java API helps in developing a RESTful Web Service?


Answer:

Java developers can use several APIs and frameworks to build RESTful web services.

1. Jakarta RESTful web services (JAX-RS)

JAX-RS , originally known as Java API for RESTful Web services, is a standard Java API for developing RESTful web services.

It provides annotations that simplify REST API development.

for example:

@Path("/users")
public class UserResource{

    @GET
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public User getUser(@PathParam("id") int id){
        return userService.getUser(id);
    }

}

Here:
@Path defined the resource URI.
@GET specifies the HTTP method.
@PathParam extracts a value from the URI.
@Produces specifies the response format.

JAX-RS implementations include:

  • Jersey
  • RESTEasy
  • Apache CXF

2. Spring Boot with Spring MVC

Spring boot is another widely used approach for developing Rest APIs in java.
Spring MVC provides annotations such as @RestController, @GetMapping, @PostMapping, @PutMapping and @DeleteMapping.

Example:

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping("/{id}")
    public User getUser(@PathVariable int id) {
        return userService.getUser(id);
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }
}


Spring boot simplifies application configuration, dependency management and deployment.

Which one should you choose?

Use Jakarta RESTful Web Services when you want to build services using the standard JAX-RS API and one of its implementations.

Use Spring Boot with Spring MVC when building applications within the spring ecosystem.


 If you liked this post, then Hit 'LIKE' button.