Open In App
Related Articles

Spring – REST JSON Response

Improve Article
Save Article
Like Article

REST APIs are becoming popular for the advantages they provide in the development of applications. REST APIs work like a client-server architecture. The client makes a request and a server (REST API) responds back by providing some kind of data. A client can be any front-end framework like Angular, React, etc, or Spring application ( internal/external ) itself. Data can be sent in various formats like plain text, XML, JSON, etc. Of these formats, JSON ( JavaScript Object Notation ) is a standard for transporting data between web applications.

Spring Application

Pre-requisites required are as follows: 

  1. JSON string can be stored in it own file with the ‘.json‘ extension.
  2. It has the MIME type of – ‘application/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
On sending an array of objects, they are wrapped in the square brackets

  "id" : 07,
  "name" : "darshan"
  "id" : 08,
  "name" : "DARSHAN"
  • Spring framework’s ‘Starter Web’ dependency provides you with the two essential features of Spring MVC – (Spring’s web framework)  and the RESTful ( REST API ) methodology.
  • To include ‘Starter Web’ in the Spring application, add the following dependency –
Maven -> pom.xml


Project structure – Maven

File: pom.xml (Configurations)


<?xml version="1.0" encoding="UTF-8"?>
        <relativePath/> <!-- lookup parent from repository -->
    <description>REST API Response</description>

File: ( Bootstrapping of the application )


// Java Program to Illustrate Bootstrapping of an
// Application
package gfg;
// Importing classes
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// Annotation
// Main class
public class GfgJsonRestResponseApplication {
    // Main driver method
    public static void main(String[] args)

            GfgJsonRestResponseApplication.class, args);


File: ( User properties – The data to be transferred ) 


  • Java Beans requires the Getter/Setter methods.
  • One can generate them automatically with the ‘@Data’ annotation of the ‘Lombok’ library.
  • Dependency is as depicted below as follows:
Maven -> pom.xml




// java Program to illustrate DomainBean class
package gfg;
// Importing class
import lombok.Data;
// Annotation
// Class
public class DomainBean {
    String id;
    String name;
    String data;


File: ( REST API )


  • This class provides RESTful services.
  • Essential annotations are –



@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



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;
@RequestMapping(path="/JSON", produces="application/json")
public class RestJsonResponse {
    public ArrayList<DomainBean> get() {
        ArrayList<DomainBean> arr = new ArrayList<>();
        DomainBean userOne = new DomainBean();
        DomainBean userTwo = new DomainBean();
        return arr;
    public ResponseEntity<DomainBean> getData(@PathVariable("id") String id,
                             @PathVariable("name") String name,
                                @PathVariable("data") String data) {
        DomainBean user = new DomainBean();
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<DomainBean> entity = new ResponseEntity<>(user,headers,HttpStatus.CREATED);
        return entity;


An array of JSON object literals

JSON object literal

REST API’s JSON response can be consumed by:

  1. Spring application itself.
  2. Front-end application/framework

A: Spring Application

  • Spring offers the ‘RestTemplate‘ – a convenient way of handling a REST response.
  • It has the HTTP method-specific handler methods.

File: ( Consume REST API response )


// 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(
            DomainBean.class, "007", "geek@drash",


File: ( Regular Controller )


A normal Spring controller is used to retrieve the responses from the ‘RestTemplate’ method and returns a view.





// 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
// Class
public class ResponseController {
    @GetMapping("/get") public String get(Model model)
        // Creating object of ConsumeResponse class
        ConsumeResponse data = new ConsumeResponse();
        return "output";


File: Output.html ( output of API: Thymeleaf template)



<!DOCTYPE html>
<h1 style="color:forestgreen" th:text="${}">attributeValue will be placed here</h1>
<h1 style="color:forestgreen" th:text="${}">attributeValue will be placed here</h1>
<h1 style="color:forestgreen" th:text="${}">attributeValue will be placed here</h1>
<h2 style="color:forestgreen; width : 350px" th:text="${headers}">attributeValue will be placed here</h2>


Response with JSON as content type

B: Front-end Application/Framework – Angular

File: 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';

  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() { 
     .subscribe(data => this.restData = data);

File: 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.


<h1>Rest API Response : JSON</h1>
 <table *ngFor="let json of restData">

File: consume-json.component.css ( Style file ) 


h1, tr{
  color : green;
  font-size : 25px;


Add - '<app-consume-json></app-consume-json>' in the 'app.component.html' file




Response retrieved by Angular component

  • You can additionally map an object to JSON object literal using the Jackson API.
  • Add the following dependency:
Maven -> pom.xml


Note: This dependency will also automatically add the following libraries to the classpath:


  • jackson-annotations
  • jackson-core


Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Last Updated : 03 Mar, 2022
Like Article
Save Article
Similar Reads
Complete Tutorials