Creating a Rest Application with Spring Boot

In this tutorial, we will be developing a Rest webservice and will test the API from the Rest-client.

What is a REST API?

  • REST stands for REpresentational State Transfer which is an architectural style which makes the effective use of http protocol.

  • Data transfer takes place mainly in two formats (JSON/XML).

  • JSON (Javascript Object Notation) follows the pattern of key:value pair whereas XML (eXtensible Markup Language) follows the root and branch (tags) pattern.

  • Every Application deals with data, it may be the User profile, User orders, Product information (for an e-commerce application) etc. So, there is a repository of data which needs to be handled effectively.

  • Applications need some input which can be processed to generate the output. The output needs to be returned to the client who requested for the data.

  • Web service is nothing but a service delivered over the web. REST helps in building web services which are called as RESTful web services. The below figure displays the JSON and XML structures respectively.

  • REST API documentation can be generated by Swagger which will be discussed in upcoming tutorials.

Development of REST API:

All the REST end-points will be scanned using the annotation @RestController.

It is required to mark your end-points with the type of request they can handle (GET, POST, DELETE, etc).

Let us create some POJOs named Student and Teacher as follows. Both the classes are placed under the package com.tutorial.studytonight.pojo

Student.java

public class Student{
    private int id;
    private String name;
    private String institute;
    private LocalDate birthdate;
    private String city;
           
    //Setters and Getters
}

Teacher.java

public class Teacher{
    private int id;
    private String name;
    private String subject;
    private String institute;
    private String city;
       
    //Setters and Getters
}

The above classes are the POJOs created and we need a RestController class to scan the available REST end-points. In the POJOs setters and getters can be generated automatically from the IDE after right clicking in the Java file. (As seen in the figure 8.1).

Let's create the ResourceController class which will have the @RestController annotation,

@RestController
public class ResourceController{

    @Autowired
    ResourceService resourceService;

    @PostMapping("/saveTeacher")
    public void saveTeacher(@RequestBody Teacher  teacher){
        resourceService.saveTeacher(teacher);
    }

    @GetMapping("/getTeacherDetails/{id}")
    public Teacher getTeacherDetails(@PathVariable("id") int id){
        return resourceService.getTeacherDetails(id);
    }
}   

The above class is the ResourceController annotated with @RestController to scan the REST end-points.

Usually in the development we follow the layered architecture where we have RestController for defining the endpoints, Service layer where all the action takes place and the Repository layer where data is stored.

Let us create a Service layer (where business logic goes) and a Repository layer (for database transactions). We are not using any database to store the values in this example, we will be using an In-memory database (H2) in the upcoming tutorials.

Instead of a Database we will be storing the values in a HashMap and will be retrieving from it using a GET request.

@Service
public class ResourceService{

    @Autowired
    ResourceRepository repository;

    public void saveTeacher(Teacher teacher){
        repository.saveTeacher(teacher);
    }

    public Teacher getTeacherDetails(int id ){
        return repository.getTeacherDetails(id);
    }
}

Now let's create the Repository layer class,

[email protected]
public class ResourceService{

    @Autowired
    ResourceRepository repository;

    public void saveTeacher(Teacher teacher){
        repository.saveTeacher(teacher);
    }

    public Teacher getTeacherDetails(int id ){
        return repository.getTeacherDetails(id);
    }
}

The above two classes display the Service and Repository layers and are created in the com.tutorial.studytonight.service and com.tutorial.studytonight.repository packages respectively.

Strucure of the Developed Project setup:

Let's explore the structure of our project so far,

The above Figure 8.2 displays the structure of the developed setup. To run the application, right click on Application.java and click on Run As Java Application.

The above Figure 8.3 displays that the Application was started and ready to receive requests. Let us test the application using the Rest client Postman.

The above figure is the screenshot of POSTMAN observe that the URL was passed as localhost:8080/saveTeacher which is being used to save the teacher details(refer to the end-points in ResourceController class).

Select the Body tab, followed by the radio-button raw, place the above JSON structure as displayed in the POSTMAN and hit the SEND button (top right corner). We can see that the status received is 200 OK from the bottom right-corner which indicates that the request was successful.

The JSON structure will be mapped to the Teacher instance which is the parameter in the end-point (refer to ResourceController class). The @RequestBody is the annotation which helps in binding the JSON structure to Teacher class instance.

Note that instead of using a Database, we are storing the details in a HashMap, Integer is the Key we declared above which should be a unique value. So, when making multiple requests, make sure that the Integer value is unique.

The above figure displays the GET request from the POST MAN and observe that the ID value was passed as a PathVariable in the URL.

To describe about pathvariable, refer to ResourceController class created above, It has the end-point /getTeacherDetails/{id}. The PathVariable here is id which is enclosed in the curly-braces. Spring-boot provides an annotation @PathVariable which is used to capture the PathVariables in URL.

We are passing this ID to repository and getting the value from the map. Observe that value is nothing but an instance of the Teacher class which is returned and can be seen in the Response Body of the POSTMAN.

Conclusion: In this tutorial, we have seen the development of REST-API development using spring-boot and testing using Rest-client.