Spring Boot REST API Returns Java Bean (JSON)

Introduction

In this chapter, we will build the Spring Boot REST API that returns a Java Bean in JSON format. This is a common requirement for building web services that return the JSON to the client.

Setting Up the Project

Using Spring Initializr

  1. Open Spring Initializr:
  2. Configure Project Metadata:
    • Group: com.company
    • Artifact: springboot-rest-api
    • Name: springboot-rest-api
    • Description: Spring Boot REST API returns Java Bean as JSON
    • Package name: com.company.restapi
    • Packaging: Jar
    • Java Version: 21 (or the latest version available)
    • Spring Boot Version: Select the latest version of Spring Boot
  3. Select Dependencies:
    • Add the following dependencies:
      • Spring Web
  4. Generate and Download:
    • Click the “Generate” button to download the project as a ZIP file.

Importing the Project into IntelliJ IDEA

  1. Open IntelliJ IDEA:
    • Launch IntelliJ IDEA from your installed applications.
  2. Import the Project:
    • On the welcome screen, click “Open or Import”.
    • Navigate to the directory where you downloaded the Spring Initializr ZIP file.
    • Select the ZIP file and click “Open”.
    • IntelliJ IDEA will unzip the file and import the project.
  3. Configure Maven (if needed):
    • IntelliJ IDEA will automatically detect the Maven build file (pom.xml) and import the project.
    • If prompted, confirm any necessary Maven configurations.

Creating the Java Bean

Step 1: Create a Java Bean

  1. Create a new package:
    • In the src/main/java/com/company/restapi directory, create a new package named model.
  2. Create the Java Bean:
    • Inside the model package, create a new class named Student.
    • Add the following code to the Student class:
package com.company.restapi.model;

public class Student {
    private Long id;
    private String firstName;
    private String lastName;
    private String email;

    // Constructors
    public Student() {}

    public Student(Long id, String firstName, String lastName, String email) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Explaining the Java Bean

  • Fields: The Student class has four fields: id, firstName, lastName, and email.
  • Constructors: The class includes a no-argument constructor and a parameterized constructor.
  • Getters and Setters: The class provides getter and setter methods for each field, allowing other classes to access and modify the values.

Creating the REST Controller

Step 2: Create a Controller Class

  1. Create a new package:
    • In the src/main/java/com/company/restapi directory, create a new package named controller.
  2. Create the Controller Class:
    • Inside the controller package, create a new class named StudentController.
    • Add the following code to the StudentController class:
package com.company.restapi.controller;

import com.company.restapi.model.Student;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StudentController {

    @GetMapping("/student")
    public Student getStudent() {
        return new Student(1L, "Ramesh", "Fadatare", "ramesh.fadatare@example.com");
    }
}

Explaining the Controller Class

  • @RestController Annotation: Marks the class as a Spring MVC controller where every method returns a domain object instead of a view. It is a convenience annotation that combines @Controller and @ResponseBody.
  • @GetMapping("/student") Annotation: Maps HTTP GET requests to the /student URL to the getStudent method.
  • getStudent Method: Returns a new Student object with sample data.

Running the Application

Step 3: Run Your Spring Boot Application

  1. Open Application Class:
    • Navigate to the main application class (annotated with @SpringBootApplication).
  2. Run the Application:
    • In IntelliJ IDEA, right-click the main application class and select “Run ‘SpringbootRestApiApplication'”.
    • Alternatively, open a terminal, navigate to the project directory, and run mvn spring-boot:run.
  3. Verify the Application:
    • Open a web browser and go to http://localhost:8080/student.
    • You should see a JSON representation of the Student object:
{
    "id": 1,
    "firstName": "Ramesh",
    "lastName": "Fadatare",
    "email": "ramesh.fadatare@example.com"
}

Output

Spring Boot REST API Returns Java Bean (JSON)

Conclusion

In this chapter, we have created a simple Spring Boot REST API that returns a Java Bean as JSON. We set up the project, created a Student Java Bean, developed a REST API and ran the application to verify the JSON output. This example provides a foundation for building more complex REST APIs with Spring Boot.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top