Spring - REST JSON Response
Last Updated :
23 Jul, 2025
REST APIs have become increasingly popular due to their advantages in application development. They operate on a client-server architecture, where the client makes a request, and the server (REST API) responds with data. Clients can be front-end frameworks like Angular, React, or even another Spring application. Data can be sent in various formats, such as plain text, XML, or JSON. Among these, JSON (JavaScript Object Notation) is the standard for transporting data between web applications.
Key benefits of REST APIs:
- Scalable & Lightweight: REST APIs are stateless and follow a client-server architecture, which makes them highly scalable.
- Flexible Data Formats: They support multiple data formats like JSON and XML, though JSON is the most common format used.
- Easy Integration: REST APIs can be easily integrated into front-end frameworks like Angular, React, or even other Spring applications.
The below image demonstrates the communication between a Spring Application (REST API) and a front-end framework, where requests are sent from the front-end and JSON responses are returned.
Prerequisites
The prerequisites required are as follows:
- Basic knowledge of Spring Boot and REST APIs.
- A Spring Boot project set up with Maven or Gradle.
- Familiarity with JSON and its structure.
JSON
JSON is an abbreviation for JavaScript Object Notation. It is a text-based data format following Javascript object syntax. It has syntax somewhat like a Javascript object literal and can be used independently from Javascript. Many programming environments have the ability to parse and generate JSON. It exists as a string and needs to be converted into a native Javascript object to access the data by available global JSON methods of Javascript.
Structure of the JSON
{
"id": 07,
"framework": "Spring",
"API": "REST API",
"Response JSON": true
}
When sending an array of objects, they are wrapped in square brackets
[
{
"id": 07,
"name": "darshan"
},
{
"id": 08,
"name": "geek"
}
]
Setting Up the Spring Boot Project
Project Structure
The project structure for the application is as follow:

Step 1: Add Dependencies
To create a Spring Boot application that handles JSON responses, we need to include the spring-boot-starter-web dependency. This dependency provides essential features for building RESTful web services.
Maven Dependency:
Add the following dependency to the pom.xml file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
pom.xml:
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>sia</groupId>
<artifactId>GFG-JSON-REST-RESPONSE</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>GFG-JSON-REST-RESPONSE</name>
<description>REST API Response</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 2: Bootstrapping the Spring Application
Create the main application class to bootstrap the Spring Boot application.
GfgJsonRestResponseApplication.java:
Java
// Java Program to Illustrate Bootstrapping of an
// Application
package gfg;
// Importing classes
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// Annotation
@SpringBootApplication
// Main class
public class GfgJsonRestResponseApplication {
// Main driver method
public static void main(String[] args)
{
SpringApplication.run(
GfgJsonRestResponseApplication.class, args);
}
}
Step 3: Creating the Domain Bean
The domain bean represents the data structure that will be transferred as a JSON response. Use Lombok to automatically generate getters and setters.
Maven Dependency:
Dependency is as depicted below as follows:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
DomainBean.java:
Java
// java Program to illustrate DomainBean class
package gfg;
// Importing class
import lombok.Data;
// Annotation
@Data
// Class
public class DomainBean {
String id;
String name;
String data;
}
Step 4: Implementing the REST Controller
The REST controller handles incoming requests and sends JSON responses. Key annotations used include @RestController, @RequestMapping, and @GetMapping.
The below table demonstrates the essential annotation
Annotation | Description |
---|
@RestController | Combines @Controller and @ResponseBody |
@RequestMapping | Maps web requests with 'path' attribute and response format with 'produces' attribute |
@CrossOrigin | Permits cross-origin web requests on the specific handler classes/methods |
@GetMapping | Maps GET request on specific handler method |
@PathVariable | Binds the URI template variables to method parameters |
RestJsonResponse.java:
This class provides RESTful services.
Java
package gfg;
import java.util.ArrayList;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path="/JSON", produces="application/json")
@CrossOrigin(origins="*")
public class RestJsonResponse {
@GetMapping("/data")
public ArrayList<DomainBean> get() {
ArrayList<DomainBean> arr = new ArrayList<>();
DomainBean userOne = new DomainBean();
userOne.setId("1");
userOne.setName("@geek");
userOne.setData("GeeksforGeeks");
DomainBean userTwo = new DomainBean();
userTwo.setId("2");
userTwo.setName("@drash");
userTwo.setData("Darshan.G.Pawar");
arr.add(userOne);
arr.add(userTwo);
return arr;
}
@GetMapping("/{id}/{name}/{data}")
public ResponseEntity<DomainBean> getData(@PathVariable("id") String id,
@PathVariable("name") String name,
@PathVariable("data") String data) {
DomainBean user = new DomainBean();
user.setId(id);
user.setName(name);
user.setData(data);
HttpHeaders headers = new HttpHeaders();
ResponseEntity<DomainBean> entity = new ResponseEntity<>(user,headers,HttpStatus.CREATED);
return entity;
}
}
Outputs:
REST API's JSON response can be consumed by:
- Spring application itself.
- Front-end application/framework
Spring Application
- Spring offers the RestTemplate (a convenient way of handling a REST response)
- It has the HTTP method-specific handler methods.
ConsumeResponse.java ( Consume REST API response ):
Java
// Java Program to Illustrate Consume REST API response
package gfg;
// Importing required classes
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
// Class
public class ConsumeResponse {
// Creating an object of ResponseEntity class
RestTemplate rest = new RestTemplate();
public ResponseEntity<DomainBean> get()
{
return rest.getForEntity(
"http://localhost:8080/JSON/{id}/{name}/{data}",
DomainBean.class, "007", "geek@drash",
"Darshan.G.Pawar");
}
}
A normal Spring controller is used to retrieve the responses from the RestTemplate method and returns a view.
ResponseController.java ( Regular Controller ):
Java
// Java Program to Illustrate Regular Controller
package gfg;
// Importing required classes
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
// Annotation
@Controller
@RequestMapping("/ConsumeResponse")
// Class
public class ResponseController {
@GetMapping("/get") public String get(Model model)
{
// Creating object of ConsumeResponse class
ConsumeResponse data = new ConsumeResponse();
model.addAttribute("response",
data.get().getBody());
model.addAttribute("headers",
data.get().getHeaders());
return "output";
}
}
Output.html (output of API: Thymeleaf template):
HTML
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml/"
xmlns:th="https://www.thymeleaf.org/">
<head>
<title>GeeksforGeeks</title>
</head>
<body>
<h1 style="color:forestgreen" th:text="${response.id}">attributeValue will be placed here</h1>
<h1 style="color:forestgreen" th:text="${response.name}">attributeValue will be placed here</h1>
<h1 style="color:forestgreen" th:text="${response.data}">attributeValue will be placed here</h1>
<h2 style="color:forestgreen; width : 350px" th:text="${headers}">attributeValue will be placed here</h2>
</body>
</html>
Output:
Front-end Application/Framework - Angular
consume-json.component.ts (Angular component):
- This component retrieves the JSON data from the specified URL targeting REST API.
- Retrieved data is stored in a variable.
import { Component, OnInit, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-consume-json',
templateUrl: './consume-json.component.html',
styleUrls: ['./consume-json.component.css']
})
export class ConsumeJsonComponent implements OnInit {
restData : any;
constructor(private http:HttpClient) { }
ngOnInit() {
this.http.get('http://localhost:8080/JSON/data')
.subscribe(data => this.restData = data);
}
}
consume-json.component.html (view of component):
- Get the stored data by dot( . ) notation.
- 'ngFor' is an Angular template directive used for iterating through the collection of objects.
HTML
<h1>Rest API Response : JSON</h1>
<div>
<table *ngFor="let json of restData">
<tr>
<td>{{json.id}}</td>
<td>{{json.name}}</td>
<td>{{json.data}}</td>
</tr>
</table>
</div>
consume-json.component.css (Style file):
CSS
h1, tr{
color : green;
font-size : 25px;
}
Add - '<app-consume-json></app-consume-json>' in the 'app.component.html' file
Output:
- You can additionally map an object to JSON object literal using the Jackson API.
- Add the following dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
Note: This dependency will also automatically add the following libraries to the classpath:
- jackson-annotations
- jackson-core
Similar Reads
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Spring Boot Basics and Prerequisites
Introduction to Spring BootSpring is one of the most popular frameworks for building enterprise applications, but traditional Spring projects require heavy XML configuration, making them complex for beginners.Spring Boot solves this problem by providing a ready-to-use, production-grade framework on top of Spring. It eliminate
4 min read
Difference between Spring and Spring BootSpring Spring is an open-source lightweight framework that allows Java developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier
4 min read
Spring - Understanding Inversion of Control with ExampleSpring IoC (Inversion of Control) Container is the core of the Spring Framework. It creates and manages objects (beans), injects dependencies and manages their life cycles. It uses Dependency Injection (DI), based on configurations from XML files, Java-based configuration, annotations or POJOs. Sinc
6 min read
Spring - IoC ContainerThe Spring framework is a powerful framework for building Java applications. It can be considered a collection of sub-frameworks, also referred to as layers, such as Spring AOP, Spring ORM, Spring Web Flow, and Spring Web MVC. We can use any of these modules separately while constructing a Web appli
2 min read
BeanFactory vs ApplicationContext in SpringThe Spring Framework provides two core packages that enable Inversion of Control (IoC) and Dependency Injection (DI):org.springframework.beansorg.springframework.contextThese packages define Spring containers that manage the lifecycle and dependencies of beans.Spring offers two main containers1. Bea
6 min read
Spring Boot Core
Spring Boot - ArchitectureSpring Boot is built on top of the Spring Framework and follows a layered architecture. Its primary goal is to simplify application development by providing auto-configuration, embedded servers and a production-ready environment out of the box.The architecture of Spring Boot can be divided into seve
2 min read
Spring Boot - AnnotationsAnnotations in Spring Boot are metadata that simplify configuration and development. Instead of XML, annotations are used to define beans, inject dependencies and create REST endpoints. They reduce boilerplate code and make building applications faster and easier. Core Spring Boot Annotations 1. @Sp
5 min read
Spring Boot ActuatorDeveloping and managing an application are the two most important aspects of the applicationâs life cycle. It is very important to know what is going on beneath the application. Also, when we push the application into production, managing it gradually becomes critically important. Therefore, it is a
5 min read
How to create a basic application in Java Spring BootSpring Boot is the most popular Java framework that is used for developing RESTful web applications. In this article, we will see how to create a basic Spring Boot application.Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also p
3 min read
Spring Boot - Code StructureThere is no specific layout or code structure for Spring Boot Projects. However, there are some best practices followed by developers that will help us too. You can divide your project into layers like service layer, entity layer, repository layer,, etc. You can also divide the project into modules.
3 min read
Spring Boot - SchedulingSpring Boot provides the ability to schedule tasks for execution at a given time period with the help of @Scheduled annotation. This article provides a step by step guideline on how we can schedule tasks to run in a spring boot application Implementation:It is depicted below stepwise as follows:Â St
4 min read
Spring Boot - LoggingLogging in Spring Boot plays a vital role in Spring Boot applications for recording information, actions, and events within the app. It is also used for monitoring the performance of an application, understanding the behavior of the application, and recognizing the issues within the application. Spr
8 min read
Exception Handling in Spring BootException handling in Spring Boot helps deal with errors and exceptions present in APIs, delivering a robust enterprise application. This article covers various ways in which exceptions can be handled and how to return meaningful error responses to the client in a Spring Boot Project. Key Approaches
8 min read
Spring Boot with REST API
Spring Boot - Introduction to RESTful Web ServicesRESTful Web Services REST stands for REpresentational State Transfer. It was developed by Roy Thomas Fielding, one of the principal authors of the web protocol HTTP. Consequently, REST was an architectural approach designed to make the optimum use of the HTTP protocol. It uses the concepts and verbs
5 min read
Spring Boot - REST ExampleIn modern web development, most applications follow the Client-Server Architecture. The Client (frontend) interacts with the server (backend) to fetch or save data. This communication happens using the HTTP protocol. On the server, we expose a bunch of services that are accessible via the HTTP proto
4 min read
How to Create a REST API using Java Spring Boot?Representational State Transfer (REST) is a software architectural style that defines a set of constraints for creating web services. RESTful web services allow systems to access and manipulate web resources through a uniform and predefined set of stateless operations. Unlike SOAP, which exposes its
4 min read
How to Make a Simple RestController in Spring Boot?A RestController in Spring Boot is a specialized controller that is used to develop RESTful web services. It is marked with the @RestController annotation, which combines @Controller and @ResponseBody. This ensures that the response is automatically converted into JSON or XML, eliminating the need f
2 min read
JSON using Jackson in REST API Implementation with Spring BootWhen we build REST APIs with Spring Boot, we need to exclude NULL values from the JSON responses. This is useful when we want to optimize the data being transferred, making the response more compact and easier to process for the client.In this article, we are going to learn the approach that is used
4 min read
Spring Boot with Database and Data JPA
Spring Boot with H2 DatabaseH2 Database in Spring Boot is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It stores data in memory, not persist the data on disk. Here we will be discussing how can we configure and perform some b
6 min read
Spring Boot - JDBCSpring Boot JDBC is used to connect the Spring Boot application with JDBC by providing libraries and starter dependencies. Spring Boot JDBC has a level of control over the SQL queries that are being written. Spring Boot JDBC has simplified the work of Spring JDBC by automating the work and steps by
8 min read
Advantages of Spring Boot JDBCSpring JDBC is used to build the Data Access Layer of enterprise applications, it enables developers to connect to the database and write SQL queries and update data to the relational database. The code related to the database has to be placed in DAO classes. SpringJDBC provides a class called JdbcT
3 min read
Spring Boot - CRUD OperationsCRUD stands for Create, Read/Retrieve, Update, and Delete and these are the four basic operations that we perform on persistence storage. CRUD is data-oriented and the standardized use of HTTP methods or there is a term for this called HTTP action verbs. HTTP has a few action verbs or methods that w
7 min read
Spring Boot - MongoRepository with ExampleSpring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
5 min read
Spring Boot JpaRepository with ExampleSpring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
9 min read
Spring Boot - CrudRepository with ExampleSpring Boot's CrudRepository is a part of the Spring Data JPA framework, which provides convenient methods for performing CRUD (Create, Read, Update, Delete) operations on entities in a relational database. CrudRepository is an interface that extends the basic Repository interface and adds generic C
5 min read
Spring Boot with Kafka
Spring Boot Kafka Producer ExampleSpring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica
3 min read
Spring Boot Kafka Consumer ExampleSpring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica
3 min read
Spring Boot | How to consume JSON messages using Apache KafkaApache Kafka is a stream processing system that lets you send messages between processes, applications, and servers. In this article, we will see how to publish JSON messages on the console of a Spring boot application using Apache Kafka. In order to learn how to create a Spring Boot project, refer
3 min read
Spring Boot | How to consume string messages using Apache KafkaApache Kafka is a publish-subscribe messaging queue used for real-time streams of data. A messaging queue lets you send messages between processes, applications, and servers. In this article we will see how to send string messages from apache kafka to the console of a spring boot application. Appro
3 min read
Spring Boot | How to publish String messages on Apache KafkaApache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send string messages to Apache Kafka in a spring boot application. In order to learn how to create a spring boot project, r
2 min read
Spring Boot | How to publish JSON messages on Apache KafkaApache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send JSON messages to Apache Kafka in a spring boot application. In order to learn how to create a spring boot project, ref
4 min read
Spring Boot with AOP
Spring Boot - AOP(Aspect Oriented Programming)The Java applications are developed in multiple layers, to increase security, separate business logic, persistence logic, etc. A typical Java application has three layers namely they are Web layer, the Business layer, and the Data layer. Web layer: This layer is used to provide the services to the e
4 min read
How to Implement AOP in Spring Boot Application?AOP(Aspect Oriented Programming) breaks the full program into different smaller units. In numerous situations, we need to log, and audit the details as well as need to pay importance to declarative transactions, security, caching, etc., Let us see the key terminologies of AOP Aspect: It has a set of
10 min read
Spring Boot - Difference Between AOP and OOPAOP(Aspect-Oriented Programming) complements OOP by enabling modularity of cross-cutting concerns. The Key unit of Modularity(breaking of code into different modules) in Aspect-Oriented Programming is Aspect. one of the major advantages of AOP is that it allows developers to concentrate on business
3 min read
Spring Boot - Difference Between AOP and AspectJSpring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
3 min read
Spring Boot - Cache ProviderThe Spring Framework provides support for transparently adding caching to an application. The Cache provider gives authorization to programmers to configure cache explicitly in an application. It incorporates various cache providers such as EhCache, Redis, Guava, Caffeine, etc. It keeps frequently a
6 min read