Spring Boot RESTful web service JSON example

Spring Boot comes with all the needed components for creating RESTful web services. Here we will see how easily we can build a simple Spring Boot application which will provide web services for CRUD operations i.e. Create, Retrieve, Update and Delete operations using HTTP POST, GET, PUT and DELETE method respectively.

To keep the application simple, we will not use any database. Instead just use a HashMap to store the data objects through a Service layer class.

Now let us see the source code straight:

1. build.gradle
buildscript {
    ext {
        springBootVersion = '1.5.3.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

group 'com.firstfewlines'
version '1.0.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.springframework.boot:spring-boot-starter-web:$springBootVersion"
    compile "org.springframework.boot:spring-boot-devtools:$springBootVersion"
}


2. StudentController.java
package com.firstfewlines.controller;

import com.firstfewlines.domain.Student;
import com.firstfewlines.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/api")
class StudentController {

    @Autowired
    StudentService studentService;

    @RequestMapping(value = "/student/{rollNo}", method = RequestMethod.GET)
    Student getStudent(@PathVariable("rollNo") int rollNo) throws Exception {
        return studentService.getStudent(rollNo);
    }

    @RequestMapping(value = "/student", method = RequestMethod.GET)
    Iterable<Student> getStudents() {
        return studentService.getStudents();
    }

    @RequestMapping(value = "/student", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseStatus(value = HttpStatus.OK)
    void addStudent(@RequestBody Student student) throws Exception {
        studentService.addStudent(student);
    }

    @RequestMapping(value = "/student/{rollNo}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseStatus(value = HttpStatus.OK)
    void updateStudent(@PathVariable("rollNo") int rollNo, @RequestBody Student student) throws Exception {
        student.setRollNo(rollNo);
        studentService.updateStudent(student);
    }

    @RequestMapping(value = "/student/{rollNo}", method = RequestMethod.DELETE)
    @ResponseStatus(value = HttpStatus.OK)
    void deleteStudent(@PathVariable("rollNo") int rollNo) throws Exception {
        studentService.deleteStudent(rollNo);
    }
}


3. Student.java
package com.firstfewlines.domain;

public class Student {

    int rollNo;
    String name;
    int totalMarks;

    public int getRollNo() {
        return rollNo;
    }

    public void setRollNo(int rollNo) {
        this.rollNo = rollNo;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getTotalMarks() {
        return totalMarks;
    }

    public void setTotalMarks(int totalMarks) {
        this.totalMarks = totalMarks;
    }
}


4. StudentService.java
package com.firstfewlines.service;

import com.firstfewlines.domain.Student;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class StudentService {

    Map<Integer, Student> students = new HashMap<>();

    public void addStudent(Student student) throws Exception {
        if(students.containsKey(student.getRollNo())) {
            throw new Exception("Student already exists");
        }
        else {
            students.put(student.getRollNo(), student);
        }
    }

    public Iterable<Student> getStudents(){
        return students.values();
    }

    public Student getStudent(int rollNo) throws Exception {

        if(students.containsKey(rollNo)) {
            return students.get(rollNo);
        }
        else {
            throw new Exception("Student not found");
        }
    }

    public void updateStudent(Student student) throws Exception {
        if(students.containsKey(student.getRollNo())) {
            students.put(student.getRollNo(), student);
        }
        else {
            throw new Exception("Student not found");
        }
    }

    public void deleteStudent(int rollNo) throws Exception {
        if(students.containsKey(rollNo)) {
            students.remove(rollNo);
        }
        else {
            throw new Exception("Student not found");
        }
    }

}


5. SpringBootRestExample.java
package com.firstfewlines;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootRestExample {
    public static void main(String [] argv){
        SpringApplication.run(SpringBootRestExample.class, argv);
    }
}


Download complete source code:


How to run the application?

  • Make sure you have latest version of Gradle installed and PATH is configured.
  • Download the attached source code zip file and unzip it to your local folder.
  • Go to the directory where you unzipped the file i.e. where the build.gradle is there
  • Run gradle clean bootRun command
  • The web service should be up at http://localhost:8080/

Alternatively, you can use IntelliJ IDEa or Eclipse to import the Gradle project and run from there.


How to test:

To test the web services, we can use Postman apps from Google chrome or curl in linux shell. Postman will be easier to use as it has intuitive graphics user interface.


References:


Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus