Skip to content

Instantly share code, notes, and snippets.

@alex-bezverkhniy
Created January 31, 2018 21:30
Show Gist options
  • Save alex-bezverkhniy/8aa6086370c60298c0183b1668fb9ec8 to your computer and use it in GitHub Desktop.
Save alex-bezverkhniy/8aa6086370c60298c0183b1668fb9ec8 to your computer and use it in GitHub Desktop.
Simple REST server (Spring Boot, Groovy)
@Grab(group='org.springframework.boot', module='spring-boot-starter-web', version='1.1.7.RELEASE')
@Grab(group='org.springframework.boot', module='spring-boot-starter-actuator', version='1.1.7.RELEASE')
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
GET /todos/ Reads all tasks.
POST /todos/ Creates a new task.
GET /todo/:id Reads a task.
PUT /todo/:id Updates a task.
DELETE /todo/:id Destroys a task.
**/
@Controller
@RequestMapping(value="/api/todos")
@EnableAutoConfiguration
public class TodosController {
private static final Logger logger = LoggerFactory.getLogger(TodosController.class)
private dataTable = [[
"id": 1,
"title": "Learn Groovy",
"completed": false
],
[
"id": 2,
"title": "Learn ES6",
"completed": false
]]
@RequestMapping(value="/", method=RequestMethod.GET)
@ResponseBody
Map getAllTasks() {
logger.info("Get all todos")
return [
"total": dataTable.size(),
"page": 1,
"perPage": 10,
"todos": dataTable]
}
@RequestMapping(value="/", method=RequestMethod.POST)
@ResponseBody
Integer addTask(@RequestBody Map todo) {
logger.info("Add new todo: ${todo}")
todo.id = dataTable.size() + 1
dataTable.push(todo)
return todo.id
}
@RequestMapping(value="/{todoId}", method=RequestMethod.GET)
@ResponseBody
Map getTask(@PathVariable("todoId")Integer todoId) {
logger.info("Get todo: ${todoId}")
return dataTable.get(todoId - 1)
}
@RequestMapping(value="/{todoId}", method=RequestMethod.PUT)
@ResponseBody
Map updateTask(@PathVariable("todoId")Integer todoId, @RequestBody Map todo) {
logger.info("Update todo: ${todoId} with: ${todo}")
if (dataTable.get(todoId - 1)) {
todo.id = todoId
dataTable.set(todoId - 1, todo)
}
return todo
}
@RequestMapping(value="/{todoId}", method=RequestMethod.DELETE)
@ResponseBody
Map removeTask(@PathVariable("todoId")Integer todoId) {
println("Delete todo: ${todoId}")
if (dataTable.get(todoId - 1)) {
return dataTable.remove(todoId - 1)
}
return false
}
public static void main(String[] args) throws Exception {
SpringApplication.run(TodosController.class, args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment