Skip to content
The Chat Archive
qwen3-30b-a3b· Alibaba (Qwen) LMArena Human Preference 140K

In a REST (JSON) API written using Spring Boot, what's a good way to implement a PATCH…

  1. User

    In a REST (JSON) API written using Spring Boot, what's a good way to implement a PATCH endpoint that can distinguish between whether a field is set to null (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)?

  2. Assistant

    To implement a PATCH endpoint in a Spring Boot REST API that distinguishes between a field being explicitly set to null and omitted entirely from the request body, you can use the JsonNode class 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 is null.


    ✅ Key Concepts

    • PATCH is used for partial updates, meaning only the fields provided in the request are updated.
    • In JSON, the difference between:
      • "field": null (explicitly set to null)
      • No "field" key (not present in the request)
    • In Spring Boot, when using @RequestBody, the default behavior of Jackson is to deserialize missing fields as null. So, to distinguish between these two cases, you need to inspect the presence of the field in the JSON request.

    🛠️ Solution: Using JsonNode

    Here’s how you can implement this:

    1. Controller Method

    Use JsonNode to 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") → true
    • resource.setName(null) → field is set to null in the DB.

    Case 2: Field is omitted

    {
      "age": 30
    }
    
    • requestNode.has("name") → false
    • name field remains unchanged in the entity.

    🧩 Optional: Use a Map for Simplicity

    If you prefer using a Map<String, Object> instead of JsonNode, 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 null if they want them to be updated to null.

    ✅ Summary

    ConditionAction
    Field present in requestUpdate the field, even if it's null
    Field not presentLeave the field unchanged in the entity

    By using JsonNode or Map<String, Object> in your @RequestBody, you gain full control over which fields were actually sent in the request, enabling the correct behavior for PATCH operations.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.