{{announcement.body}}
{{announcement.title}}

Getting Started with Patch Endpoint

DZone 's Guide to

Getting Started with Patch Endpoint

Getting started with patch endpoint with JSON Merge Patch Message converter. Let's start and test the same in Postman.

· Microservices Zone ·
Free Resource

Let's assert into a quick tutorial covering sending a PATCH request to a Rest Controller in Spring Boot.

If you're starting from scratch, then you might want to have a look at Spring’s starter guide. The setup is covered in the link provided.

The maven dependencies we need to add:

XML
 




x


1
<dependencies>
2
  <dependency>
3
      <groupId>org.springframework.boot</groupId>
4
      <artifactId>spring-boot-starter-web</artifactId>
5
  </dependency>
6
  <dependency>
7
      <groupId>org.springframework.boot</groupId>
8
      <artifactId>spring-boot-starter-test</artifactId>
9
      <scope>test</scope>
10
  </dependency>
11
  <dependency>
12
      <groupId>javax.json</groupId>
13
      <artifactId>javax.json-api</artifactId>
14
      <version>1.1.4</version>
15
  </dependency>
16
  <dependency>
17
        <groupId>com.fasterxml.jackson.datatype</groupId>
18
        <artifactId>jackson-datatype-jsr353</artifactId>
19
        <version>2.9.8</version>
20
   </dependency>
21
   <dependency>
22
      <groupId>org.apache.johnzon</groupId>
23
      <artifactId>johnzon-core</artifactId>
24
  </dependency>
25
</dependencies>


Previously, placing our leg into the Patch endpoint, let's view having the contrast among patch and put.

The patch is utilized when you need to apply a halfway update to the resource. Let's expect a school that has the following highlights.

JSON
 




xxxxxxxxxx
1


1
{
2
 "front_patio": true,
3
 "back_patio": true,
4
 "windows": 12,
5
 "doors": 4,
6
 "Balcony": false
7
}


What's more, we need to make the accompanying update:

JSON
 




xxxxxxxxxx
1


1
{
2
 "doors": 5
3
}


The outcome will be the following:

JSON
 




xxxxxxxxxx
1


1
{
2
"front_patio": true,
3
"back_patio": true,
4
"windows": 12,
5
"doors": 5,
6
"Balcony": false
7
}



To parse a PATCH demand payload, we should take an approaching solicitation with the application/blend patch+json content sort, the payload must be changed over to an occurrence of JsonMergePatch. 

Spring MVC, be that as it may, doesn't have the foggiest idea how to make examples of JsonMergePatch. So we have to give a custom HttpMessageConverter<T> to each sort. Luckily it's quite direct. For accommodation, how about we broaden AbstractHttpMessageConverter<T> and annotate on the execution with @Component, so Spring can get it 

Here the constructor will conjure the parent's constructor demonstrating the upheld media type for this converter, We additionally demonstrate that our converter underpins the mergePatch class

Java
 




x


1
import org.springframework.http.HttpInputMessage;
2
import org.springframework.http.HttpOutputMessage;
3
import org.springframework.http.MediaType;
4
import org.springframework.http.converter.AbstractHttpMessageConverter;
5
import org.springframework.http.converter.HttpMessageNotReadableException;
6
import org.springframework.http.converter.HttpMessageNotWritableException;
7
import org.springframework.stereotype.Component;
8
 
          
9
import javax.json.Json;
10
import javax.json.JsonMergePatch;
11
import javax.json.JsonReader;
12
import javax.json.JsonWriter;
13
 
          
14
@Component
15
public class JsonMergePatchHttpMessageConverter extends AbstractHttpMessageConverter<JsonMergePatch> {
16
 
          
17
    public JsonMergePatchHttpMessageConverter() {
18
        super(MediaType.valueOf("application/merge-patch+json"));
19
    }
20
 
          
21
    @Override
22
    protected boolean supports(Class<?> clazz) {
23
        return JsonMergePatch.class.isAssignableFrom(clazz);
24
    }
25
 
          
26
    @Override
27
    protected JsonMergePatch readInternal(Class<? extends JsonMergePatch> clazz, HttpInputMessage inputMessage)
28
            throws HttpMessageNotReadableException {
29
 
          
30
        try (JsonReader reader = Json.createReader(inputMessage.getBody())) {
31
            return Json.createMergePatch(reader.readValue());
32
        } catch (Exception e) {
33
            return null;
34
        }
35
    }
36
 
          
37
    @Override
38
    protected void writeInternal(JsonMergePatch jsonMergePatch, HttpOutputMessage outputMessage)
39
            throws HttpMessageNotWritableException {
40
 
          
41
        try (JsonWriter writer = Json.createWriter(outputMessage.getBody())) {
42
            writer.write(jsonMergePatch.toJsonValue());
43
        } catch (Exception e) {
44
            throw new HttpMessageNotWritableException(e.getMessage(), e);
45
        }
46
    }
47
}
48
 
          


and add the converter to configuration.

Java
 




xxxxxxxxxx
1


 
1
@Configuration
2
public class ...... extends WebMvcConfigurationSupport {
3
  ........
4
@Override
5
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
6
        converters.add(jsonMergePatchHttpMessageConverter);
7
        addDefaultHttpMessageConverters(converters);
8
}
9
}


Here's the Rest controller for School Example

Java
 




x


1
@RestController
2
public class SchoolController {
3
    @Autowired private SchoolService schoolService;
4
    
5
    @PatchMapping(path = "/school/{schoolId}", consumes = "application/merge-patch+json")
6
    public ResponseEntity <Void> patchSchool(
7
             @PathVariable Long schoolId,
8
             @RequestBody JsonMergePatch patchRequest) {
9
        Void result = schoolService.patchSchool(schoolId, patchRequest);
10
        return new ResponseEntity<>(result, HttpStatus.OK);
11
    }
12
}


We have to get the underlying school from backend, and fixed the passed patchRequest and spare the current example. here for blending the pacthed information, we need to make a Patch Helper for it.

Java
 




xxxxxxxxxx
1
42


1
@Component
2
public class PatchHelper {
3
 
          
4
    private final ObjectMapper mapper;
5
    private final Validator validator;
6
 
          
7
    public PatchHelper(Validator validator) {
8
        this.validator = validator;
9
        this.mapper = new ObjectMapper()
10
                .setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL)
11
                .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
12
                .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
13
                .findAndRegisterModules()
14
                .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
15
    }
16
 
          
17
    public <T> T mergePatch(JsonMergePatch mergePatch, T targetBean, Class<T> beanClass) {
18
        JsonValue target = mapper.convertValue(targetBean, JsonValue.class);
19
        JsonValue patched = applyMergePatch(mergePatch, target);
20
        return convertAndValidate(patched, beanClass);
21
    }
22
 
          
23
    private JsonValue applyMergePatch(JsonMergePatch mergePatch, JsonValue target) {
24
        try {
25
            return mergePatch.apply(target);
26
        } catch (Exception e) {
27
            throw new RuntimeException(e);
28
        }
29
    }
30
 
          
31
    private <T> T convertAndValidate(JsonValue jsonValue, Class<T> beanClass) {
32
        T bean = mapper.convertValue(jsonValue, beanClass);
33
        validate(bean);
34
        return bean;
35
    }
36
 
          
37
    private <T> void validate(T bean) {
38
        Set<ConstraintViolation<T>> violations = validator.validate(bean);
39
        if (!violations.isEmpty()) {
40
            throw new ConstraintViolationException(violations);
41
        }
42
    }


We are done, now we can directly use this patch helper to patch the passed request.

Java
 




x


1
School initialschool = new School(true, true, 12, 4, false);
2
School patchedSchool = patchHelper.mergePatch(patchRequest, initialschool,
3
                    School.class);
4
System.out.print(initialschool);


Summary: JSON Merge Patch is an innocently straightforward arrangement, with restricted ease of use. Likely it is a decent decision in the event that you are building something little, with straightforward JSON Schema, however, you need to offer a rapidly reasonable, pretty much-working strategy for customers to refresh JSON records. A REST API intended for open utilization however without fitting customer libraries may be a genuine model.

patchRequest example {"doors":5}

You may discover the source code of these examples here:: https://bitbucket.org/git-test1787/simple-patch-endpoint/src 

Topics:
microservice

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}