Total Pageviews

2018/10/14

[Spring Boot] How to create a simple restful service

Scenario



How-To
Rest Controller:
package springboot.rest.controller;

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

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
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 com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import springboot.rest.vo.Book;

@RestController
@RequestMapping("/api/books")
public class BookController {

    private static List<Book> books = new ArrayList<Book>();

    static {
        Book book1 = new Book("1501108085", "Peaks and Valleys", "Spencer Johnson M.D.");
        Book book2 = new Book("0062102419", "How Will You Measure Your Life?", "Clayton M. Christensen");
        Book book3 = new Book("111908833X", "Bogle On Mutual Funds", "John C. Bogle");

        books.add(book1);
        books.add(book2);
        books.add(book3);
    }

    @GetMapping
    public String getBooks() throws JsonProcessingException {
        String booksJSON = "";
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            booksJSON = objectMapper.writeValueAsString(books);
        } catch (JsonProcessingException e) {
            throw e;
        }
        return booksJSON;
    }

    @PostMapping(value = "/add")
    public String addBook(@RequestBody Book book) throws JsonProcessingException {
        books.add(book);

        String booksJSON = "";
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            booksJSON = objectMapper.writeValueAsString(books);
        } catch (JsonProcessingException e) {
            throw e;
        }
        return booksJSON;
    }

    @PutMapping(value = "/update")
    public String updateBook(@RequestBody Book book) throws JsonProcessingException {
        books.stream().forEach(b -> {
            if (b.getName().equals(book.getName())) {
                b.setIsbn(book.getIsbn());
            }
        });
        String booksJSON = "";
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            booksJSON = objectMapper.writeValueAsString(books);
        } catch (JsonProcessingException e) {
            throw e;
        }
        return booksJSON;
    }

    @DeleteMapping(value = "/delete/{isbn}")
    public String deleteBook(@PathVariable String isbn) throws JsonProcessingException {
        books.removeIf(b -> b.getIsbn().equals(isbn));
        String booksJSON = "";
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            booksJSON = objectMapper.writeValueAsString(books);
        } catch (JsonProcessingException e) {
            throw e;
        }
        return booksJSON;
    }
}


Value object:
package springboot.rest.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Book {

    private String isbn;
    private String name;
    private String author;
    
}


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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>springboot</groupId>
    <artifactId>rest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>rest</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <jackson.version>2.9.5</jackson.version>
        <springboot.version>2.0.0.RELEASE</springboot.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${springboot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <version>${springboot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>



[Test Result] Get all books


[Test Result] Add a new book


[Test Result] Update a book


[Test Result] Delete book by ISBN


No comments: