eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – RwS Java – NPI EA (cat=Java)
announcement - icon

Building a REST API with Spring?

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

Job – Java Automation Lead NPI EA (cat=REST)
announcement - icon

We're looking for a Backend Java/Spring Team Lead with Integration Experience (Remote) (Part Time):

Read More

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

We rely on other people’s code in our own work. Every

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production - debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It's one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

>> Learn more in this quick, 5-minute Lightrun tutorial

Course – LS – NPI EA (cat=Spring)
announcement - icon

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

LEARN SPRING

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Partner – Machinet – NPI EA (cat = Testing)
announcement - icon

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation .
Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.
And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Partner – Bellsoft – NPI EA (cat = Spring/DevOps)
announcement - icon

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

Learn Spring Security

Partner – Aegik AB – NPI EA (tag = SQL)
announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:

>> Try out the Profiler

Partner – DBSchema – NPI EA (tag = SQL)
announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .

Get started with Spring Data JPA through the guided reference course:

CHECK OUT THE COURSE

Course – launch – BF – 2023 Discount 30%
We're now running the only sale of the year - our Black Friday launch. All Courses are 30% off until next Monday:

>> 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 {
    @Autowired
    private StudentService service;
    @GetMapping("/{id}")
    public Student read(@PathVariable 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 don’t find the requested student? Instead of returning a 200 or 500 status code, we might want to return a 404.

Let’s take a look at how to wrest more control over the HTTP response itself, and in turn 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("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 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 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.

Partner – Machinet – NPI EA (cat = Testing)
announcement - icon

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation.
Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Simplify Your Coding Journey with Machinet AI:

>> Install Machinet AI in your IntelliJ

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

We rely and run a host of libraries and frameworks we didn't implement ourselves. Captain obvious here.

The problem is, of course, when things fall apart in production - debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger:

>> Learn more in this quick, 5-minute Lightrun tutorial

Course – launch – BF – 2023 Discount 30%
We're now running the only sale of the year - our Black Friday launch. All Courses are 30% off until next Monday:

>> EXPLORE ACCESS NOW

res – REST with Spring (eBook) (everywhere)