ranyeli
9/3/2017 - 8:11 PM

sample api with spring boot using delete + put + get + post

sample api with spring boot using delete + put + get + post

package com.project.api;

import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.project.dao.GenericDao;
import com.project.model.Customer;

@RestController
public class TestApi {
	
	@Autowired
	private GenericDao<Customer> _dao;
	
	@GetMapping("api/test")
	public String getTest() {
		return "Test was successfull";
	}
	
	@PostMapping("api/customer/add")
	public void addCustomer(@RequestBody Customer customer) {
		_dao.save(customer);
	}
	
	@PostMapping("api/customers/add")
	public void addCustomer(@RequestBody List<Customer> customer) {
		_dao.saveAll(customer);
	}
	
	@DeleteMapping("api/customer/delete")
	public void deleteCustomer(@RequestBody Customer customer) {
		_dao.delete(customer);
	}
	
	@PutMapping("api/customer/update")
	public void updateCustomer(@RequestBody Customer customer) {
		_dao.update(customer);
	}
	
	@GetMapping("api/customer/{id}")
	public Customer getCustomer(@PathVariable("id") long id) {
		return _dao.findById(Customer.class, id);
	}
	
	@GetMapping("api/customers")
	public List<Customer> getCustomers(
			@RequestParam(value="offset", required=false) Integer offset, 
			@RequestParam(value="limit", required=false) Integer limit){
		return _dao.findAll(Customer.class, offset, limit);
	}

}