In a REST (JSON) API written using Spring Boot, what's a good way to implement a PATCH…
- User
In a REST (JSON) API written using Spring Boot, what's a good way to implement a
PATCHendpoint that can distinguish between whether a field is set tonull(in which case this is propagated to the DB) or just not present in the request body (in which case the field is left as-is)? - Assistant
To implement a
PATCHendpoint in a Spring Boot REST API that distinguishes between a field being explicitly set tonulland omitted entirely from the request body, you can use theJsonNodeclass from Jackson (which is the default JSON processor in Spring Boot). This allows you to inspect whether a field is present in the request and whether its value isnull.
✅ Key Concepts
PATCHis used for partial updates, meaning only the fields provided in the request are updated.- In JSON, the difference between:
"field": null(explicitly set tonull)- No
"field"key (not present in the request)
- In Spring Boot, when using
@RequestBody, the default behavior of Jackson is to deserialize missing fields asnull. So, to distinguish between these two cases, you need to inspect the presence of the field in the JSON request.
🛠️ Solution: Using
JsonNodeHere’s how you can implement this:
1. Controller Method
Use
JsonNodeto parse the request body and check for the presence of each field:import com.fasterxml.jackson.databind.JsonNode; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/resources") public class ResourceController { private final ResourceRepository resourceRepository; public ResourceController(ResourceRepository resourceRepository) { this.resourceRepository = resourceRepository; } @PatchMapping("/{id}") public ResponseEntity<Resource> patchResource( @PathVariable Long id, @RequestBody JsonNode requestNode) { Resource resource = resourceRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException(id)); if (requestNode.has("name")) { String name = requestNode.get("name").asText(); resource.setName(name); } if (requestNode.has("age")) { Integer age = requestNode.get("age").asInt(); resource.setAge(age); } // Add more fields as needed... Resource updatedResource = resourceRepository.save(resource); return ResponseEntity.ok(updatedResource); } }
🧠 How It Works
requestNode.has("name")checks whether the"name"field exists in the request body.- If it exists, the value is extracted and set on the entity, even if the value is
null. - If it does not exist, the current value in the entity remains unchanged.
🔁 Example Requests
Case 1: Field is set to
null{ "name": null }requestNode.has("name")→trueresource.setName(null)→ field is set tonullin the DB.
Case 2: Field is omitted
{ "age": 30 }requestNode.has("name")→falsenamefield remains unchanged in the entity.
🧩 Optional: Use a Map for Simplicity
If you prefer using a
Map<String, Object>instead ofJsonNode, it works similarly:@PostMapping("/resources/{id}") public ResponseEntity<Resource> patchResource( @PathVariable Long id, @RequestBody Map<String, Object> fields) { Resource resource = resourceRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException(id)); if (fields.containsKey("name")) { resource.setName((String) fields.get("name")); } if (fields.containsKey("age")) { resource.setAge((Integer) fields.get("age")); } // ... other fields return ResponseEntity.ok(resourceRepository.save(resource)); }
⚠️ Caveats
- This approach requires manually checking each field, which can become tedious for large entities.
- For better maintainability, consider using a DTO with field presence tracking or a custom deserializer if you're working with complex nested structures.
- Ensure that the client knows to explicitly set fields to
nullif they want them to be updated tonull.
✅ Summary
Condition Action Field present in request Update the field, even if it's nullField not present Leave the field unchanged in the entity By using
JsonNodeorMap<String, Object>in your@RequestBody, you gain full control over which fields were actually sent in the request, enabling the correct behavior forPATCHoperations.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.