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.
| Verb | Meaning | Example |
|---|---|---|
| GET | Read a resource, no side effects | GET /books/42 |
| POST | Create a new resource | POST /books |
| PUT | Replace a resource entirely | PUT /books/42 |
| PATCH | Partially update a resource | PATCH /books/42 |
| DELETE | Remove a resource | DELETE /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); } }
| Annotation | Source | Example URL |
|---|---|---|
| @PathVariable | A segment of the URL path itself | /books/{id} → the 42 in /books/42 |
| @RequestParam | A URL query string parameter | /books?author=Orwell → author=Orwell |
| @RequestBody | The HTTP request body, deserialized from JSON | The 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.
| Code | Use it for |
|---|---|
| 200 OK | Successful GET, PUT, or PATCH. |
| 201 Created | Successful POST that created a new resource — pair with a Location header pointing to it. |
| 204 No Content | Successful DELETE, or any action with intentionally no response body. |
| 400 Bad Request | Malformed or failed-validation input (Module 10). |
| 404 Not Found | The 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
| Term | What it means |
|---|---|
| API | Application Programming Interface — a defined set of rules and protocols that let two pieces of software talk to each other, usually over HTTP. |
| Resource | The "thing" an API exposes — a user, an order, a single record — addressable by a URI and acted on through HTTP methods. |
| Endpoint | The specific URL where a resource lives and can be reached, e.g. /api/orders/42. Every distinct URL + method combination is its own endpoint. |
| Client | Whatever is making the request — a browser, a mobile app, another backend service. In Spring terms, anything calling into your controller. |
| Method | The HTTP verb on a request — GET, POST, PUT, PATCH, DELETE — that tells the server what kind of operation to perform on the resource. |
| Request | What the client sends: a method, a URL, headers, and optionally a body. |
| Response | What the server sends back: a status code, headers, and optionally a body. |
| Response code / status code | The 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. |
| Payload | The actual data carried in a request or response body — almost always JSON in a modern REST API. |
| Query parameters | Key-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. |
| Pagination | Splitting a large result set into pages so a client can request one chunk at a time instead of the whole dataset in one response. |
| CRUD | Create, Read, Update, Delete — the four basic operations almost every resource-oriented API needs to support, usually mapped to POST, GET, PUT/PATCH, and DELETE. |
| Cache | A 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
| Term | What it means |
|---|---|
| REST | REpresentational 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. |
| SOAP | Simple 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. |
| JSON | JavaScript Object Notation — the lightweight, human-readable, language-agnostic data format almost all modern REST payloads use. |
| Microservices | An 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 Gateway | A 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 layer | A proxy-like layer that unifies a collection of underlying services behind one consistent, language-agnostic interface for callers. |
| Framework | A 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. |
| Application | A program, or a bundle of programs, built for an end user — in casual usage, often interchangeable with "framework" or "service." |
| Webhook | The 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
| Term | What it means |
|---|---|
| API lifecycle | The 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 economy | The 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 integration | The work of connecting two or more systems through their APIs so data flows between them automatically. |
| API portal | A public-facing hub — documentation, sandbox credentials, changelogs — that helps external developers discover and start using an API. |
| API documentation | The 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. |
| Monetization | Turning API access itself into a revenue stream — charging per call, per tier, or per usage volume. |
| SDK | Software 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. |
| SDLC | Software 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/CD | Continuous Integration / Continuous Deployment — the practice of automatically building, testing, and shipping code changes in small, frequent batches instead of large manual releases. |
| Production environment | The 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
| Term | What it means |
|---|---|
| Authentication | Verifying 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 keys | A unique identifier issued to a calling application (not a human user) so an API can recognize and authenticate that specific caller. |
| API security | The 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 limiting | Capping 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. |
| OWASP | Open 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 testing | Also 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 team | A 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 Suite | A 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 injection | An 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. |
| DDoS | Distributed 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 flaw | A 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 container | A 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
| Term | What it means |
|---|---|
| Apigee | Google 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. |
| APIsec | A 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 →