Mastering Spring Boot REST API: A Beginner's Guide - Part 2

Spring Boot - Rest API

If you haven't had a chance to read the first part of this guide, I'd recommend taking a look at it before diving into this continuation.

Part 1 - https://karthikeyanrm.hashnode.dev/spring-boot-rest-api-basics-part-1

RequestMapping :-

This is used to to map requests to controllers methods to match the URL, method, request parameters etc. It can be used either at one of the below levels

  • Class - To define the base URL for all the REST API's.

  • Method level - To narrow down to specific endpoint mapping and below are shortcuts

    • @GetMapping – maps all the HTTP Get requests onto the specific handler method.

      @PostMapping – maps all the HTTP Post requests onto the specific handler method.

      @PutMapping – handles all the HTTP Put requests onto the specific handler method.

      @DeleteMapping – handles all the HTTP delete requests onto the specific handler method.

      Apart from the above, we also have Patch.

Table showing the operations

Http MethodOperation
GetRead
PostCreate
PutUpdate
DeleteDelete

Create a Simple Spring Boot REST API

Let's start writing some code with a simple method that makes use of the @GetMapping method to return a string.

URL to test: localhost:8080/helloWorld in your favourite browser, and you'll get the output as "helloWorld". It's as simple as that.

@GetMapping("/helloWorld")
public String getHelloWorld(){
    return "helloWorld";
}

Create a REST API that returns a Java Bean

To create a REST API that returns a Java Bean, first create an entity class named Student with fields as id, name, and degree:, I'm not annotating the class and its a home-work for anyone who is following this guide :)

public class Student{
    private Long id;
    private String name;
    private String degree;
}

Now, let us make use of the Student class and use it in the REST API method

@GetMapping("/student")
public String getStudent(){
    Student student = new Student(1, "Murugan", "B.Sc");
    return student;
}

URL to test : I hope you're now familiar with testing the method which we've implemented. To test the method, go to http://localhost:8080/student in your browser, and you'll see the output with the student details that were given as input.

Create a REST API that returns a List

The only difference between the previous method and this one would be the list of students that have to be added.

@GetMapping("/students")
public List<Student> getStudents(){
    List<Student> students = new ArrayList<>();
    students.add(new Student(1, "Murugan", "B.Sc"));
    students.add(new Student(2, "Shiva", "M.Sc"));
    return students;
}

URL to test : To test the method, simply go to http://localhost:8080/students in your browser, and you'll see the output with the list of students that were given as input.

Create a REST API with a Path Variable

Path Variable - Bind the value from URI template variable to method argument. If the path-variable is id and in case if we want to use a different variable then rewrite the method argument as @PathVariable ("id") int studentId.

@GetMapping("/student/{id}")
public Student getStudentPathVariable(@PathVariable int id){
    return new Student(id, "Ganesh", "B.E");
}

In case of multiple path variables, pass them one after another in the method argument as comma separated values.

URL to test : To test the method, visit http://localhost:8080/student/1 in your browser, and you'll see the output along with the id that we passed in the URL as a path variable.

Create a REST API with a Request Param

Request Param - Handles the query parameter in a request URL

@GetMapping("/students/query")
public Student getStudentPathVariable(@RequestParam int id){
    return new Student(id, "Adi", "M.E");
}

If there is a need to use multiple query params, then simply pass them one after another in the method argument as comma separated values.

URL to test : To test the method, visit http://localhost:8080/student/query?id=24 in your browser, and you'll see the output along with the id.

Path VariableRequest Param
Used to bind the value of URI template variable into method arg.Extract the value of query parameters in the URL.
Extract the values from the URI path, its not encodedIts encoded.
Eg -> students/ab+c , then output is ab+cEg -> students/query?id=ab+c , then output is ab c

PostMapping

Let us create a new student with the use of PostMapping. We would like to send the response code as 201 (CREATED) instead of 200 which is the default one.

@PostMapping("/students/create")
@ResponseStatus(HttpStatus.CREATED) // to send response as 201
public String createStudent(@RequestBody Student student){
    System.out.println(student.getId(), student.getName(), student.degree());
    return student;
}

PutMapping

There would be always a requirement to update an existing student which can be done by the use of PutMapping.

@PutMapping("/students/{id}/update")
public String updateStudent(@RequestBody Student student, @PathVariable("id") int studentId){
    System.out.println(student.getId(), student.getName(), student.degree());
    return student;
}

DeleteMapping

And no surprises in guessing the last request mapping which is to delete the student. In this one, client do not need to send any data in the request body.

@DeleteMapping("/students/{id}/delete")
public String deleteStudent(@PathVariable("id") int studentId){
    System.out.println(studentId);
    return "student deleted with id:" + studentId;
}

Conclusion:

That's a wrap of the part-2 and stay tuned for more articles.

Meanwhile, if you are preparing for Java-Spring Boot developer interviews, then here are a few books from javinpaul&@javarevistited publications