Creating a REST Controller
Build a REST API in Spring Boot with a @RestController class whose methods return JSON for each GET, POST, PUT and DELETE request.
Journeyman · Spring Boot · REST API · Updated
You have seen that in Spring MVC, you must use the @Controller annotation to create a controller. We used the controller class to handle our web requests while building pages with the Thymeleaf view engine.
Spring MVC provides us with the @RestController annotation to build a RESTful web API. Instead of relying on a server-side rendering view engine such as Thymeleaf, a RestController allows us to return data directly from the controller methods, in the form of JSON.
Controller methods also specify the HTTP status that a successful request should return.
A categories controller
@RestController
public class CategoriesController
{
private final CategoryDao categoryDao;
public CategoriesController(CategoryDao categoryDao)
{
this.categoryDao = categoryDao;
}
@GetMapping("/api/categories")
public List<Category> getAllCategories()
{
return categoryDao.getAllCategories();
}
@GetMapping("/api/categories/{id}")
public Category getCategoryById(@PathVariable int id)
{
return categoryDao.getCategoryById(id);
}
@PostMapping("/api/categories")
@ResponseStatus(HttpStatus.CREATED)
public Category addCategory(@RequestBody Category category)
{
// returns the inserted category, with its new id
return categoryDao.insert(category);
}
@PutMapping("/api/categories/{id}")
public Category updateCategory(@PathVariable int id, @RequestBody Category category)
{
// returns the updated category, as it is now saved
return categoryDao.update(id, category);
}
@DeleteMapping("/api/categories/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteCategory(@PathVariable int id)
{
categoryDao.delete(id);
}
}
That's where this topic is heading. You build it one method at a time: start with the class and its constructor, and no methods yet. Before each method, an Insomnia lesson saves the request that method must answer, so you can send it before and after you write the code.
Do it: write a DAO that keeps the contract without a database
The CategoriesController asks for a CategoryDao, and CategoryDao is an interface, so any class that implements it will do. A class that keeps its categories in a list, instead of a database, is handy for trying the controller out, and for tests. Write one.
Given at the bottom of the file: the Category model, with getCategoryId(), getCategoryName() and getDescription(), and the CategoryDao interface, cut down to the two methods the GET requests use:
List<Category> getAllCategories(): every category.Category getCategoryById(int id): the category with that id, ornullwhen there's none.
InMemoryCategoryDao is started: it implements CategoryDao, and its constructor keeps one value:
categories: the categories to keep, aList<Category>.
For example, a DAO made with these three categories:
| categoryId | categoryName |
|---|---|
| 1 | Beverages |
| 2 | Condiments |
| 3 | Confections |
getCategoryById(2) returns the Condiments category, getCategoryById(300) returns null, and getAllCategories() returns all three. The starter doesn't compile yet: Java says InMemoryCategoryDao doesn't write the interface's methods.
Your job: finish InMemoryCategoryDao so it keeps the CategoryDao contract.
- Write
getAllCategories(): return the whole list the constructor kept. - Write
getCategoryById(int id): return the category whosegetCategoryId()isid. - When no category has that id,
getCategoryByIdreturnsnull. - Leave
Category, the interface and the constructor as they are.
Practiced live on the lesson page: write the Java right there and check it.