spring boot rest api example tutorial presents a todo list rest api created using spring boot 2.
The api presents 4 endpoints :
- GET api endpoint : returns all the tod list
- POST api endpoint : creates a todo and ad dit to the todo list
- PUT api endpoint : updates a todo
- DELETE api endpoint : deletes a todo
In this spring boot rest api example, we don’t use a
database. So, the todo list is stored in an arrayList in the controller that
exposes the todo list REST API.
Spring Boot 2 REST API maven dependencies
In this project we use spring-boot-starter-web to expose the rest API and spring-boot-starter-test to make unit tests. In this spring boot rest api example, we don’t focus on unit testing because we will create a dedicated tutorial for unit testing a REST API.
The maven POM file is the following :
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javasneo</groupId> <artifactId>todo-list</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>todo-list</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Spring Boot 2 REST API configuration
This class is a JAVA configuration class marked with the
annotation @Configuration. It enables Spring MVC and declares that our
endpoints supports all the hTTP methods (GET, POST, PUT, DELETE, PATCH).
The code of the configuration class is the following :
package com.javasneo.todolist.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedMethods("GET", "PUT", "POST", "DELETE", "PATCH"); } }; } }
Spring Boot 2 REST API model
In this spring boot rest api example, we use two classes as our model :
- The Todo class
- The TodoListResponse class : it represent the response of Getting all the Todos endpoint
The source code of those classes is the following :
package com.javasneo.todolist.model; public class Todo { private int id; private String name; private String description; public Todo() { } public Todo(int id, String name, String description) { this.id = id; this.name = name; this.description = description; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public String getDescription() { return description; } public void setName(String name) { this.name = name; } public void setDescription(String description) { this.description = description; } }
TodoListResponse.java
package com.javasneo.todolist.model; import java.util.ArrayList; public class TodoListResponse { private ArrayListtodos; public ArrayList getTodos() { return todos; } public void setTodos(ArrayList todos) { this.todos = todos; } }
Spring Boot 2 REST API controller
This controller presents the four REST endpoints that we
spoke about above.
The data in this REST API controller is stored in an
ArrayList that we initialize in the controller ‘s constructor.
In order to make a controller as a REST controller, we annotate it using @RestController and in order to mark a method in the controller as a REST endpoint we annotate it using @RequestMapping annotation.
In the @RequestMapping annotation, we indicate the http method used by that endpoint.
In order to generate an id for a newly added Todo, the controller uses a static variable called id that it increments for the newly created Todo.
The source code of the REST controller is the following :
package com.javasneo.todolist.controller; import com.javasneo.todolist.model.Todo; import com.javasneo.todolist.model.TodoListResponse; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; /** * Created by Abderrahmen on 31/01/2018. */ @RestController @RequestMapping("/todos") @CrossOrigin() public class TodoController { ArrayList<todo> todos; static int id = 0; public TodoController(){ this.todos = new ArrayList<>(); this.todos.add(new Todo(id++,"my first todo","my first todo description")); this.todos.add(new Todo(id++, "my second todo","my second todo description")); this.todos.add(new Todo(id++, "my third todo","my third todo description")); } @RequestMapping(method = RequestMethod.GET) public TodoListResponse todos (){ TodoListResponse todoListResponse = new TodoListResponse(); todoListResponse.setTodos(this.todos); return todoListResponse; } @RequestMapping(method = RequestMethod.POST) public Todo addtodo (@RequestBody Todo todo){ todo.setId(++id); this.todos.add(todo); return todo; } @RequestMapping(method = RequestMethod.PUT) public Todo updateTodo (@RequestBody Todo todo){ for(int i =0; i < this.todos.size(); i++){ if(this.todos.get(i).getId() == todo.getId()){ this.todos.get(i).setName(todo.getName()); this.todos.get(i).setDescription(todo.getDescription()); break; } } return todo; } @RequestMapping(value="/{id}", method = RequestMethod.DELETE) public void deleteTodo (@PathVariable("id") int id){ for(int i =0; i < this.todos.size(); i++){ if(this.todos.get(i).getId() == id){ this.todos.remove(i); break; } } } }
Spring Boot 2 REST API main Class
The main class is the entry point of any Spring boot application. The code of that main class is very simple an is the following :
package com.javasneo.todolist; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TodoListApplication { public static void main(String[] args) { SpringApplication.run(TodoListApplication.class, args); }
}
Invoking Spring Boot 2 Rest API endpoints
In this section, we invoke all the REST API endpoints using
Postman. You can install postman using this link.
In order to use this section, you need to run the TodoListApplication class.
Otherwise the REST endpoints will be down.
HTTP GET /todos
The Request is the following :
Here, we just add the url of our REST GET endpoint in
Postman. The URL is the following : localhost:8080/todos
Initially, the endpoint returns the Todo list manually
created in the controller. But, the list gets updated when we use the other REST
endpoints.
HTTP POST /todos
Here, we add the following Todo object to the TodoList :
{ "name": "added todo", "description": "added todo description" }
The rest endpoint returns the newly added Todo in the response.
HTTP PUT /todos
Here, we update the which id is equal to zero. In fact, we replace
the Todo object which id is equal to zero with another object and we keep the
same id (zero).
If we want to implement the partial update of the object, we
should use the PATCH http method.
So, here we replace the original object at index 0 with this object :
{ "id":0, "name": "modified first todo", "description": "first todo description" }
This REST endpoint returns the modified Todo object as
shown in the image below:
HTTP DELETE /todo/{id}
This REST endpoint deletes the Todo object present at the id
put in the URL.
To delete the Todo at the index 0, we invoke this url :
localhost:8080/todos/0
You may guess the URL to invoke the delete the Todo at the
index 1 : localhost:8080/todos/1
This endpoint returns a 200 OK response for the moment. But
we can return a no content response instead if we want.
We just want to be as simple as possible because we will use
this REST api to build a fullstack Angular application.
Conclusion :
This spring boot rest api example arrives at its end.
The next step is to use a real database. As a first step, we will use an in
memory database like H2. Then, we will move to using hibernate and a nosql database
like MongoDB.
In the final step, we will build the frontend part of the
app using Angular, react and Vue JS.
So, keep tuned and give as a like and share this tutorial to
spread the knowledge.
We share our tutorial in our how to program Facebook page and the source code can be found at abderrahmen ben mariem Github.
You may also check our core java tutorial or the other spring boot 2 tutorials.
Post a Comment