Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

A controller and JSON

A REST API is a set of addresses where other programs (a JavaScript site, a mobile app, another server) read and change data. They usually exchange JSON. In Spring such addresses are served by a controller — a class annotated with @RestController.

The first API controller

Create a file next to PostService.java:

// src/main/java/com/example/blog/PostController.java
package com.example.blog;
 
import java.util.List;
 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class PostController {
 
    private final PostService postService;
 
    public PostController(PostService postService) {
        this.postService = postService;
    }
 
    @GetMapping("/api/posts")
    public List<Post> list() {
        return postService.findAll();
    }
}

@GetMapping("/api/posts") binds the method to the GET /api/posts request. The method returns an ordinary list of records, not response text — Spring takes care of turning it into JSON.

Checking it

Restart the application and call the address:

curl -i http://localhost:8080/api/posts
HTTP/1.1 200
Content-Type: application/json
Content-Length: 2
 
[]

There are no posts yet, so an empty array arrived. The Content-Type: application/json header tells the client the response is JSON.

How an object becomes JSON

The spring-boot-starter-webmvc starter includes the Jackson library. It takes the components of a record and turns them into JSON fields. Once we can add posts in the next lessons, the same address returns:

[{"id":1,"title":"Hello, Spring","body":"First post","author":"anna","createdAt":"2026-10-04T08:50:07.494425300Z"}]

Each component of the Post record became a field with the same name. The Instant date is written in the standard ISO-8601 format, and a null would become null.

@RestController and @Controller

AnnotationWhat the method returns
@RestControllerData: the object is turned into JSON
@ControllerThe name of an HTML page template

@RestController is @Controller plus @ResponseBody on every method. Template pages come in chapter five; until then all controllers are @RestController.

How to name addresses

API addresses usually start with /api, and a collection of objects uses a plural noun: /api/posts, /api/comments, /api/users. This way API addresses never clash with site pages.

Common mistake

Jackson only sees what is visible from outside: record components or public getter methods like getTitle(). If you return an object of a plain class with private fields and no getters, there is no error — you get a 200 response with an empty object {}. The fields silently disappear. Use records for API responses — they already have everything needed.

Thanks for reading!

Donate to the site — we work hard for you.