{"id":560,"date":"2025-08-19T10:28:14","date_gmt":"2025-08-19T10:28:14","guid":{"rendered":"https:\/\/www.examtopics.info\/blog\/?p=560"},"modified":"2026-10-29T23:18:59","modified_gmt":"2026-10-29T23:18:59","slug":"spring-boot-rest-api-a-complete-guide-to-getting-started","status":"publish","type":"post","link":"https:\/\/www.examtopics.info\/blog\/spring-boot-rest-api-a-complete-guide-to-getting-started\/","title":{"rendered":"Spring Boot REST API: A Complete Guide to Getting Started"},"content":{"rendered":"<p>Spring Boot can expose HTTP endpoints with a small Spring MVC controller, but a working REST service involves more than attaching <code>@RestController<\/code> 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.<\/p>\n<h2>Create a Spring Boot project with Spring Web<\/h2>\n<p>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 <code>com.example.notes<\/code>. Add the controller below under the same package and start the application with <code>.\/mvnw spring-boot:run<\/code> (or <code>mvnw.cmd spring-boot:run<\/code> on Windows).<\/p>\n<p>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.<\/p>\n<h2>Implement GET and POST for a small resource<\/h2>\n<pre><code class=\"language-java\">package com.example.notes;\n\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicLong;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.ResponseStatus;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.server.ResponseStatusException;\n\n@RestController\n@RequestMapping(&quot;\/api\/notes&quot;)\npublic class NoteController {\n    private final Map&lt;Long, Note&gt; notes = new ConcurrentHashMap&lt;&gt;();\n    private final AtomicLong nextId = new AtomicLong(1);\n\n    public record NewNote(String text) {}\n    public record Note(long id, String text) {}\n\n    @GetMapping(&quot;\/{id}&quot;)\n    public Note find(@PathVariable long id) {\n        Note note = notes.get(id);\n        if (note == null) {\n            throw new ResponseStatusException(HttpStatus.NOT_FOUND, &quot;Note not found&quot;);\n        }\n        return note;\n    }\n\n    @PostMapping\n    @ResponseStatus(HttpStatus.CREATED)\n    public Note create(@RequestBody NewNote input) {\n        if (input == null || input.text() == null || input.text().isBlank()) {\n            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, &quot;Text required&quot;);\n        }\n        long id = nextId.getAndIncrement();\n        Note note = new Note(id, input.text().trim());\n        notes.put(id, note);\n        return note;\n    }\n}<\/code><\/pre>\n<p>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. <code>@ResponseStatus(CREATED)<\/code> 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.<\/p>\n<h2>Exercise the API from the command line<\/h2>\n<pre><code class=\"language-bash\">curl -i -X POST http:\/\/localhost:8080\/api\/notes \\\n  -H &quot;Content-Type: application\/json&quot; \\\n  -d &#x27;{&quot;text&quot;:&quot;Review controller tests&quot;}&#x27;\n\ncurl -i http:\/\/localhost:8080\/api\/notes\/1\ncurl -i http:\/\/localhost:8080\/api\/notes\/999<\/code><\/pre>\n<p>The first response should be HTTP 201 with JSON similar to <code>{\"id\":1,\"text\":\"Review controller tests\"}<\/code>. 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.<\/p>\n<h2>Add meaningful tests before adding a database<\/h2>\n<p>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.<\/p>\n<h2>Production concerns deliberately outside the demo<\/h2>\n<ul>\n<li>Add authentication and authorization before exposing business data; never assume a URL is private because it is difficult to guess.<\/li>\n<li>Choose storage and transaction behavior appropriate to the workload; the in-memory map is not durable and does not synchronize across application instances.<\/li>\n<li>Validate payload size and schema, design pagination for collection endpoints, and make error messages consistent.<\/li>\n<li>Use HTTPS, structured logging, request tracing, deployment health checks and secrets management; do not embed credentials in controller source.<\/li>\n<li>Version public contracts carefully and document compatibility when clients depend on field names or response codes.<\/li>\n<\/ul>\n<p>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.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,14],"tags":[],"class_list":["post-560","post","type-post","status-publish","format-standard","hentry","category-post","category-software-development"],"_links":{"self":[{"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/posts\/560","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/comments?post=560"}],"version-history":[{"count":3,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/posts\/560\/revisions"}],"predecessor-version":[{"id":5990,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/posts\/560\/revisions\/5990"}],"wp:attachment":[{"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/media?parent=560"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/categories?post=560"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/tags?post=560"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}