INSIGHTS
Software Development

Spring Boot REST API: A Complete Guide to Getting Started

In this article
  1. Create a Spring Boot project with Spring Web
  2. Implement GET and POST for a small resource
  3. Exercise the API from the command line
  4. Add meaningful tests before adding a database
  5. Production concerns deliberately outside the demo

Spring Boot can expose HTTP endpoints with a small Spring MVC controller, but a working REST service involves more than attaching @RestController to a class. The endpoint must have defined request and response shapes, input checks, correct status codes and predictable error handling. This tutorial builds a self-contained in-memory notes API that you can run locally, then explains which parts must change before production use.

Create a Spring Boot project with Spring Web

Use Spring Initializr to create a Maven Java project with the Spring Web dependency and a currently supported Java runtime. Select a stable Spring Boot release offered by the generator rather than copying a version number from an old screenshot. Keep the generated application class in a package such as com.example.notes. Add the controller below under the same package and start the application with ./mvnw spring-boot:run (or mvnw.cmd spring-boot:run on Windows).

The example has no database and uses a memory map, so all notes disappear on restart. That is intentional: it isolates HTTP behavior from persistence and authentication while you learn endpoint design. The official Spring MVC documentation explains the controller mapping model.

Implement GET and POST for a small resource

package com.example.notes;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

@RestController
@RequestMapping("/api/notes")
public class NoteController {
    private final Map<Long, Note> notes = new ConcurrentHashMap<>();
    private final AtomicLong nextId = new AtomicLong(1);

    public record NewNote(String text) {}
    public record Note(long id, String text) {}

    @GetMapping("/{id}")
    public Note find(@PathVariable long id) {
        Note note = notes.get(id);
        if (note == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Note not found");
        }
        return note;
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Note create(@RequestBody NewNote input) {
        if (input == null || input.text() == null || input.text().isBlank()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Text required");
        }
        long id = nextId.getAndIncrement();
        Note note = new Note(id, input.text().trim());
        notes.put(id, note);
        return note;
    }
}

Spring binds a matching HTTP request to the annotated method and serializes the returned record as JSON when the normal Spring Web JSON support is present. @ResponseStatus(CREATED) marks a successful POST as HTTP 201. The GET method returns HTTP 404 when no matching ID exists. The minimal input check prevents blank text; a production application should use stronger validation rules and consistent exception responses.

Exercise the API from the command line

curl -i -X POST http://localhost:8080/api/notes \
  -H "Content-Type: application/json" \
  -d '{"text":"Review controller tests"}'

curl -i http://localhost:8080/api/notes/1
curl -i http://localhost:8080/api/notes/999

The first response should be HTTP 201 with JSON similar to {"id":1,"text":"Review controller tests"}. The second should be HTTP 200 with the same resource, while a missing ID should produce HTTP 404. A repeated run may allocate a different ID because the counter is process-local. Verify status codes as well as response bodies: a JSON object with the wrong HTTP status is not a complete API contract.

Add meaningful tests before adding a database

At minimum, test POST with a valid note, POST with blank text, GET for an existing note, and GET for a nonexistent ID. Controller integration tests using MockMvc can verify routing, JSON and status codes without manually clicking in a browser. Test request validation and exception behavior separately from persistence; later you can replace the in-memory map with a repository without changing the public response contract unnecessarily.

Production concerns deliberately outside the demo

  • Add authentication and authorization before exposing business data; never assume a URL is private because it is difficult to guess.
  • Choose storage and transaction behavior appropriate to the workload; the in-memory map is not durable and does not synchronize across application instances.
  • Validate payload size and schema, design pagination for collection endpoints, and make error messages consistent.
  • Use HTTPS, structured logging, request tracing, deployment health checks and secrets management; do not embed credentials in controller source.
  • Version public contracts carefully and document compatibility when clients depend on field names or response codes.

A REST API is useful when consumers can predict how to create, retrieve and handle a resource. Start with a small working contract, prove it with repeatable HTTP calls, then introduce the database, access control and observability required by your application. The official Spring REST service walkthrough is a companion reference for the framework annotations and project setup.

Filed under Software Development