Spring BootREST APIsbeginner
Updated:

Spring Boot REST API Interview Questions and Answers

9 min read

Building a REST endpoint is easy; explaining status codes, validation and exception handling is what interviews test. Here are the 13 REST API questions with code and traps.

TL;DR – Quick Answer

Spring Boot REST API interviews test the whole request lifecycle: mapping URLs and HTTP verbs, binding path variables and request bodies, returning correct status codes with ResponseEntity, validating input, handling exceptions globally with @ControllerAdvice, and designing clean resource URIs. Interviewers want to see you return the right status code and never leak entities or stack traces to clients.

On This Page

Anyone can annotate a method with @GetMapping and return a list. A REST API interview finds out whether you understand the parts that separate a toy endpoint from a real service: correct status codes, input validation, consistent error responses, and a contract that does not leak your database. This set covers the thirteen REST questions asked most in Spring Boot rounds, each with a fast answer, working code, and the follow-up trap.

Why interviewers ask about REST APIs in Spring Boot

REST endpoints are the surface every Spring Boot developer works on daily, so this is where interviewers check practical judgement rather than trivia. The wrong status code or a leaked entity in your answer tells them exactly how much production code you have actually shipped.

The questions also probe HTTP fundamentals, not just Spring syntax. Idempotency, status-code semantics and resource design are protocol-level knowledge that a good backend developer must have regardless of framework. Spring is just how you express it.

How to answer in an interview

Answer every REST question in terms of the request lifecycle: how the request is mapped, how input is bound and validated, what is returned, and what status code accompanies it. A complete answer names the status code — "on create I return 201 Created with a Location header" beats "I return the object."

Show that you separate the API contract from the persistence layer. Mentioning DTOs, validation and @ControllerAdvice unprompted signals real experience. If any concept is rusty, work through the REST API with Spring Boot tutorial first.

Q1. What makes an API RESTful?

REST is an architectural style: resources identified by URIs, manipulated through standard HTTP methods, communicated in a representation like JSON, and stateless — each request carries everything the server needs. Following those constraints, not using JSON alone, makes an API RESTful.

The constraints interviewers listen for are statelessness, resource-based URIs (nouns, not verbs), and correct use of HTTP methods and status codes. A "REST" API that tunnels everything through POST /doSomething is REST in name only.

Interview note: Follow-up: "is your API stateless if you use HTTP sessions?" Not strictly — server-side session state breaks the stateless constraint. Token-based auth keeps state on the client and preserves it.

Q2. How do you map HTTP methods to controller methods?

Each verb has a mapping annotation: @GetMapping to read, @PostMapping to create, @PutMapping to replace, @PatchMapping to partially update, @DeleteMapping to remove. @RequestMapping sets a shared base path at class level.

@RestController
@RequestMapping("/api/orders")
public class OrderController {
    @GetMapping("/{id}")   public Order get(@PathVariable Long id) { ... }
    @PostMapping           public Order create(@RequestBody OrderDto dto) { ... }
    @DeleteMapping("/{id}") public void delete(@PathVariable Long id) { ... }
}

The judgement being tested is semantic correctness: reads on GET, creation on POST. Using GET to change data is a classic mistake because GET is meant to be safe and cacheable.

Interview note: Trap: "difference between PUT and PATCH?" PUT replaces the whole resource (idempotent); PATCH applies a partial change. Sending half an object with PUT can wipe the omitted fields.

Q3. What is ResponseEntity and when should you use it?

ResponseEntity<T> lets you control the full HTTP response — status code, headers and body — instead of returning only a body with an implicit 200. Use it whenever the status or headers vary, such as returning 201 on create or 404 when nothing is found.

@PostMapping
public ResponseEntity<Order> create(@RequestBody OrderDto dto) {
    Order saved = service.create(dto);
    return ResponseEntity
        .created(URI.create("/api/orders/" + saved.getId()))  // 201 + Location
        .body(saved);
}

Returning a plain object is fine when 200 is always correct, but ResponseEntity is what you reach for the moment status codes matter.

Interview note: Follow-up: "how do you return 404 for a missing resource?" ResponseEntity.notFound().build(), or throw an exception that a @ControllerAdvice maps to 404 — the cleaner approach at scale.

Q4. Which status codes should a REST API use and when?

200 OK for a successful read or update, 201 Created for a successful POST, 204 No Content for a successful delete, 400 for bad input, 401/403 for auth, 404 for a missing resource, 409 for a conflict, and 500 for server errors.

The family logic matters more than memorising each: 2xx success, 4xx the client's fault, 5xx the server's fault. Returning 200 for everything — including errors buried in the body — is the anti-pattern interviewers hunt for.

Interview note: Trap: "you validated input and it failed — 400 or 422?" Either is defensible; 400 is the common Spring default via validation, 422 is more precise for semantically invalid but well-formed input. Justify your choice.

Q5. How do you bind path variables, query params and the request body?

@PathVariable reads a segment of the URI, @RequestParam reads a query-string parameter, and @RequestBody deserialises the JSON body into an object via Jackson.

@GetMapping("/{id}/items")
public List<Item> items(@PathVariable Long id,
                        @RequestParam(defaultValue = "10") int limit) { ... }

Path variables identify the resource; query params filter or paginate; the body carries the payload for writes. Matching each to its correct source is a frequent hands-on check.

Interview note: Follow-up: "how do you make a query param optional with a default?" @RequestParam(required = false) or defaultValue = "...". Without it, a missing param yields a 400.

Q6. How do you validate incoming request data?

Put Bean Validation annotations (@NotNull, @Email, @Size) on the DTO fields and add @Valid before the @RequestBody parameter. Spring validates before the method runs and raises MethodArgumentNotValidException on failure.

public record OrderDto(@NotBlank String product,
                       @Min(1) int quantity) {}

@PostMapping
public Order create(@Valid @RequestBody OrderDto dto) { ... }

The important detail is that validation belongs on the DTO, keeping the controller clean, and that a failed validation should produce a 400 with a clear message. The request validation guide covers custom validators.

Interview note: Trap: "where do you turn the validation error into a nice JSON response?" In a @ControllerAdvice handler for MethodArgumentNotValidException — otherwise the client gets Spring's default, less friendly body.

Q7. How do you handle exceptions consistently across all controllers?

Use a class annotated @RestControllerAdvice containing @ExceptionHandler methods. Each maps an exception type to a status code and a consistent error body, so error handling lives in one place instead of every controller.

@RestControllerAdvice
public class ApiExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ApiError> notFound(ResourceNotFoundException ex) {
        return ResponseEntity.status(404).body(new ApiError(ex.getMessage()));
    }
}

This is the single most valued answer in the set: centralised, predictable errors that never leak a stack trace. Detail lives in REST exception handling.

Interview note: Follow-up: "difference between @ExceptionHandler in a controller and in @ControllerAdvice?" A controller-local handler only covers that controller; @ControllerAdvice applies globally across all of them.

Q8. Why return a DTO instead of the JPA entity?

A DTO is a dedicated response object you control. Returning entities couples the API to your schema, can leak sensitive fields, and risks LazyInitializationException when Jackson serialises an un-fetched association. A DTO gives a stable, intentional contract.

public record UserDto(Long id, String name) {}   // no password, no lazy relations

Interviewers see entity-returning code as a junior signal. The mapping cost is real but small, and the decoupling pays off the first time the schema changes without the API needing to.

Interview note: Trap: "isn't mapping entity to DTO wasteful?" The cost is trivial next to a leaked password field or an API frozen to your table structure. Tools like MapStruct remove the boilerplate.

Q9. What is idempotency and why does it matter for REST?

An idempotent method yields the same server state whether called once or many times. GET, PUT and DELETE are idempotent; POST is not. It matters because clients, load balancers and gateways retry failed requests, and retrying a non-idempotent call can duplicate data.

The practical consequence: a payment "create" over POST needs an idempotency key so a retry after a timeout does not charge twice. Recognising that retries are inevitable is the mature part of the answer.

Interview note: Follow-up: "is DELETE really idempotent if the second call returns 404?" Yes — idempotency is about resulting state, not the response code. The resource is gone after one or ten calls.

Q10. How do you version a REST API?

Common strategies are URI versioning (/api/v1/orders), header versioning (a custom Accept header or media type), and request-param versioning. URI versioning is the most widely used because it is explicit and easy to route and cache.

Versioning exists because you cannot break existing clients when the contract changes. The trade-off to state: URI versioning is simplest but duplicates paths; media-type versioning is cleaner but harder to test by hand.

Interview note: Trap: "when do you need a new version at all?" Only for breaking changes — removing a field or changing its meaning. Additive changes (a new optional field) do not require a version bump.

Q11. How do you paginate a REST endpoint in Spring Boot?

Accept page and size parameters and use Spring Data's Pageable. The repository returns a Page<T> carrying the content plus total counts, which you expose so clients can navigate large result sets without loading everything.

@GetMapping
public Page<UserDto> list(Pageable pageable) {
    return repo.findAll(pageable).map(this::toDto);   // ?page=0&size=20
}

Returning an unbounded list is the mistake — it does not scale and can exhaust memory. Pagination shows you think about production data volumes.

Interview note: Follow-up: "offset vs cursor pagination?" Offset (page/size) is simple but drifts as data changes and slows on deep pages; cursor/keyset pagination is stable and faster for large datasets.

Q12. How do you secure a REST API at a high level?

Authenticate each stateless request, commonly with a JWT or OAuth2 token in the Authorization header, then authorise with role checks. Use HTTPS, validate all input, and never expose stack traces. Spring Security wires the filter chain that enforces this.

Freshers are not expected to implement OAuth, but should know REST auth is token-based and stateless, unlike a session cookie. Naming HTTPS and input validation shows security is not an afterthought for you.

Interview note: Trap: "why tokens instead of sessions for REST?" Statelessness — a token lets any server instance serve the request without shared session state, which matters behind a load balancer.

Q13. What are common REST API design mistakes?

Verbs in URIs instead of nouns, returning 200 for errors, exposing entities, missing pagination, inconsistent error shapes, and ignoring status codes. Each makes the API harder to consume and signals inexperience.

The cleanest mental checklist: nouns for resources, correct verbs for actions, correct status codes for outcomes, a consistent error body, DTOs for the contract. If you can recite that, you can critique almost any API shown to you.

Interview note: Follow-up: "critique GET /getUserById?id=5." It uses a verb in the path and a query param for an identifier. RESTful form is GET /users/5.

How to prepare

Build one CRUD API end to end — resource URIs, DTOs, @Valid validation, a @RestControllerAdvice, correct status codes via ResponseEntity, and pagination. Then hit it with a REST client and deliberately trigger each error path so you can see the status codes and error bodies your design produces. That hands-on loop is what turns these answers into things you have observed.

Rehearse the status-code map (Q4), the @ControllerAdvice exception pattern (Q7), and the DTO-vs-entity reasoning (Q8) — they are asked in almost every backend round. Then reinforce the annotations behind it all in the Spring Boot annotations set and follow the hands-on Spring Boot REST API tutorial for beginners. Designing clean, well-behaved APIs is a core skill in our Java Full Stack with AI program.

Frequently Asked Questions

What REST topics come up most in Spring Boot interviews?
HTTP methods and idempotency, correct status codes, ResponseEntity versus a plain return type, request validation with @Valid, and centralised exception handling with @ControllerAdvice. Between them these cover the majority of REST questions at fresher and mid levels.
Should I return the entity or a DTO from a REST endpoint?
Return a DTO. Exposing JPA entities couples your API to your database schema, risks leaking fields like passwords, and can trigger lazy-loading serialisation errors. A DTO gives you a stable, intentional contract that you control independently of the tables.
What is the correct status code for a successful POST that creates a resource?
201 Created, ideally with a Location header pointing to the new resource. Returning 200 works but signals less REST maturity. Interviewers often ask this specifically because it separates candidates who have designed APIs from those who have only consumed them.
How do you handle exceptions in a Spring Boot REST API?
Use a @RestControllerAdvice class with @ExceptionHandler methods that map exceptions to consistent error responses and status codes. This keeps error handling out of every controller and gives clients a predictable error body instead of a stack trace.
What is idempotency and which HTTP methods are idempotent?
An idempotent operation produces the same result whether called once or many times. GET, PUT and DELETE are idempotent; POST is not, because repeating it typically creates another resource. This distinction drives safe retry behaviour in clients and gateways.

Want to Build Your Career in Java Full Stack with AI?

Join CodeBegun and train with working industry engineers — Explore the Program

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 15 July 2026 LinkedIn
Chat with us