beginner~2h

Building REST APIs

Foundations are done. This module is where an HTTP request actually becomes a method call in your code — and the request/response shapes real clients depend on.

Learning objectives

  • Beginner: Trace a single incoming HTTP request through DispatcherServlet to the specific controller method that handles it.
  • Intermediate: Correctly choose between @RequestBody, @RequestParam, and @PathVariable for a given endpoint's inputs.
  • Advanced: Design response status codes and ResponseEntity usage so the API's contract is explicit and correct, not just "always 200."

REST models an API as a set of resources (e.g. /books, /books/42) manipulated through standard HTTP verbs, with each request carrying everything the server needs to process it — no server-side session state required to interpret the request itself.

VerbMeaningExample
GETRead a resource, no side effectsGET /books/42
POSTCreate a new resourcePOST /books
PUTReplace a resource entirelyPUT /books/42
PATCHPartially update a resourcePATCH /books/42
DELETERemove a resourceDELETE /books/42

◆ Under the hood

Every HTTP request into a Spring Boot web app first hits one servlet — the DispatcherServlet — which examines the request path and method, consults the request-mapping metadata registered by every @RestController (Module 04 §1), and dispatches to the matching handler method. You never configure this servlet yourself for a standard REST app; spring-boot-starter-web 's auto-configuration (Module 04 §4) sets it up automatically.

@RestController @RequestMapping("/books") public class BookController { private final BookService bookService; public BookController(BookService bookService) { this.bookService = bookService; } @GetMapping("/{id}") public BookResponse getBook(@PathVariable Long id) { return bookService.findById(id); } @GetMapping public List<BookResponse> searchBooks(@RequestParam(required = false) String author) { return bookService.search(author); } @PostMapping public ResponseEntity<BookResponse> createBook(@RequestBody CreateBookRequest request) { BookResponse created = bookService.create(request); return ResponseEntity.status(HttpStatus.CREATED).body(created); } }

💻 Code example

@RestController @RequestMapping("/books") public class BookController { private final BookService bookService; public BookController(BookService bookService) { this.bookService = bookService; } @GetMapping("/{id}") public BookResponse getBook(@PathVariable Long id) { return bookService.findById(id); } @GetMapping public List<BookResponse> searchBooks(@RequestParam(required = false) String author) { return bookService.search(author); } @PostMapping public ResponseEntity<BookResponse> createBook(@RequestBody CreateBookRequest request) { BookResponse created = bookService.create(request); return ResponseEntity.status(HttpStatus.CREATED).body(created); } }
AnnotationSourceExample URL
@PathVariableA segment of the URL path itself/books/{id} → the 42 in /books/42
@RequestParamA URL query string parameter/books?author=Orwell → author=Orwell
@RequestBodyThe HTTP request body, deserialized from JSONThe JSON payload of a POST/PUT request

▲ Pitfall

Binding @RequestBody directly to your JPA @Entity class (instead of a dedicated request DTO) lets a client set fields they should never control — like an internal id, an createdAt timestamp, or a relationship field — simply by including them in the JSON payload. This is exactly the problem Module 07's DTOs exist to prevent.

CodeUse it for
200 OKSuccessful GET, PUT, or PATCH.
201 CreatedSuccessful POST that created a new resource — pair with a Location header pointing to it.
204 No ContentSuccessful DELETE, or any action with intentionally no response body.
400 Bad RequestMalformed or failed-validation input (Module 10).
404 Not FoundThe requested resource doesn't exist.

✓ Quick recap

What single component receives every incoming HTTP request before it reaches your controller? The DispatcherServlet — auto-configured by spring-boot-starter-web. Why is binding @RequestBody directly to a JPA entity risky? It lets a client set fields (IDs, timestamps, relationships) it should never control, just by including them in the JSON payload.

◆ Why this matters

The subtopics above cover how Spring Boot turns an HTTP request into a method call — but real REST API work also comes with a whole vocabulary that shows up constantly in job descriptions, code reviews, and system-design conversations: gateway, payload, rate limiting, idempotency-adjacent terms like CRUD, and a cluster of API-security acronyms. This is a fast, practical reference for that vocabulary — organized by theme, not alphabetically, so related terms sit next to each other.

Core request/response vocabulary

TermWhat it means
APIApplication Programming Interface — a defined set of rules and protocols that let two pieces of software talk to each other, usually over HTTP.
ResourceThe "thing" an API exposes — a user, an order, a single record — addressable by a URI and acted on through HTTP methods.
EndpointThe specific URL where a resource lives and can be reached, e.g. /api/orders/42. Every distinct URL + method combination is its own endpoint.
ClientWhatever is making the request — a browser, a mobile app, another backend service. In Spring terms, anything calling into your controller.
MethodThe HTTP verb on a request — GET, POST, PUT, PATCH, DELETE — that tells the server what kind of operation to perform on the resource.
RequestWhat the client sends: a method, a URL, headers, and optionally a body.
ResponseWhat the server sends back: a status code, headers, and optionally a body.
Response code / status codeThe 3-digit number in a response that tells the caller what happened — 200 (OK), 201 (Created), 404 (Not Found), 500 (Internal Server Error), and so on.
PayloadThe actual data carried in a request or response body — almost always JSON in a modern REST API.
Query parametersKey-value pairs appended to a URL after ? (e.g. ?status=active&page=2) used to filter, sort, or paginate a request without changing the endpoint itself.
PaginationSplitting a large result set into pages so a client can request one chunk at a time instead of the whole dataset in one response.
CRUDCreate, Read, Update, Delete — the four basic operations almost every resource-oriented API needs to support, usually mapped to POST, GET, PUT/PATCH, and DELETE.
CacheA layer that stores a copy of frequently-requested data closer to the caller, so repeat requests can be served faster without hitting the origin service every time.

Architecture, protocols & data formats

TermWhat it means
RESTREpresentational State Transfer — an architectural style (not a protocol) for designing networked APIs around stateless requests and resources identified by URIs. An API that follows these conventions is called RESTful.
SOAPSimple Object Access Protocol — an older, stricter, XML-based messaging protocol for web services, still found in some enterprise and banking systems. Where REST is a style, SOAP is a formal specification.
JSONJavaScript Object Notation — the lightweight, human-readable, language-agnostic data format almost all modern REST payloads use.
MicroservicesAn architectural style that splits one application into many small, independently deployable services, each owning a narrow piece of business capability and its own data.
API GatewayA single entry point that sits in front of a set of backend services, routing each incoming request to the right one while centrally handling concerns like authentication, rate limiting, and request aggregation.
API layerA proxy-like layer that unifies a collection of underlying services behind one consistent, language-agnostic interface for callers.
FrameworkA pre-built set of libraries, conventions, and APIs (Spring Boot itself is one) that developers build on top of instead of writing every piece of infrastructure from scratch.
ApplicationA program, or a bundle of programs, built for an end user — in casual usage, often interchangeable with "framework" or "service."
WebhookThe inverse of polling: instead of a client repeatedly asking "anything new yet?", the server pushes an HTTP request to a URL the client registered, the moment something actually happens.

API lifecycle, business & tooling

TermWhat it means
API lifecycleThe full span of managing an API from design and creation, through active use and versioning, to eventual deprecation and retirement — commonly grouped into creation, control, and consumption stages.
API economyThe broader pattern of businesses exposing and consuming each other's APIs to create value neither side could build alone — Uber calling the Google Maps API instead of building its own mapping stack is a classic example.
API integrationThe work of connecting two or more systems through their APIs so data flows between them automatically.
API portalA public-facing hub — documentation, sandbox credentials, changelogs — that helps external developers discover and start using an API.
API documentationThe reference material that explains an API's endpoints, parameters, and expected responses well enough that another developer can integrate against it without reading the source code.
MonetizationTurning API access itself into a revenue stream — charging per call, per tier, or per usage volume.
SDKSoftware Development Kit — a packaged bundle of client libraries, sample code, and docs for a specific platform, so developers don't have to hand-write raw HTTP calls against an API.
SDLCSoftware Development Lifecycle — the structured process of planning, building, testing, and deploying software, aimed at shipping reliable software as cheaply and quickly as is responsible.
CI/CDContinuous Integration / Continuous Deployment — the practice of automatically building, testing, and shipping code changes in small, frequent batches instead of large manual releases.
Production environmentThe live setting where real users actually hit your API and real traffic depends on it staying up — as opposed to local, dev, or staging environments.

API security & testing

TermWhat it means
AuthenticationVerifying that a caller is who they claim to be, typically via an API key, a bearer token, or full OAuth credentials, before letting a request proceed.
API keysA unique identifier issued to a calling application (not a human user) so an API can recognize and authenticate that specific caller.
API securityThe umbrella discipline of practices — authentication, authorization, rate limiting, input validation, and more — aimed at stopping an API from being abused, exploited, or taken down.
Rate limitingCapping how many requests a given client can make in a given time window, to stop one caller (malicious or just buggy) from overwhelming a shared API.
OWASPOpen Web Application Security Project — a nonprofit that publishes widely-used, freely available security standards, tools, and the well-known "OWASP Top 10" list of common vulnerability classes, including an API-specific edition.
Penetration testingAlso called pen testing or ethical hacking — deliberately simulating real attacks against a system, with permission, to find exploitable weaknesses before an actual attacker does.
Red teamA group of security professionals whose job is to actively attack a system — finding compromised entry points or exploitable logic — to show an organization exactly how it could really be broken into.
Burp SuiteA widely used, all-in-one penetration-testing toolkit for web applications, built around an intercepting proxy that lets a tester inspect and modify requests and responses in transit.
ZAP (OWASP Zed Attack Proxy)A free, open-source security scanner (an OWASP project) that automates finding vulnerabilities in web applications and can be driven through its own API for CI/CD integration.
SQL injectionAn attack where malicious SQL is smuggled into a query through unsanitized user input (a form field, a URL parameter), potentially exposing or destroying data — one of the oldest and still most common web attack classes, which is exactly why parameterized queries and an ORM like Spring Data JPA exist.
DDoSDistributed Denial of Service — flooding a target with traffic from many sources at once until its infrastructure can't keep up and legitimate requests can no longer get through.
Logic flawA bug in an application's business rules — not its syntax — that behaves in an unintended way an attacker can exploit, such as being able to apply the same discount code an unlimited number of times.
Over-permissioned containerA container running with more privileges than it actually needs — often full root-equivalent access to its host — which turns it into a much bigger prize if an attacker ever gets a foothold inside it.

Two vendor tools worth recognizing

TermWhat it means
ApigeeGoogle Cloud's API gateway and management platform — used to expose backend services behind a managed proxy layer with built-in rate limiting, analytics, and access control.
APIsecA company specializing in automated, continuous API security testing, aimed at catching business-logic vulnerabilities before an API reaches production rather than after.

▲ Common mistake

Treating "authentication" and "API security" as the same thing. Authentication is one piece of API security — verifying identity — but a fully authenticated caller can still send malicious payloads, abuse rate limits, or exploit a logic flaw. Real API security layers authentication together with authorization, input validation, and rate limiting; none of them alone is sufficient.

Want a visual for this concept?

Generate a diagram tailored to “Building REST APIs” — the AI picks whichever visual (flowchart, comparison, sequence, etc.) best fits.

Sign in to generate a visual →

Practice quiz

Next Step

Continue to DTOs & Entity Mapping← Back to all Spring Boot chapters