Suresh Rohan's Blog

This blog is all about Java, J2EE,Spring, Angular, React JS, NoSQL, Microservices, DevOps, BigData, Tutorials, Tips, Best practice, Interview questions, Views, News, Articles, Techniques, Code Samples, Reference Application and much more

Wednesday, January 24, 2018

Build an API with Spring Boot

Image result for wallpaper

Build an API with Spring Boot


To get started with Spring Boot, navigate to start.spring.io. In the “Search for dependencies” field, select the following:
  • DevTools: Provides auto-reloading of your application when files change
  • H2: An in-memory database
  • JPA: Standard ORM for Java
  • Rest Repositories: Allows you to expose your JPA repositories as REST endpoints
  • Web: Spring MVC with Jackson (for JSON), Hibernate Validator, and embedded Tomcat
start.spring.io

Open the “server” project in your favorite IDE and run DemoApplication or start it from the command line using ./mvnw spring-boot:run.
Create a com.example.demo.beer package and a Beer.java file in it. This will be the entity that holds your data.

package com.example.demo.beer;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Beer {

    @Id
    @GeneratedValue
    private Long id;
    private String name;

    public Beer() {}

    public Beer(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Beer{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}


Add a BeerRepository class that leverages Spring Data to do CRUD on this entity.
package com.example.demo.beer;

import org.springframework.data.jpa.repository.JpaRepository;

interface BeerRepository extends JpaRepository<Beer, Long> {
}
Add a BeerCommandLineRunner that uses this repository and creates a default set of data.
package com.example.demo.beer;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.stream.Stream;

@Component
public class BeerCommandLineRunner implements CommandLineRunner {

    private final BeerRepository repository;

    public BeerCommandLineRunner(BeerRepository repository) {
        this.repository = repository;
    }

    @Override
    public void run(String... strings) throws Exception {
        // Top beers from https://www.beeradvocate.com/lists/top/
        Stream.of("Kentucky Brunch Brand Stout", "Good Morning", "Very Hazy", "King Julius",
                "Budweiser", "Coors Light", "PBR").forEach(name ->
                repository.save(new Beer(name))
        );
        repository.findAll().forEach(System.out::println);
    }
}
Rebuild your project and you should see a list of beers printed in your terminal.
Beers printed in terminal
Add a @RepositoryRestResource annotation to BeerRepository to expose all its CRUD operations as REST endpoints.
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource
interface BeerRepository extends JpaRepository<Beer, Long> {
}
Add a BeerController class to create an endpoint that filters out less-than-great beers.
package com.example.demo.beer;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class BeerController {
    private BeerRepository repository;

    public BeerController(BeerRepository repository) {
        this.repository = repository;
    }

    @GetMapping("/good-beers")
    public Collection<Beer> goodBeers() {

        return repository.findAll().stream()
                .filter(this::isGreat)
                .collect(Collectors.toList());
    }

    private boolean isGreat(Beer beer) {
        return !beer.getName().equals("Budweiser") &&
                !beer.getName().equals("Coors Light") &&
                !beer.getName().equals("PBR");
    }
}
Re-build your application and navigate to http://localhost:8080/good-beers. You should see the list of good beers in your browser.
Good Beers JSON
You should also see this same result in your terminal window when using HTTPie.
http localhost:8080/good-beers 

No comments:

Post a Comment