Spring Boot Sample Rest API
Membuat simple REST API pertama menggunakan spring boot dengan API spek berikut:
- Membuat dan menampilkan List Buku
- Membuat dan menampilkan data buku berdasarkan bookId
- Buat package controller seperti berikut

2. Buat class BookController

3. Buat Package model dan class BookResponse

package com.hyvercode.spring.model.response;
import java.io.Serializable;
public class BookResponse implements Serializable {
private int bookId;
private String bookName;
public BookResponse(int bookId, String bookName) {
this.bookId = bookId;
this.bookName = bookName;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
}
4. Buat API “books” dan endpoint untuk menampilkan data buku dan mengambil data buku berdasarakn bookId

package com.hyvercode.spring.controller;
import com.hyvercode.spring.model.response.BookResponse;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
@RestController
@RequestMapping("/books")
public class BookController {
private final List<BookResponse> bookResponses = Arrays.asList(new BookResponse(1,"Java Basic"),new BookResponse(2,"Spring Boot"));
@GetMapping(value = "",produces = MediaType.APPLICATION_JSON_VALUE)
public List<BookResponse> getBooks(){
return bookResponses.stream().toList();
}
@GetMapping(value = "/{bookId}",produces = MediaType.APPLICATION_JSON_VALUE)
public List<BookResponse> getBook(@PathVariable("bookId") int bookId){
return bookResponses.stream()
.filter(bookResponse -> bookResponse.getBookId()==bookId)
.toList();
}
}
Selanjutnya jalankan aplikasi dengan perintah berikut:
mvn spring-boot:run
Bukan browser atau Postman akses url http://localhost:8080/books

Bukan browser atau Postman akses url http://localhost:8080/books/1


Sample source code bisa di download di github-hyvercode