Spring boot rest service example

Environment used

Eclipse

Maven

JDK 1.8

Spring Boot 1.4.2

Spring 4.3

This post shows you how to use @GetMapping, @PostMapping, @PathMapping, @PutMapping, @DeleteMapping

Spring boot restful web services JSON example

@Controller

package com.candidjava.spring.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.service.UserService;

@RestController
@RequestMapping(value={"/user"})
public class UserController {
    @Autowired
    UserService userService;


    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getUserById(@PathVariable("id") int id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }

    @PostMapping(value="/create",headers="Accept=application/json")
    public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder){
        System.out.println("Creating User "+user.getName());
        userService.createUser(user);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }

    @GetMapping(value="/get", headers="Accept=application/json")
    public List<User> getAllUser() {
        List<User> tasks=userService.getUser();
        return tasks;

    }

    @PutMapping(value="/update", headers="Accept=application/json")
    public ResponseEntity<String> updateUser(@RequestBody User currentUser)
    {
        User user = userService.findById(currentUser.getId());
        if (user==null) {
            return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
        }
        user.setId(currentUser.getId());
        user.setName(currentUser.getName());
        user.setCountry(currentUser.getCountry());
        userService.update(user);
        return new ResponseEntity<String>(HttpStatus.OK);
    }

    @DeleteMapping(value="/{id}", headers ="Accept=application/json")
    public ResponseEntity<User> deleteUser(@PathVariable("id") int id){
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        userService.deleteUserById(id);
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }

    @PatchMapping(value="/{id}", headers="Accept=application/json")
    public ResponseEntity<User> updateUserPartial(@PathVariable("id") int id, @RequestBody User currentUser){
        User user = userService.findById(id);
        if(user ==null){
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }

        userService.updatePartially(currentUser, id);
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }
}

Bean class

package com.candidjava.spring.bean;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User {

    private int id;
    private String country;
    private String name;
    public User(){
        id=0;
    }
    public User(int id, String name, String country){
        this.id = id;
        this.name = name;
        this.country = country;
    }
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }

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

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String toString()
    {
        return"name:"+name;
    }

}

Service Interface

package com.candidjava.spring.service;

import java.util.List;

import com.candidjava.spring.bean.User;

public interface UserService {
    public void createUser(User user);
    public List<User> getUser();
    public User findById(int id);
    public void update(User user);
    public void deleteUserById(int id);
    public void updatePartially(User user, int id);
}

Service Implementation with dummy data

package com.candidjava.spring.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.stereotype.Service;

import com.candidjava.spring.bean.User;

@Service
public class UserServiceImp implements UserService {

    private static List<User> users;

    static {
        users = dummyUsers();
    }

    public List<User> getUser() {
        // TODO Auto-generated method stub
        return users;
    }

    public User findById(int id) {
        // TODO Auto-generated method stub
        for (User user : users) {
            if (user.getId() == id) {
                return user;
            }
        }
        return null;
    }

    public void createUser(User user) {
        // TODO Auto-generated method stub
        users.add(user);
    }

    public void deleteUserById(int id) {
        // TODO Auto-generated method stub
        Iterator<User> it = users.iterator();
        while (it.hasNext()) {
            User user = (User) it.next();
            if (user.getId() == id) {
                it.remove();
            }
        }
    }

    public void updatePartially(User currentUser, int id) {
        for (User user : users) {
            if (user.getId() == id) {
                if (currentUser.getCountry() != null) {
                    user.setId(id);
                    user.setCountry(currentUser.getCountry());
                }
                user.setName(user.getName());
                update(user);
            }
        }

    }

    public void update(User user) {
        // TODO Auto-generated method stub
        int index = users.indexOf(user);
        users.set(index, user);
    }

    private static List<User> dummyUsers() {
        // TODO Auto-generated method stub
        List<User> users = new ArrayList<User>();
        users.add(new User(14221, "John", "INDIA"));
        users.add(new User(14222, "Ben", "UK"));
        users.add(new User(14223, "Andrew", "INDIA"));
        users.add(new User(14224, "Samuael", "USA"));
        return users;
    }

}

 

Spring Boot Application.java

package com.candidjava;

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

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

}

 

Spring boot application.properties

logging.level.org.springframework.web=DEBUG

Maven dependencies pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.candidjava.spring</groupId>
    <artifactId>Spring-Boot-RestCrud</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring-Boot-RestCrud Maven Webapp</name>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath />
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Tomcat embedded container-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <finalName>Spring-Boot-RestCrud</finalName>
    </build>
</project>

 

How to run

mvn spring-boot:run

 

Rest Endpoints

GET –> http://localhost:8080/user/get

Download

Spring boot rest curd example maven

References

Spring boot rest – Official website

 

Leave a Reply

Your email address will not be published. Required fields are marked *