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.
Join the DZone community and get the full member experience.
Join For FreeLet'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:
x
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr353</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>org.apache.johnzon</groupId>
<artifactId>johnzon-core</artifactId>
</dependency>
</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.
xxxxxxxxxx
{
"front_patio": true,
"back_patio": true,
"windows": 12,
"doors": 4,
"Balcony": false
}
What's more, we need to make the accompanying update:
xxxxxxxxxx
{
"doors": 5
}
The outcome will be the following:
xxxxxxxxxx
{
"front_patio": true,
"back_patio": true,
"windows": 12,
"doors": 5,
"Balcony": false
}
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
x
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import javax.json.Json;
import javax.json.JsonMergePatch;
import javax.json.JsonReader;
import javax.json.JsonWriter;
public class JsonMergePatchHttpMessageConverter extends AbstractHttpMessageConverter<JsonMergePatch> {
public JsonMergePatchHttpMessageConverter() {
super(MediaType.valueOf("application/merge-patch+json"));
}
protected boolean supports(Class<?> clazz) {
return JsonMergePatch.class.isAssignableFrom(clazz);
}
protected JsonMergePatch readInternal(Class<? extends JsonMergePatch> clazz, HttpInputMessage inputMessage)
throws HttpMessageNotReadableException {
try (JsonReader reader = Json.createReader(inputMessage.getBody())) {
return Json.createMergePatch(reader.readValue());
} catch (Exception e) {
return null;
}
}
protected void writeInternal(JsonMergePatch jsonMergePatch, HttpOutputMessage outputMessage)
throws HttpMessageNotWritableException {
try (JsonWriter writer = Json.createWriter(outputMessage.getBody())) {
writer.write(jsonMergePatch.toJsonValue());
} catch (Exception e) {
throw new HttpMessageNotWritableException(e.getMessage(), e);
}
}
}
and add the converter to configuration.
xxxxxxxxxx
public class ...... extends WebMvcConfigurationSupport {
........
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(jsonMergePatchHttpMessageConverter);
addDefaultHttpMessageConverters(converters);
}
}
Here's the Rest controller for School Example
x
public class SchoolController {
private SchoolService schoolService;
(path = "/school/{schoolId}", consumes = "application/merge-patch+json")
public ResponseEntity <Void> patchSchool(
Long schoolId,
JsonMergePatch patchRequest) {
Void result = schoolService.patchSchool(schoolId, patchRequest);
return new ResponseEntity<>(result, HttpStatus.OK);
}
}
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.
xxxxxxxxxx
public class PatchHelper {
private final ObjectMapper mapper;
private final Validator validator;
public PatchHelper(Validator validator) {
this.validator = validator;
this.mapper = new ObjectMapper()
.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.findAndRegisterModules()
.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
}
public <T> T mergePatch(JsonMergePatch mergePatch, T targetBean, Class<T> beanClass) {
JsonValue target = mapper.convertValue(targetBean, JsonValue.class);
JsonValue patched = applyMergePatch(mergePatch, target);
return convertAndValidate(patched, beanClass);
}
private JsonValue applyMergePatch(JsonMergePatch mergePatch, JsonValue target) {
try {
return mergePatch.apply(target);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private <T> T convertAndValidate(JsonValue jsonValue, Class<T> beanClass) {
T bean = mapper.convertValue(jsonValue, beanClass);
validate(bean);
return bean;
}
private <T> void validate(T bean) {
Set<ConstraintViolation<T>> violations = validator.validate(bean);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
}
We are done, now we can directly use this patch helper to patch the passed request.
x
School initialschool = new School(true, true, 12, 4, false);
School patchedSchool = patchHelper.mergePatch(patchRequest, initialschool,
School.class);
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.
You may discover the source code of these examples here:: https://bitbucket.org/git-test1787/simple-patch-endpoint/src
Opinions expressed by DZone contributors are their own.
Comments