Quick revision
The short answer
We write a @PostMapping method in a @RestController that takes @Valid @RequestBody CustomerRequest and returns ResponseEntity<CustomerResponse>. After saving, we build the URI with ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri() and return ResponseEntity.created(uri).body(dto), which gives 201 with a Location header. If validation fails, Spring raises MethodArgumentNotValidException, which maps to 400, and we return a response DTO rather than the JPA entity so internal fields and lazy associations are never serialized.
What to remember
In this answer, we wrote a @RestController with a @PostMapping method taking @Valid @RequestBody CustomerRequest and returning ResponseEntity<CustomerResponse>. We built the Location with ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri() and returned ResponseEntity.created(uri).body(dto) for a 201. We saw that validation failures raise MethodArgumentNotValidException and become 400, and that returning a response DTO instead of the JPA entity keeps internal fields and lazy associations out of the JSON.
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 write a @PostMapping method in a @RestController that takes @Valid @RequestBody CustomerRequest and returns ResponseEntity<CustomerResponse>. After saving, we build the URI with ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri() and return ResponseEntity.created(uri).body(dto), which gives 201 with a Location header. If validation fails, Spring raises MethodArgumentNotValidException, which maps to 400, and we return a response DTO rather than the JPA entity so internal fields and lazy associations are never serialized.
Why this question is asked
Creating a resource is the most common write endpoint in any API, and it is where small mistakes show up first: a 200 instead of a 201, a missing Location header, validation that never runs, or an entity in the response that leaks internal columns or fails on a lazy association. Interviewers ask for this code to see whether we know the annotations and also why each one is there. In this answer, we will write the request and response DTOs, the controller method, see what each annotation does, look at what happens when validation fails, and explain why the response is a DTO rather than the entity.
1The Request and Response DTOs
A DTO, data transfer object, is a class that exists only to describe the JSON of one request or response. We use records, which are immutable and handled by Jackson directly. The request carries Bean Validation annotations, constraints that the validator checks before our code runs. Bean Validation needs the spring-boot-starter-validation dependency; without it, @Valid silently does nothing, which is a classic surprise.
Notice that the request has no id. The server assigns ids, so a client should not be able to send one; leaving it out of the DTO makes that impossible rather than merely forbidden.
2The Controller Method
Here is the complete endpoint. @RestController makes every method's return value the response body, written as JSON by Jackson. @PostMapping maps POST requests on /customers to the method. @RequestBody tells Spring to read the JSON body into CustomerRequest, and @Valid asks it to validate the result before calling us.
9 messages in order. Play them, or step through them one at a time.
Validation runs before the controller method is ever called.
The return type is ResponseEntity<CustomerResponse> because a plain return value would always produce 200 OK. ResponseEntity lets us set the status and headers, and ResponseEntity.created(uri) is a shortcut for status 201 with a Location header. ServletUriComponentsBuilder.fromCurrentRequest() starts from the URL of the current request, so the Location is correct whatever host, port or context path the service runs under. Behind a reverse proxy, the original host and scheme come from X-Forwarded headers, which Spring Boot honours when server.forward-headers-strategy is set to framework, or native on supported servers; otherwise the Location may point at the internal address.
3What Happens When Validation Fails
If the body violates a constraint, for example a blank name or an invalid email, the validator reports violations and Spring throws MethodArgumentNotValidException before our method runs. Spring MVC maps it to 400 Bad Request. So the controller code only ever sees valid input, and we do not write any if statements for these rules.
- Can Jackson read the JSON?YesContinueNo400: HttpMessageNotReadableException
- Do the constraints pass?
@NotBlank,@Email,@SizeYesCall the controllerNo400: MethodArgumentNotValidException - Service saves the customerBusiness rules, e.g. email unique
- Return 201 with Location
ResponseEntity.created(uri)
4 steps in order. Play them, or step through them one at a time.
Two different exceptions, both 400, with very different causes.
Malformed JSON, such as a missing brace, fails earlier, while Jackson reads the body, with HttpMessageNotReadableException, which also maps to 400. The default bodies are generic; clients usually want to know which field failed, which is the follow-up question below.
4Why We Return a DTO and Not the Entity
It is tempting to return the saved Customer entity directly, since it already has all the fields. There are three good reasons not to. First, entities contain internal fields such as version numbers, audit columns, password hashes or soft-delete flags, which become part of the public contract as soon as Jackson serializes them. Second, entities have associations, such as the customer's orders, that are often lazy: Jackson touching them outside a transaction throws a LazyInitializationException, or with open-in-view enabled silently runs extra queries, and bidirectional associations can recurse forever. Third, the API shape becomes tied to the database schema, so renaming a column breaks clients.
A response DTO fixes all three: it contains exactly the fields we promise, it is built while the data is loaded, and it can change independently of the table. The same reasoning applies on the way in, where binding a request directly to an entity would let clients set fields such as id or status, a problem known as mass assignment.
5Follow-up questions
How would you return validation errors as RFC 9457 problem details?
I would extend ResponseEntityExceptionHandler in a @RestControllerAdvice and override handleMethodArgumentNotValid. The exception already carries a 400 ProblemDetail through getBody(), so I add properties to it, for example an errorCode of VALIDATION_FAILED and an errors list with the field name and message of each FieldError, and return it with handleExceptionInternal. The client then gets application/problem+json with a standard shape plus the field details it needs to show messages next to inputs.
What if the email must be unique?
That is a business rule that needs the database, so it belongs in the service, not in a Bean Validation annotation. The service checks for an existing customer, and a unique constraint in the database is the final guarantee against races. A duplicate is reported as 409 Conflict, ideally as a problem detail with a clear error code.
Is it acceptable to return 201 without a body?
Yes, HTTP only requires that 201 indicates creation, and the Location header tells the client where to fetch the resource. Returning the representation in the body is a convenience that saves a round trip, and most JSON APIs do it, including server-assigned fields such as the id and timestamps.
6Conclusion
In this answer, we wrote a @RestController with a @PostMapping method taking @Valid @RequestBody CustomerRequest and returning ResponseEntity<CustomerResponse>. We built the Location with ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri() and returned ResponseEntity.created(uri).body(dto) for a 201. We saw that validation failures raise MethodArgumentNotValidException and become 400, and that returning a response DTO instead of the JPA entity keeps internal fields and lazy associations out of the JSON.
Open with
I would write a RestController with a RequestMapping of /customers and a PostMapping method that takes a CustomerRequest annotated with Valid and RequestBody. RequestBody makes Jackson read the JSON into the record, and Valid triggers Bean Validation, so the record carries constraints like NotBlank on the name and Email on the email; I need the validation starter on the classpath or Valid does nothing.
Then, if they want more
The method returns ResponseEntity of CustomerResponse, because I need a 201 and a header, not the default 200.
After the service saves the customer, I build the Location with ServletUriComponentsBuilder.fromCurrentRequest, path slash id in braces, buildAndExpand with the new id, toUri, and return ResponseEntity.created of that URI with the response DTO as body. fromCurrentRequest keeps host, port and context path right; behind a proxy I make sure forwarded headers are honoured.
If validation fails, Spring throws MethodArgumentNotValidException before my method runs and that maps to 400; malformed JSON gives HttpMessageNotReadableException, also 400. To return field errors as problem details I would extend ResponseEntityExceptionHandler and add an errors property.
And I return a DTO, not the JPA entity, so internal fields, lazy associations and recursion never reach the JSON, and the contract does not depend on the schema.
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 Spring MVC controller method that creates a customer from a JSON body, validates...": https://scrivio-interview-library.netlify.app/spring-boot/rest-api-design/4591d91fb7/