Quick revision
The short answer
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.
What to remember
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.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
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.
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.
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.
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.
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.
- Official documentation
- Spring Framework reference, Spring Web MVC
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/