Java interview questions on spring boot rest API

1. REST

REST is an architectural style for networked applications with the following constraints:

  • Client-Server: Separates clients and servers for scalability.
  • Stateless: No client context is stored on the server between requests.
  • Cacheable: Responses must be cacheable for efficiency.
  • Uniform Interface: Standardized URIs, HTTP methods, and resource representations.
  • Layered System: Components operate independently in layers.
  • Code on Demand (optional): Allows downloading and executing code.

A common misconception is that REST is a software model, whereas it is an architectural style.

2. HTTP Methods

  • GET (Read)
  • POST (Create)
  • PUT (Replace)
  • DELETE (Remove)
  • PATCH (Partial update) → Used for updating specific fields rather than the whole object.

3. Idempotency

  • Idempotent methods: GET, PUT, DELETE (multiple requests result in the same outcome).
  • Non-idempotent methods: POST, PATCH (can cause changes with each request).
  • Example: PUT prevents duplicate side effects like charging a user twice for a service.

JAX-RS Annotations

4. Annotations

  • @Path("/resource") → Defines the URI path.
  • @GET, @POST → HTTP methods.
  • @Produces(MediaType.APPLICATION_JSON) → Specifies response format.
  • @Consumes(MediaType.APPLICATION_JSON) → Specifies request format.

5. Parameters

  • @PathParam → Extracts URL path segment (/users/{id} → id).
  • @QueryParam → Extracts URL query parameter (/users?name=John → name).
  • @FormParam → Extracts HTML form data.
  • @HeaderParam → Extracts HTTP header values.

6. Request Body

  • Use @RequestBody (Spring) or JAX-RS to deserialize JSON/XML into a Java object (e.g., User user).

Status Codes & Error Handling

7. Status Codes

  • 201 Created → Resource successfully created.
  • 400 Bad Request → Invalid input from the client.
  • 401 Unauthorized → Missing or failed authentication.
  • 404 Not Found → Resource does not exist.

8. Exception Handling

Create global exception handlers in @ControllerAdvice (Spring) to return standardized error responses:

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity handleNotFound() { ... }

Advanced Topics

9. HATEOAS

Hypermedia links guide clients in navigating resources.

Example:

{
  "order": { "id": 1 },
  "_links": {
    "self": "/orders/1",
    "payment": "/orders/1/payment"
  }
}

10. Pagination

Use page, size, and sort parameters. Returns a Spring Data Page with metadata:

@GetMapping("/users")
public Page<User> getUsers(Pageable pageable) { ... }

11. Caching

  • ETag → Helps check if content has changed.
  • Cache-Control → Example: max-age=3600 (cache for 1 hour).
  • Spring: Use @Cacheable or ResponseEntity with headers.

12. Security

Use Spring Security with OAuth2/JWT.

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter { ... }

13. Versioning

  • URI-based: /v1/users (simpler but less RESTful).
  • Header-based: Accept: application/vnd.myapi.v1+json (cleaner URIs).

Frameworks & Tools

14. Spring Boot Controller

@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping
    public List<User> getUsers() { ... }
}

15. Testing

Use @SpringBootTest with TestRestTemplate or MockMvc:

mockMvc.perform(get("/users")).andExpect(status().isOk());

16. OpenAPI/Swagger

Add springdoc-openapi dependency in your build file. Annotate endpoints with @Operation and @ApiResponse.

Scenario-Based Answers

17. Library API Design

  • Resources: Book, Member
  • Endpoints:
    • GET /books → List books
    • POST /books → Add a new book (201 Created)
    • PUT /books/{id} → Update a book (200 OK)
    • DELETE /books/{id}→ Remove a book

18. 415 Error - Unsupported Media Type

Occurs when the client sends data in a format not specified in @Consumes. Example: The server expects JSON but the client sends XML.

19. Idempotent Payments

Use a unique client-generated header idempotency-key. The server checks if the key has been processed before to prevent duplicate payments.

20. Rate Limiting

Use Bucket4j with Spring Interceptors to limit requests per IP.


Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu