Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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 code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW