Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
Chaturmind
← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: Fresher to 2 YearsSpring Boot Essentials
✓ FreeBeginner· 8 min read

REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Building REST APIs, versioning strategies, REST best practices, ResponseEntity, DELETE status codes, Swagger/OpenAPI, embedded servers and how Boot picks one, switching servers, the must-know annotations, and @Component vs @Service/@Repository.

Published September 25, 2026


How to use this lesson

For REST questions, back up each claim with an HTTP detail: the status code, the header, the method semantics. Interviewers also love the annotation list, so know what each annotation does and the one trap attached to it.

Q1. How do you create a REST API in Spring Boot?

Short answer:

  1. Add spring-boot-starter-web.
  2. Create a @RestController, and map methods with @GetMapping, @PostMapping, @PutMapping, @PatchMapping and @DeleteMapping.
  3. Bind input with @PathVariable, @RequestParam and @RequestBody, adding @Valid for validation.
  4. Delegate to a service layer, and return DTOs, or a ResponseEntity with the correct status code.
@RestController
@RequestMapping("/api/v1/products")
class ProductController {
    private final ProductService service;
    ProductController(ProductService service) { this.service = service; }

    @GetMapping
    Page<ProductDto> list(@RequestParam(defaultValue = "0") int page,
                          @RequestParam(defaultValue = "20") int size) {
        return service.list(PageRequest.of(page, size));
    }

    @PostMapping
    ResponseEntity<ProductDto> create(@Valid @RequestBody CreateProductRequest req) {
        ProductDto created = service.create(req);
        return ResponseEntity.created(URI.create("/api/v1/products/" + created.id())).body(created);  // 201 + Location
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    void delete(@PathVariable long id) { service.delete(id); }
}

Key points to cover:

  • Return DTOs, not JPA entities. That avoids leaking internal fields and lazy-loading exceptions, and it decouples the API contract from the database schema.

Learn it in depth → REST Controllers

Q2. What is API versioning, and how can you implement it?

Short answer: Versioning lets you make breaking changes without breaking existing clients. Several versions run side by side while clients migrate. There are four common strategies:

StrategyExampleNotes
URI path/api/v1/ordersMost common; visible, easy to route and cache
Query parameter/api/orders?version=1Simple, but easy to forget
Custom headerX-API-Version: 1Keeps URLs clean; less visible
Media type (content negotiation)Accept: application/vnd.shop.v1+jsonMost "RESTful"; harder to test in a browser

Key points to cover:

  • Version only for breaking changes. Adding optional fields is backwards-compatible.
  • Deprecate old versions with a timeline, for example the Deprecation and Sunset headers.
  • Spring Framework 7 / Boot 4 add first-class API versioning support (@GetMapping(version = "1.1")).

Learn it in depth → API Contract Design

Q3. What are the REST API best practices?

Short answer:

  • Resource-oriented plural nouns (/orders/{id}/items), not verbs.
  • Correct HTTP methods, with their semantics: GET is safe; PUT and DELETE are idempotent.
  • Correct status codes.
  • Stateless requests.
  • Consistent error format (Problem Details).
  • Pagination, filtering and sorting for collections.
  • Versioning.
  • HTTPS everywhere, with authentication (OAuth2/JWT) and input validation.
  • Idempotency keys for retries of POST.
  • Documentation (OpenAPI).

Key points to cover:

  • Status codes worth knowing:
    • 200 OK, 201 Created (with Location), 204 No Content.
    • 400 Bad Request, 401 Unauthorized (not authenticated), 403 Forbidden (not allowed), 404 Not Found, 409 Conflict, 422 Unprocessable Content.
    • 429 Too Many Requests.
    • 500 / 503.

Q4. What is ResponseEntity used for?

Short answer: It represents the whole HTTP response, so you control the status code, headers and body in one return value. For example: 201 with a Location header, 204 with no body, or conditional 304 responses with an ETag.

@GetMapping("/{id}")
ResponseEntity<OrderDto> get(@PathVariable long id) {
    return service.findOptional(id)
            .map(order -> ResponseEntity.ok().eTag(order.version()).body(order))
            .orElse(ResponseEntity.notFound().build());
}

Key points to cover:

  • If you just return an object, the status is 200. Use ResponseEntity (or @ResponseStatus) when you need anything else.

Q5. What status code should a DELETE endpoint return?

Short answer:

  • 204 No Content when the deletion succeeded and there's nothing to return. This is the most common case.
  • 200 OK if you return a body, such as the deleted resource or a status message.
  • 202 Accepted if the deletion is queued asynchronously.
  • For a resource that doesn't exist, 404, although many APIs return 204 anyway, treating DELETE as idempotent: "it's gone either way".

Key points to cover:

  • Whichever you choose, document it, and be consistent across the API.

Q6. What is Swagger?

Short answer: Swagger is the tooling ecosystem around the OpenAPI Specification, the standard, machine-readable description of REST APIs (endpoints, parameters, schemas, authentication). Swagger UI renders that description as interactive documentation, where developers can try the endpoints.

Key points to cover:

  • In Spring Boot 3, use springdoc-openapi (springdoc-openapi-starter-webmvc-ui). It generates the spec at /v3/api-docs, and serves the UI at /swagger-ui.html. Springfox is unmaintained.

Q7. How does Swagger help document APIs?

Short answer: springdoc builds the OpenAPI document from your code: mappings, DTOs, validation annotations. That keeps the documentation in sync with the implementation. The same document can generate client SDKs, drive contract tests, and be imported into API gateways and Postman.

@Operation(summary = "Get an order by id")
@ApiResponse(responseCode = "404", description = "Order not found")
@GetMapping("/{id}")
OrderDto get(@PathVariable long id) { … }

Key points to cover:

  • Disable or protect the Swagger UI in production if the API isn't public (springdoc.swagger-ui.enabled=false).

Q8. Which embedded servers does Spring Boot support, and which is the default?

Short answer: Tomcat (the default, with spring-boot-starter-web), Jetty and Undertow for servlet applications, and Reactor Netty as the default for WebFlux.

Q9. How does Spring Boot decide which embedded server to use if several are on the classpath?

Short answer: It doesn't depend on classpath order. The servlet web-server auto-configuration imports the Tomcat, Jetty and Undertow configurations in that fixed order. Each is guarded by @ConditionalOnClass (is this server present?) and @ConditionalOnMissingBean(ServletWebServerFactory.class). So the first matching one wins: Tomcat if it's present, otherwise Jetty, otherwise Undertow. You can force a choice by defining your own ServletWebServerFactory bean.

Common trap: the popular answer "whichever comes first in the dependency list" is wrong. The priority is fixed by the auto-configuration's import order and conditions.

Q10. How do you replace the default server with a different one?

Short answer: Exclude Tomcat from the web starter, and add the other server's starter:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

Q11. What are the most important Spring Boot annotations?

Short answer: Grouped by purpose:

AnnotationWhat it doesTrap or tip
@SpringBootApplication@SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScanPut it in the root package
@EnableAutoConfigurationTurns on conditional auto-configurationAlready included above
@Configuration / @BeanDeclare beans in Java config@Bean for third-party objects
@ComponentScanWhere to look for componentsDefaults to the class's package and its sub-packages
@Component, @Service, @Repository, @ControllerStereotypes for auto-detected beans@Repository adds exception translation
@RestController@Controller + @ResponseBodyReturns data, not views
@RequestMapping / @GetMapping…Map requests to handler methodsClass-level base path
@PathVariable, @RequestParam, @RequestBody, @ResponseBodyBind request parts and write the response@RequestBody uses Jackson
@AutowiredInject dependenciesUnnecessary on a single constructor
@EnableWebMvcImports Spring MVC's full configurationIn Boot it switches off MVC auto-configuration. Usually don't add it
@EnableAsync + @AsyncRun methods on a task executorSelf-invocation bypasses the proxy
@EnableScheduling + @ScheduledCron, fixed-rate or fixed-delay jobsRuns on every instance; use a lock (ShedLock) in clusters

Learn it in depth → Component Scanning & Configuration

Q12. Can you use @Component instead of @Service and @Repository? Then why use them?

Short answer: Yes. Technically, all three register a bean through component scanning. The specialised stereotypes still matter:

  • @Repository activates persistence exception translation, which turns vendor-specific exceptions (SQLException, Hibernate exceptions) into Spring's DataAccessException hierarchy.
  • @Service and @Repository document the architectural layer. Tools, AOP pointcuts and architecture tests (ArchUnit) can target layers by annotation.

Follow-up questions this topic invites — and their answers

Q: What's the difference between PUT and PATCH? A: PUT replaces the whole resource with the request body, and is idempotent. PATCH applies a partial update, for example with a JSON Merge Patch. It isn't inherently idempotent.

Q: How do you make POST requests safe to retry? A: Accept an Idempotency-Key header, store the key together with the result of the first request, and return the stored result for any repeat. That's essential for payments and order creation.

Q: How do you implement pagination in Spring Boot? A: Accept a Pageable parameter (for example ?page=0&size=20&sort=createdAt,desc), and return a Page<T>, or a trimmed DTO with the content plus page metadata. For very large or fast-changing datasets, prefer cursor (keyset) pagination.

Q: What does @Async need in order to work? A: @EnableAsync, a public method called from another bean (so the call goes through the proxy), and ideally a configured TaskExecutor. Return void or CompletableFuture<T>, and handle exceptions, because they don't reach the caller otherwise.

Previous

Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions

Next

Spring MVC Architecture & DispatcherServlet — Interview Questions

AI Tutor

Lesson: REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.