Scrivio Interview library
CodingFoundations5 min read · updated 12 November 2026

Write a controller with GET /orders/{id} returning JSON and POST /orders accepting JSON and returning 201 with a Location header.

We put @RestController and @RequestMapping("/orders") on the class. GET uses @GetMapping("/{id}") with a @PathVariable and returns the DTO, which Jackson writes as JSON. POST uses @PostMapping with a @Valid @RequestBody request record, creates the order, builds the new resource's URI with ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri(), and returns ResponseEntity.created(location).body(dto), which sends 201 Created with a Location header.

Why this question is asked

This is a small coding question, but it checks several habits at once: separating request and response types, validating input, using the right status code, and telling the client where the new resource lives. Interviewers often ask follow-ups about what happens on invalid input or behind a proxy. In this answer, we will recap what a 201 response with Location means, write the controller piece by piece, test it with MockMvc, and look at the details that trip people up.

1A Quick Recap of 201 Created and Location

When a POST creates a new resource, HTTP says the server should answer 201 Created and include a Location header with the URI of that resource. The client can then GET that URI without knowing how our ids or paths are built. Returning 200 works technically, but it hides the fact that something was created and leaves the client guessing where it is.

In Spring MVC, a plain return value always gets 200. To choose the status and headers, we return ResponseEntity, a wrapper that holds the status, the headers and the body together.

2The Request and Response Types

We start with two records. The request record holds only what the client may send, with Bean Validation constraints. The response record is what we promise to return. Neither is the JPA entity, so the database model can change without changing the API.

Java
public record CreateOrder(
@NotBlank String customerId,
@NotEmpty List<@Valid Line> lines) {
public record Line(@NotBlank String sku, @Positive int quantity) {}
}
public record OrderDto(long id, String customerId, String status, BigDecimal total) {}

3Writing the Controller

Now the controller itself. It stays thin: it maps HTTP to a service call and back, and the service does the work.

Java
@RestController
@RequestMapping("/orders")
public class OrderController {
private final OrderService orders;
public OrderController(OrderService orders) { this.orders = orders; }
@GetMapping("/{id}")
public OrderDto get(@PathVariable long id) {
return orders.find(id); // 200 with JSON body; service throws if missing
}
@PostMapping
public ResponseEntity<OrderDto> create(@Valid @RequestBody CreateOrder req) {
OrderDto created = orders.create(req); // e.g. id 42
URI location = ServletUriComponentsBuilder
.fromCurrentRequest() // http://localhost:8080/orders
.path("/{id}") // http://localhost:8080/orders/{id}
.buildAndExpand(created.id()) // http://localhost:8080/orders/42
.toUri();
return ResponseEntity.created(location).body(created); // 201, Location: .../orders/42
}
}
Step throughPOST /orders end to end
ClientOrderControllerOrderServiceDatabase
POST /orders {customerId, lines}
validate CreateOrder
create(req)
INSERT order and lines
id 42
OrderDto(42, ...)
201 Created, Location: /orders/42, JSON body

7 messages in order. Play them, or step through them one at a time.

Notice how the Location is built. fromCurrentRequest() starts from the URI of the POST we are handling, so we do not hard-code the host or the /orders prefix. path("/{id}") appends a template, and buildAndExpand fills it in and encodes it. If the class prefix changes one day, the Location still points to the right place.

Notice also @Valid on the request body. If customerId is blank or a quantity is zero, Spring throws MethodArgumentNotValidException before our method runs, and the client gets 400 Bad Request. With spring.mvc.problemdetails.enabled=true, Boot formats that as an RFC 9457 problem detail.

4Testing It With MockMvc

A slice test with @WebMvcTest starts only the web layer, so it runs in a second or two. We mock the service and check the status, the header and the body.

Java
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired MockMvc mvc;
@MockitoBean OrderService orders; // Boot 3.4+; older versions use @MockBean
@Test
void createReturns201WithLocation() throws Exception {
when(orders.create(any())).thenReturn(new OrderDto(42, "c-1", "NEW", new BigDecimal("19.90")));
mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON)
.content("""
{"customerId":"c-1","lines":[{"sku":"BOOK-1","quantity":2}]}"""))
.andExpect(status().isCreated()) // 201
.andExpect(header().string("Location", "http://localhost/orders/42")) // MockMvc host is localhost
.andExpect(jsonPath("$.id").value(42));
}
@Test
void invalidBodyReturns400() throws Exception {
mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON).content("{\"lines\":[]}"))
.andExpect(status().isBadRequest()); // 400, validation failed
}
}

5Details That Trip People Up

The first is proxies. Behind a load balancer, the current request may look like http://10.0.0.5:8080/orders, and the Location would point there. Spring Boot can honour X-Forwarded-Host and X-Forwarded-Proto headers when we set server.forward-headers-strategy=framework, or native when the container handles them; then the Location uses the public host.

The second is the GET path for a missing order. The service should throw an exception that maps to 404, for example a ResponseStatusException with HttpStatus.NOT_FOUND or a custom exception handled in a @RestControllerAdvice, rather than returning null, which would give an empty 200 response.

The third is idempotency. If the client retries a POST after a timeout, it may create two orders. For payments and orders, an Idempotency-Key header that the service stores and checks is a common protection, and worth mentioning if the interviewer asks about retries.

6Follow-up questions

Why not return the entity from the POST?

Returning the entity exposes every field, including internal ones, couples the API to the database model, and can trigger lazy loading errors or infinite recursion during JSON serialisation. A response DTO keeps the contract explicit and stable.

Is the body required in a 201 response?

No. HTTP only requires the status, and the Location header is strongly expected. Returning the created representation saves the client a second request, so most APIs include it. ResponseEntity.created(location).build() sends no body if we prefer.

7Conclusion

In this answer, we wrote a REST controller with a class-level @RequestMapping("/orders"), a GET that binds the id with @PathVariable and returns a DTO as JSON, and a POST that validates a request record with @Valid @RequestBody, builds the Location with ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri(), and returns ResponseEntity.created(location).body(dto). We tested it with MockMvc and covered proxies, missing orders and retries.

What to say in the interviewAbout 80 seconds aloud

Open with

I'd annotate the class with @RestController and @RequestMapping("/orders") so both methods share the prefix. For the GET, a @GetMapping("/{id}") method takes @PathVariable long id, calls the service and returns an OrderDto, which Jackson writes as JSON with a 200.

Then, if they want more

If the order doesn't exist, the service throws an exception that's mapped to 404, rather than returning null. For the POST, the method takes @Valid @RequestBody CreateOrder, a record with only the fields the client may send and validation annotations on them, so a bad body is rejected with 400 before my code runs.

The service creates the order and returns the DTO with the new id. Then I build the Location with ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri(), which starts from the current request URI, so I don't hard-code the host or prefix. The return value is ResponseEntity.created(location).body(dto), which gives 201 Created with the Location header and the created representation.

I'd use separate request and response records rather than the entity, and I'd test it with a @WebMvcTest checking the 201, the Location header and a 400 for an invalid body. Behind a proxy, I'd configure forwarded headers so the Location uses the public host.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a controller with GET /orders/{id} returning JSON and POST /orders accepting JSON...": https://scrivio-interview-library.netlify.app/spring-boot/rest-controllers/63dbe18f67/