Skip to main content

Restaurant API using SpringBoot

 Restaurant API using Spring Boot




Controller - Add @RestController annotation the class

    @Autowired

private RestaurantService restaurantService;


//to create a restaurant

@PostMapping("/restaurant/add")

public ResponseEntity<Object> postRestaurant(@RequestBody Restaurant restaurant){

return restaurantService.postRestaurant(restaurant);

}

//to get a restaurant by id

@GetMapping("/restaurant/get/{id}")

public ResponseEntity<Object>getRestaurantById(@PathVariable int id){

return restaurantService.getRestaurantById(id);

}

//to get restaurants which are equal to or greater than the given rating

@GetMapping("/restaurant/ratings")

public ResponseEntity<Stream<Restaurant>> getGreaterRating(@RequestParam("rating") Double rating){

return restaurantService.getGreaterRating(rating);

}

//to get the Sorted Restaurant with the given param value

@GetMapping("/restaurant/sortBy")

public ResponseEntity<Object> getRestaurantBySort(@RequestParam("value") String value){

return restaurantService.getRestaurantBySort(value);

}

//to update the restaurant's vote and rating by id as PathVariable and restaurant Object

@PutMapping("/restaurant/{id}")

public ResponseEntity<Object> updateRestaurant(@PathVariable int id, @RequestBody Restaurant restaurant){

return restaurantService.updateRestaurant(id, restaurant);

}

// to delete the restaurant by using id as PathVariable

@DeleteMapping("/restaurant/{id}")

public ResponseEntity<Object> deleteRestaurantById(@PathVariable int id){

return restaurantService.deleteRestaurantById(id);

}

// manually seed the h2 database

@GetMapping("/restaurant/seed")

public ResponseEntity<Object> getResturantSeed(){

return restaurantService.seedRestaurant();

}

@GetMapping("/restaurant/getall")

public ResponseEntity<Object> getAllResturant(){

return restaurantService.allRestaurant();

}


Model - Add @Entity annotation to the class

    @Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(unique = true)

private int id;


private String name;

private String city;

private int estimatedCost;

private double averageRating;

private int votes;

private long contactNo;



Repository - Add @Repository annotation to the class

public interface RestaurantRepository extends JpaRepository<Restaurant,Integer> {

List<Restaurant> findByAverageRatingGreaterThanEqual(double rating);

@Query(value = "SELECT max(id) FROM Restaurant")

public int getMaxId();

}


Services - Add @Service annotation to to the class

private static final Logger log = Logger.getLogger(RestaurantController.class.getName());

/*

* Implement the business logic for the RestaurantService operations in this

* class Make sure to add required annotations

*/

@Autowired

private RestaurantRepository restaurantRepository;

// to create a restaurant

// created->201

// badRequest()->400

public ResponseEntity<Object> postRestaurant(Restaurant restaurant) {

if (restaurant == null) {

return ResponseEntity.badRequest().build();

}

log.info(restaurant.toString());

restaurantRepository.save(restaurant);

return ResponseEntity.status(HttpStatus.CREATED).build();

}


// to get a restaurant by id

// ok()->200

// badRequest()->400

public ResponseEntity<Object> getRestaurantById(int id) {

Restaurant restaurant = restaurantRepository.findById(id).orElse(null);

if (restaurant == null) {

return ResponseEntity.badRequest().build();

}

return ResponseEntity.ok(restaurant);

}

// to get restaurants which are equal to or greater than the given rating

// ok()->200

// badRequest()->400

public ResponseEntity<Stream<Restaurant>> getGreaterRating(Double rating) {

List<Restaurant> matchingRestaurants = restaurantRepository.findByAverageRatingGreaterThanEqual(rating);

if (matchingRestaurants.isEmpty()) {

return ResponseEntity.badRequest().build();

}

Stream<Restaurant> restaurantStream = matchingRestaurants.stream();

return ResponseEntity.ok().body(restaurantStream);

}


// to get the Sorted Restaurant with the given param value

// ok()->200

// badRequest()->400

public ResponseEntity<Object> getRestaurantBySort(String value) {

List<Restaurant> restaurants = restaurantRepository.findAll();

if(restaurants.isEmpty()) {

return ResponseEntity.badRequest().build();

}

switch (value) {

case "id":

restaurants.sort(Comparator.comparing(Restaurant::getId));

break;

case "name":

restaurants.sort(Comparator.comparing(Restaurant::getName));

break;

case "city":

restaurants.sort(Comparator.comparing(Restaurant::getCity));

break;

case "estimatedCost":

restaurants.sort(Comparator.comparingInt(Restaurant::getEstimatedCost));

break;

case "averageRating":

restaurants.sort(Comparator.comparingDouble(Restaurant::getAverageRating));

break;

case "votes":

restaurants.sort(Comparator.comparingInt(Restaurant::getVotes));

break;

case "contactNo":

restaurants.sort(Comparator.comparingLong(Restaurant::getContactNo));

break;

default:

return ResponseEntity.badRequest().build();

}

return ResponseEntity.ok(restaurants);

}

// to delete the restaurant by using id as PathVariable

// ok()->200

// badRequest()->400

public ResponseEntity<Object> deleteRestaurantById(int id) {

if (!restaurantRepository.existsById(id)) {

return ResponseEntity.badRequest().build();

}

restaurantRepository.deleteById(id);

return ResponseEntity.ok().build();

}


// to update the restaurant's vote and rating by id as PathVariable and

// restaurant Object

// ok()->200

// badRequest()->400

public ResponseEntity<Object> updateRestaurant(int id, Restaurant restaurant) {

Restaurant fetchedRestaurant = restaurantRepository.findById(id).orElse(null);

if(fetchedRestaurant == null) {

return ResponseEntity.badRequest().build();

}

restaurant.setId(id);

if(!StringUtils.hasText(restaurant.getName())) {

restaurant.setName(fetchedRestaurant.getName());

}

if(!StringUtils.hasText(restaurant.getCity())) {

restaurant.setCity(fetchedRestaurant.getCity());

}

if(restaurant.getEstimatedCost() == 0) {

restaurant.setEstimatedCost(fetchedRestaurant.getEstimatedCost());

}

if(restaurant.getAverageRating() == 0) {

restaurant.setAverageRating(fetchedRestaurant.getAverageRating());

}

if(restaurant.getVotes() == 0) {

restaurant.setVotes(fetchedRestaurant.getVotes());

}

if(restaurant.getContactNo() == 0) {

restaurant.setContactNo(fetchedRestaurant.getContactNo());

}

restaurantRepository.save(restaurant);

return ResponseEntity.ok(restaurant);

}

// done by me to manually seed the h2 database

public ResponseEntity<Object> seedRestaurant(){

postRestaurant(new Restaurant(1, "Accord","Delhi",40000,4.5,98,7547898765L));

postRestaurant(new Restaurant(2, "Plaso", "Chennai", 50000, 4.1, 100, 9854728626L));

postRestaurant(new Restaurant(3, "MassHotel", "Mumbai",20000,3.5,66,8637954894L));

postRestaurant(new Restaurant(4, "GetToGather", "Kerala",10000,2.9,459,6383475894L));

return ResponseEntity.ok().build();

}

public ResponseEntity<Object> allRestaurant(){

List<Restaurant> restaurants = restaurantRepository.findAll();

if(restaurants.isEmpty()) {

return ResponseEntity.notFound().build();

}

return ResponseEntity.ok(restaurants);

}


Configuration
Add SQL insert statements to data.sql if insert during time of application startup, for model with camel case 'sampleTable' table name would be 'sample_table'.

# added below

spring.h2.console.path=/h2

spring.datasource.inititalization-mode=always


# Already present

spring.jpa.defer-datasource-initialization=true

spring.datasource.url=jdbc:h2:mem:testdb

spring.h2.console.enabled=true



Comments

Popular posts from this blog

Kubernetes2

  Challenge 2 ConfigMaps: Step-1: To create a ConfigMap named 'fresco-config' with the key-value pair SERVER_URL= https://www.fresco.me , use the following command: kubectl create configmap fresco-config --from-literal=SERVER_URL=https://www.fresco.me To verify if the ConfigMap is created, use the following command: kubectl get configmap fresco-config Step-2: To create an nginx pod with the environmental variable SERVER_URL_ENV using the ConfigMap created earlier, use the following YAML template: apiVersion: v1 kind: Pod metadata: name: fresco-nginx-pod spec: containers: - name: fresco-nginx-container image: nginx env: - name: SERVER_URL_ENV valueFrom: configMapKeyRef: name: fresco-config key: SERVER_URL Deploy the above file you can name it deployment.yaml and use the command: kubectl apply -f deployment.yaml To test your configuration by executing the following command:

Kubernetes1

  Challenge 1 Welcome to the Kubernetes challenge, your task is to follow the below steps and complete them successfully. Environment Setup Check whether docker & minikube are properly installed and configured. Start Minikube and execute this command to sync host docker with minikube docker minikube -p minikube docker-env and eval $(minikube docker-env) Step-1 Create a pod object using kubectl run command with google's sample image: gcr.io/google-samples/kubernetes-bootcamp:v1 and expose it on port 8080, name the pod as firstapp. Check if the pod creation is successful by running the command: kubectl get pod firstapp Step-2 Expose the application to the local VM by creating a Service object of type NodePort. Check if the service is created by running the command: kubectl get svc firstapp Step-3 Create another deployment using a 'YAML' file, create a deployment.yaml file that contains information of the number of replicas and the images to be

Docker + Docker Compose + Ansible

 Docker + Docker Compose + Ansible ----------------------------------------------------------------------------------------------------------------------------- Flask Application Deployment using Ansible roles and Docker-Compose 1. Run the "setup.sh" file given in the path to install the required dependencies before starting the challenge. 2. A Flask application named "app.py" is given in the path . 3. Create an Ansible role named "Installation" in the path "/etc/ansible/roles" to install docker-compose. 4. Write an Ansible playbook named "creation.yaml" in the path , to perform the following tasks: 1. Using "file" and "copy" modules, create a Multi-stage "Dockerfile" in the path to  - Dockerize the given Flask application with "python:alpine3.7" as its base image, using the given 'requirements.txt' file.  - Build an image using "postgres" as its base image. 2. Using &q