Spring ResponseEntity, ResponseBody, ResonseStatus

ResponseEntity represents an HTTP response, including headers, body, and status in a spring restful API. While @ResponseBody puts the return value into the body of the response of API, ResponseEntity also allows us to add headers and status code as well.

Prerequisite :

Let’s take a Java Entity Model Class called “Dependant” to be used in this example.

@Entity
@Table(name = "Dependant")
public class Dependant implements Serializable {

    @Id
    private int deptid;

    @Column(name="firstname")
    private String firstname;

    @Column(name="lastname")
    private String lastname;

    // getter, setter methods ...
}

1. ResponseEntity

Example

Let’s create a simple REST API which returns Dependant class object which we made above, wrapped inside the ResponseEntity.

@GetMapping("/dependant/id/{id}")
public ResponseEntity<Dependant> getDependantbyId(@PathVariable int id){
        
    Dependant dept = new Dependant();
    dept = dependantRepository.findBydeptid(id);
   
    HttpHeaders headers = new HttpHeaders();
    headers.add("Custom-Header", "foo - Department");

    return ResponseEntity.status(HttpStatus.OK).headers(headers).body(dept);
}

We give ResponseEntity a custom status code, headers, and a body.

OUTPUT

Status : 200 OK

Custom-Header →foo - Department
Content-Type →application/json;charset=UTF-8
Transfer-Encoding →chunked
Date →Tue, 25 Feb 2020 07:48:58 GMT

and body as shown below

{
    "deptid": 1,
    "firstname": "Donald",
    "lastname": "T",
}

2. @ResponseBody

Example

In this example we try to achieve the same as as ResponseEntity but @ResponseBody only returns the body, in this case only the Dependant class object.

@GetMapping("/dependant/id/{id}")
@ResponseBody
public Dependant getDependant2byId(@PathVariable int id){

    Dependant dept = new Dependant();
    dept = dependantRepository.findBydeptid(id);
    
    return dept;
}

With @ResponseBody, only the body is returned. The headers and status code are provided by Spring.

3. @ResponseStatus

@ResponseStatus marks a method or exception class with the status code and reason message that should be returned. The status code is applied to the HTTP response when the handler method is invoked, or whenever the specified exception is thrown.
It overrides status information set by other means, like ResponseEntity or redirect.

Example : Custom Exceptions

@GetMapping("/dependant/id/{id}")
@ResponseBody
public Dependant getDependantbyId(@PathVariable int id){

	if(id>10){
		throw new MyCustomException("the id is not in range");
	}
	Dependant dept = new Dependant();
	dept = dependantRepository.findBydeptid(id);

	return dept;
}
	
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "No such dependant with this id")
public class MyCustomException extends RuntimeException {

    public MyCustomException(String message){
        super(message);
    }
}

Summary

In this article, we looked into ResponseEntity, ResponseBody and ResponseStatus functionalities/annotations. We learnt it by simple examples.
Please let us know if you have any questions or concerns related to the topic in the comments section below.
Hope you liked it !


React Router

React Router is a standard library for routing in a React app. It enables the navigation among views of various components in a React Application and allows changing the browser URL.

Super Easy installation

Create a react app first and when you are done with that then do a simple npm install of react-router-dom as shown below.

npx create-react-app demo-app
cd demo-app

npm install react-router-dom

Now after installing react-router-dom, add its components to your React app.

import { 
    BrowserRouter as Router, 
    Link, 
    Route, 
    Switch 
} from 'react-router-dom'; 

Four main components :

  • BrowserRouter : It is the parent component and the other Child components which we need to create routes for are wrapped inside this component.
    BrowserRouter is a router implementation that uses the HTML5 history API(pushState, replaceState and the popstate event) to keep your UI in sync with the URL.
  • Link : It works like html anchor tags, this is used to create routes and implement the navigation in the application.
  • Route : Route is used to conditionally open a component/page based on the link selected.
  • Switch : Switch component is used to render only the first route that matches the location rather than rendering all matching routes.

Example to showcase the React Router using the above components :

import React from "react";
import {
  BrowserRouter as Router,
  Link,
  Switch,
  Route,
} from "react-router-dom";

// This site has 3 pages, all of which are rendered
// dynamically in the browser (not server rendered).

// Although the page does not ever refresh, notice how
// React Router keeps the URL up to date as you navigate
// through the site. This preserves the browser history,
// making sure things like the back button and bookmarks
// work properly.

export default function RouteExample() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About Us</Link>
          </li>
          <li>
            <Link to="/dashboard">Dashboard</Link>
          </li>
        </ul>

        <hr />

        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/dashboard">
            <Dashboard />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

// You can think of these components as "pages"
 in your app.

function Home() {
  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}

function About() {
  return (
    <div>
      <h2>About Us</h2>
    </div>
  );
}

function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
    </div>
  );
}

Summary

In this article, we learnt about react routing using react-router-dom which can be installed as a node dependency and then used in any react app to navigate between the pages.
Please let us know in the comments below about your thoughts and queries.
Hope you liked it !