# 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 November 14, 2026

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

```java
@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.

## Cheat sheets

- [RESTful Web APIs](https://www.ask-codey.com/cheat-sheets/restful-web-apis-an-overview-cheat-sheet)

Source: https://www.ask-codey.com/lessons/restful-web-apis-creating-a-rest-controller
