Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll demonstrate how to build a REST service to consume and produce JSON content with Spring Boot.

We’ll also take a look at how we can easily employ RESTful HTTP semantics.

For simplicity, we won’t include a persistence layer, but Spring Data also makes this easy to add.

2. REST Service

Writing a JSON REST service in Spring Boot is simple, as that’s its default opinion when Jackson is on the classpath:

@RestController
@RequestMapping("/students")
public class StudentController {

    private final StudentService service;

    public StudentController(StudentService service) {
        this.service = service;
    }

    @GetMapping("/{id}")
    public Student read(@PathVariable(name = "id) String id) {
        return service.find(id);
    }

...

By annotating our StudentController with @RestController, we’ve told Spring Boot to write the return type of the read method to the response body. Since we also have a @RequestMapping at the class level, it would be the same for any more public methods that we add.

Though simple, this approach lacks HTTP semantics. For example, what would happen if we didn’t find the requested student? Instead of returning a 200 or 500 status code, we might want to return a 404.

Let’s look at how to gain more control over the HTTP response itself and add some typical RESTful behaviors to our controller.

3. Create

When we need to control aspects of the response other than the body, like the status code, we can instead return a ResponseEntity:

@PostMapping("/")
public ResponseEntity<Student> create(@RequestBody Student student) 
    throws URISyntaxException {
    Student createdStudent = service.create(student);
    if (createdStudent == null) {
        return ResponseEntity.notFound().build();
    } else {
        URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
          .path("/{id}")
          .buildAndExpand(createdStudent.getId())
          .toUri();

        return ResponseEntity.created(uri)
          .body(createdStudent);
    }
}

Here, we’re doing much more than just returning the created Student in the response. We’re also responding with a semantically clear HTTP status and, if creation succeeds, a URI to the new resource.

4. Read

As previously mentioned, if we want to read a single Student, it’s more semantically clear to return a 404 if we can’t find the student:

@GetMapping("/{id}")
public ResponseEntity<Student> read(@PathVariable(name = "id") Long id) {
    Student foundStudent = service.read(id);
    if (foundStudent == null) {
        return ResponseEntity.notFound().build();
    } else {
        return ResponseEntity.ok(foundStudent);
    }
}

Here, we can clearly see the difference from our initial read() implementation.

This way, the Student object will be properly mapped to the response body and returned with a proper status at the same time.

5. Update

Updating is very similar to creation, except it’s mapped to PUT instead of POST, and the URI contains an id of the resource we’re updating:

@PutMapping("/{id}")
public ResponseEntity<Student> update(@RequestBody Student student, @PathVariable(name = "id) Long id) {
    Student updatedStudent = service.update(id, student);
    if (updatedStudent == null) {
        return ResponseEntity.notFound().build();
    } else {
        return ResponseEntity.ok(updatedStudent);
    }
}

6. Delete

The delete operation is mapped to the DELETE method. The URI also contains the id of the resource:

@DeleteMapping("/{id}")
public ResponseEntity<Object> deleteStudent(@PathVariable(name = "id") Long id) {
    service.delete(id);
    return ResponseEntity.noContent().build();
}

We didn’t implement specific error handling because the delete() method actually fails by throwing an Exception.

7. Conclusion

In this article, we learned how to consume and produce JSON content in a typical CRUD REST service developed with Spring Boot. Additionally, we demonstrated how to implement proper response status control and error handling.

To keep things simple, we didn’t go into persistence this time, but Spring Data REST provides a quick and efficient way to build a RESTful data service.

The complete source code for the example is available over on GitHub.

Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.