What you will learn
- What the frontend, backend and database are each responsible for
- Chirp's complete architecture, and the path one click takes through it
- How the backend is organised into layers, and why
- REST APIs: URLs, HTTP methods, status codes and JSON
- Authentication vs authorization, and how JSON Web Tokens work
- The two ideas chapter 6 builds on: caching and real-time updates
Why it matters
When something breaks in a real application, the first question is always "where?" Is it the browser, the network, the API, the database? If you have a clear map of the pieces and the path a request takes between them, you can answer that in minutes instead of hours. Every later chapter fills in one part of this map.
Three parts, three jobs
Every web application like Chirp is split into at least three parts. They run in different places, are written differently, and, most importantly, are trusted differently.
React app
Runs in the user's browser. It draws screens, reacts to clicks and asks the backend for data.
- Shows posts, forms, buttons
- Sends HTTP requests
- Can't be trusted: users can change anything running on their own machine
Spring Boot API
Runs on our server. It decides what is allowed and does the work.
- Checks who is calling
- Applies the rules (280 characters, only delete your own posts)
- Reads and writes the database
PostgreSQL
Stores everything permanently and keeps it consistent.
- Users, posts, follows, likes…
- Enforces rules of its own (no duplicate likes)
- Only the backend talks to it
Analogy: a restaurant
The diner (browser) reads the menu and orders. The waiter (the API's front door) takes the order, checks it's something the kitchen makes, and that the diner can pay. The kitchen (the backend's business logic) cooks. The pantry (the database) holds the ingredients. Diners never walk into the pantry and help themselves: not because they couldn't find the flour, but because the restaurant would have no control over what gets taken. That's exactly why the browser never talks to the database directly.
Why can't the browser just talk to the database?
Because everything that runs in the browser is under the user's control. If the React app connected to PostgreSQL, the database password would have to be inside the app, and anyone could open the browser's developer tools, copy it, and run DELETE FROM posts. The backend exists to stand between untrusted users and the data: it is the only place where the rules can't be skipped.
This gives us the most important rule of this chapter: the frontend makes things convenient, the backend makes things safe. The composer stops you typing more than 280 characters, which is a nice touch, but the backend checks again, because a request can come from anywhere, not just our React app.
Chirp's complete architecture
Here is everything we will build, with the backend opened up so you can see its layers. Click any box to see what it does and which chapter builds it.
- React app (browser)
- The user interface: HTML, CSS and JavaScript downloaded once, then running on the user's machine. It sends HTTP requests to
/api/…and keeps one WebSocket open on/wsfor live notifications. Built in chapter 5. - Proxy: Vite in development, nginx in production
- The browser loads the page and calls the API through the same address, and the proxy forwards
/apiand/wsto Spring Boot. Because the browser only ever sees one origin, we never need CORS rules (explained below). In development this is Vite's dev server on port 5173; in production nginx serves the built files and does the forwarding (chapter 8). - Security filter (JwtAuthFilter)
- Runs before any controller. It reads the
Authorization: Bearer …header, checks the token's signature and expiry, and tells Spring Security who the user is. Requests without a valid token are refused with 401 for every endpoint except register and login. Chapter 4. - Controllers
- The front door for each URL:
PostControllerhandles/api/posts. They turn JSON into Java objects, run validation (@Valid), call a service and turn the result back into JSON. No business rules live here. - Services
- The business rules: "only the author may delete a post", "liking twice counts once", "notify the author".
PostService,UserService,FeedService… Each public method usually runs in one database transaction. - Repositories
- The only code that talks SQL.
PostRepository(Spring Data JPA) and small JdbcClient classes such asLikeRepositoryturn method calls likefindFeedIds(…)into queries. - PostgreSQL
- The source of truth. If Redis is wiped, nothing is lost; if PostgreSQL is wiped, everything is. Its tables and indexes are designed in chapter 3.
- Redis
- An in-memory store for data that is read over and over: cached profiles and pre-built home feeds. Optional by design: if it is down, the services fall back to PostgreSQL. Chapter 6.
- S3 (object storage)
- Image files live here, not in the database. The backend hands the browser a short-lived signed URL, and the browser uploads straight to S3, so big files never pass through our server. Chapter 6.
Why one backend and not many small services?
Chirp's backend is a single program organised into packages (auth, post, user, feed…). This is often called a modular monolith. It's one thing to build, test and deploy, and calls between parts are plain method calls instead of network requests. Splitting into microservices solves problems of large teams and very uneven load; chapter 7 explains when that becomes worth the cost.
The journey of one request
Let's follow a single click from start to finish: Alice has typed a post and presses Post. Step through it slowly; this path is the same for almost every request in Chirp.
- Alice presses Post. React calls
createPost(content), which builds an HTTP request: methodPOST, path/api/posts, a JSON body, and her token in theAuthorizationheader. - The request leaves the browser. It goes to the same address the page came from, so the browser treats it as same-origin.
- The proxy sees a path starting with
/apiand forwards the request to Spring Boot on port 8080. - Before any of our endpoint code runs,
JwtAuthFilterchecks the token's signature and expiry. It is valid, so Spring Security now knows the caller is user 3,alice. (No valid token? The request stops here with401.) - Spring turns the JSON body into a
CreatePostRequestand@Validchecks it: not blank, at most 280 characters. (Too long?400with the reason.) The controller hands it to the service. - The service applies the business rules: it loads the author, trims the text and creates a
Postentity, then asks the repository to save it, all inside one transaction. - Hibernate (behind the repository) sends an
INSERTto PostgreSQL. - PostgreSQL stores the row, picks the next id (6) and commits.
- The service turns the entity into a
PostResponse: only the fields the public should see, never the entity itself. - Spring converts the
PostResponseto JSON and sends status201 Created. - The response travels back through the proxy. React adds the new post to the top of Alice's feed. The whole round trip usually takes a fraction of a second.
This is the exact request the browser sends (the token is shortened):
POST /api/posts HTTP/1.1
Host: localhost:5173
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIzIi…
Content-Type: application/json
{"content":"Building a Twitter clone with Spring Boot and React."}And this is the response the real backend sent back while this course was being tested:
HTTP/1.1 201
Content-Type: application/json
Content-Length: 279
{"id":6,"content":"Building a Twitter clone with Spring Boot and React.","imageUrl":null,"createdAt":"2026-11-05T16:20:13.942706506Z","author":{"id":3,"username":"alice","displayName":"Alice"},"likeCount":0,"commentCount":0,"repostCount":0,"likedByMe":false,"repostedByMe":false}Notice what is not in the response: no password hash, no email address. The response is a DTO (data transfer object), a class designed for the outside world. You'll see why that matters in the next section.
Inside the backend: layers
The journey above passed through four kinds of class. Splitting a backend into layers, each with one job, is the most common way to organise it:
| Layer | Chirp example | Its job | It must not… |
|---|---|---|---|
| Controller | PostController | Map URLs to methods, read JSON, validate input, choose the status code | contain business rules or SQL |
| Service | PostService | Business rules and transactions: who may do what, what happens next | know about HTTP (requests, headers) |
| Repository | PostRepository, LikeRepository | Read and write the database | make business decisions |
| Entity | Post, User | One row of a table, as a Java object | be sent to the browser directly |
| DTO | CreatePostRequest, PostResponse | The shape of JSON going in and out: the public contract | change just because a table changed |
Here is the controller method from our journey. It is short on purpose: it receives the logged-in user and a validated request, and delegates.
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public PostResponse create(@AuthenticationPrincipal AuthUser me, @Valid @RequestBody CreatePostRequest request) {
return postService.create(me, request);
}And the service method it calls, where the decisions are made:
public PostResponse create(AuthUser me, CreatePostRequest request) {
User author = users.findById(me.id())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "User no longer exists"));
Post post = posts.save(new Post(author, request.content().strip(), null));
return PostResponse.from(post, false, false);
}Don't worry about every annotation yet; chapter 4 explains each one. What matters now is the split: the controller speaks HTTP, the service speaks business rules, the repository speaks SQL.
Why bother with layers? Wouldn't one class be simpler?
For a single endpoint, yes. But Chirp has around twenty, and many share rules. "Load a post or answer 404" is needed by get, like, repost and comment. With layers, that rule lives in one service method. Layers also make testing easy: in chapter 8 we test PostService with fake repositories and no web server at all, which is only possible because it doesn't know about HTTP.
Why not return the entity as JSON? It has all the fields already.
Because then every column becomes public, including ones added later. If someone added a passwordHash field to User, returning entities would leak it in every response that includes an author. A DTO like PostResponse lists exactly what the outside world may see. It also lets the database change (rename a column, split a table) without breaking the React app.
REST APIs: how the frontend and backend talk
The frontend and backend speak HTTP, the same protocol your browser uses to load web pages. REST is a style of designing an HTTP API around resources (things: posts, users, comments) instead of actions. Each resource has a URL, and the HTTP method says what to do with it:
- GET reads and never changes anything. Browsers, proxies and caches may repeat it safely.
- POST creates something (or triggers an action such as "like").
- PUT / PATCH replace or change something. Chirp doesn't need them yet.
- DELETE removes something.
These are Chirp's MVP endpoints, as built in chapter 4:
| Method | URL | Meaning | Success |
|---|---|---|---|
| POST | /api/auth/register | Create an account, get a token | 201 |
| POST | /api/auth/login | Log in, get a token | 200 |
| GET | /api/auth/me | Who am I? (is my saved token still good?) | 200 |
| POST | /api/posts | Create a post | 201 |
| GET | /api/posts/{id} | One post | 200 |
| DELETE | /api/posts/{id} | Delete my post | 204 |
| POST DELETE | /api/posts/{id}/like | Like / unlike | 200 |
| POST DELETE | /api/posts/{id}/repost | Repost / undo | 200 |
| GET POST | /api/posts/{id}/comments | List / add replies | 200 / 201 |
| GET | /api/feed?cursor=…&size=… | My home feed, one page | 200 |
| GET | /api/users/{username} | A profile with counts | 200 |
| GET | /api/users/{username}/posts | A user's posts, one page | 200 |
| POST DELETE | /api/users/{username}/follow | Follow / unfollow | 204 |
| GET | /api/users/suggestions | Who to follow | 200 |
| GET POST | /api/notifications, /read | My notifications / mark all read | 200 / 204 |
Notice the pattern: nouns in the URL, verbs in the method. "Follow alice" is POST /api/users/alice/follow and "unfollow" is DELETE on the same URL. Once you know the pattern, you can guess most URLs without reading documentation, and that predictability is the main point of REST.
Anatomy of an HTTP request
An HTTP request is just text. Click each underlined part of this real Chirp request to see what it does.
Click POST to start.
Status codes: the first thing to read
Every response starts with a three-digit status code. The first digit tells you who is responsible: 2xx it worked, 4xx the client sent something wrong, 5xx the server failed. The ones Chirp uses:
| Code | Meaning | When Chirp sends it |
|---|---|---|
200 OK | Here is what you asked for | GET requests, login, like/unlike |
201 Created | A new thing exists now | Register, create a post, add a reply |
204 No Content | Done, nothing to send back | Delete a post, follow, unfollow |
400 Bad Request | Your input is invalid | A 281-character post, a missing field, broken JSON |
401 Unauthorized | I don't know who you are | No token, an expired or tampered token, wrong password |
403 Forbidden | I know who you are, and the answer is no | Deleting someone else's post |
404 Not Found | That doesn't exist | A post or user id that isn't there |
409 Conflict | Clashes with what already exists | Registering a username that's taken |
500 Internal Server Error | A bug or outage on our side | Never on purpose: it means something we didn't expect |
When something goes wrong, Chirp answers with a small JSON document in a standard format called problem details (RFC 9457), so the frontend can always find a human-readable message in detail. These are real responses from the backend:
HTTP/1.1 400
Content-Type: application/problem+json
{"detail":"Some fields are invalid","instance":"/api/auth/register","status":400,"title":"Bad Request","errors":{"email":"must be a well-formed email address","password":"size must be between 8 and 72","username":"3 to 30 letters, digits or underscores"}}The extra errors map lets the sign-up form show each message under the right input.
HTTP/1.1 401
Content-Type: application/problem+json
{"detail":"Invalid username or password","instance":"/api/auth/login","status":401,"title":"Unauthorized"}The same message for "no such user" and "wrong password", so attackers can't use the login form to find out which usernames exist. A request with no token at all gets a bare 401 with an empty body, from the security filter.
HTTP/1.1 403
Content-Type: application/problem+json
{"detail":"You can only delete your own posts","instance":"/api/posts/5","status":403,"title":"Forbidden"}{"detail":"Post not found","instance":"/api/posts/999999","status":404,"title":"Not Found"}{"detail":"Username is already taken","instance":"/api/auth/register","status":409,"title":"Conflict"}Usernames are case-insensitive in Chirp, so registering Alice when alice exists gives this 409.
Authentication and authorization
Two words that sound alike and are constantly mixed up:
Authentication: who are you?
Proving identity. In Chirp: logging in with a password, then sending a token on every request. Done once per request by JwtAuthFilter, before any controller runs. Failure means 401.
Authorization: are you allowed?
Checking permission for this action on this thing. In Chirp: "only the author can delete a post", checked in PostService. Failure means 403.
Here is where each happens in the real code. Authentication, in the filter:
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header != null && header.startsWith("Bearer ")) {
try {
AuthUser user = jwtService.parse(header.substring("Bearer ".length()));
var authentication = new UsernamePasswordAuthenticationToken(user, null, List.of());
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (JwtException | IllegalArgumentException e) {
// Bad signature, expired or malformed: stay anonymous. Protected endpoints will answer 401.
}
}
chain.doFilter(request, response);Authorization, in the service (excerpt):
public void delete(AuthUser me, long postId) {
Post post = posts.findById(postId).orElseThrow(PostService::postNotFound);
if (post.getAuthor().getId() != me.id()) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "You can only delete your own posts");
}
posts.delete(post); // likes, reposts, comments and notifications go too (ON DELETE CASCADE)Notice the service compares the post's author with me.id(), the id that came from the verified token, not an id sent in the request. That difference is the whole point.
Sessions or tokens?
After you log in, the server needs a way to recognise you on the next request without asking for your password again. There are two classic designs:
Server sessions
The server creates a random session id, stores "session abc123 = Alice" in memory or a database, and sends the id in a cookie. Each request: look up the id.
- ✓ Logout is instant: delete the session
- ✓ The browser handles cookies automatically
- ✗ Every request needs a lookup in shared storage once you have several servers
- ✗ Cookies sent automatically need CSRF protection
Signed tokens (JWT) · what Chirp uses
The server writes "user 3, alice, valid until tomorrow" into a token and signs it with a secret key. Each request: check the signature. No lookup.
- ✓ Any server with the key can verify it; nothing is shared
- ✓ Simple for APIs and mobile apps
- ✗ Hard to revoke before it expires (hence short lifetimes)
- ✗ The frontend must store it and attach it itself
Neither is "the right one". Large sites often combine them. We use JWTs because they keep each request independent (no shared session store), which also makes scaling to several servers in chapter 7 straightforward, and because they let us show the mechanics clearly.
What is inside a JWT?
A JSON Web Token is three pieces of text joined by dots: header.payload.signature. This is a real token the Chirp backend issued to Alice:
The first two parts are just base64url-encoded JSON (base64 with - and _ instead of + and /, and no = padding, so it is safe in URLs and headers). Anyone can decode them:
{"alg":"HS256"}The algorithm: HMAC with SHA-256, a signature made with one shared secret key.
{"sub":"3","username":"alice","iat":1793895613,"exp":1793982013}sub (subject) is Alice's user id. iat (issued at) and exp (expires) are seconds since 1 January 1970: issued 5 November 2026 16:20 UTC, valid for exactly 24 hours (86,400 seconds), the ttl: 24h from our configuration.
The signature is HMAC-SHA256(secret, header + "." + payload), base64url-encoded. Only someone with the secret can produce it. Change one character of the payload, say "sub":"1", and the signature no longer matches, so the server refuses the token. That is what makes the token trustworthy even though the browser holds it.
Signed is not encrypted
Anyone who has a JWT can read its payload. Paste the token above into the site's JWT decoder and see. The signature only proves the server wrote it and nobody changed it. So never put secrets (passwords, emails you don't want exposed, internal flags) in a JWT payload.
Here is the full login-to-request flow. The last two steps show what happens to a tampered token.
- Alice submits the login form. The browser sends her username and password (over HTTPS in production) to
POST /api/auth/login. - The backend looks up the user
alice. - PostgreSQL returns her row, including the BCrypt hash. The backend hashes the typed password the same way and compares. They match.
- The backend writes the claims (user 3, alice, expires in 24 h) and signs them with the secret key. The secret never leaves the server.
- The token goes back in the JSON response. The React app saves it in
localStorage. - Every later request carries
Authorization: Bearer <token>, hereGET /api/feed. - The filter recomputes the signature with the secret and checks
exp. Both fine: the request is from user 3. No database lookup was needed to know who is calling. - The feed comes back.
- Someone edits the payload to claim they are user 1 and sends it, keeping the old signature.
- The recomputed signature doesn't match, so the request stays anonymous and gets
401. Without the secret, a valid signature can't be forged.
Try it: sign and verify a token in your browser
This demo does exactly what our JwtService does, using your browser's built-in cryptography (Web Crypto, HMAC-SHA256). Nothing is sent anywhere. Sign a token, then tamper with it or change the secret and verify again.
Simplified example
The playground skips some checks a real library performs (for example rejecting tokens whose header asks for a different algorithm). In Chirp we never write this by hand: the jjwt library does it, as you'll see in chapter 4. The demo exists so the idea stops being magic.
Caching in one picture
Some data is read far more often than it changes. Alice's profile (name, bio, follower count) may be viewed thousands of times between two changes. Asking PostgreSQL every single time works, but it does the same work over and over. A cache keeps a copy of the answer in fast memory, here Redis, for a while.
The pattern Chirp uses is called cache-aside: the application looks in the cache first; on a miss it asks the database and saves the answer in the cache; on a hit it skips the database entirely.
- Someone opens Alice's profile. The backend first asks Redis for the key
profile:alice. - Not there yet: a miss.
- So the backend asks PostgreSQL: the user row plus three counts.
- PostgreSQL answers.
- The backend stores the answer in Redis with an expiry time (a TTL) and returns it.
- The next visitor asks for the same profile.
- A hit: Redis answers from memory and PostgreSQL isn't touched. When Alice gains a follower, the backend deletes the key so the next read rebuilds it with the new count.
The hard part of caching is not storing things; it is knowing when a copy is out of date. Chapter 6 deals with that (and with what happens if Redis is down) in detail.
Real-time updates
HTTP is request–response: the server only speaks when the browser asks. So how can Alice's notification badge change the moment Bob likes her post? There are two common answers:
- Every few seconds, Alice's browser asks: "any new notifications?"
- "No." A full request and response for nothing.
- A few seconds later, again.
- "No."
- Bob likes Alice's post. The server records a notification, but has no way to tell Alice: she has to ask.
- At the next poll…
- …she finally learns about it, up to one interval late. Shorter intervals mean fresher news but more wasted requests for every open tab.
- When Alice opens Chirp, the browser asks to "upgrade" an HTTP request to a WebSocket at
/ws. The token travels in the URL, because the browser's WebSocket API can't add anAuthorizationheader. - The server checks the token and accepts. The connection now stays open, both ways, for as long as the tab is open.
- Nothing happens. No requests, no waste: the connection just waits.
- Bob likes Alice's post.
- The server pushes a small JSON message down Alice's open connection immediately. Her badge changes without a refresh.
Chirp uses a WebSocket for notifications in chapter 6. Note the catch: an open connection lives on one server, so with several servers Bob's like may be handled by a different one than Alice's connection. Chapter 7 shows how Redis pub/sub solves that. Other options exist too: Server-Sent Events (a one-way stream from server to browser, simpler than WebSockets) and long polling (the server holds each request open until there is news).
How it runs: development and production
The same code runs in two setups. The ports and processes differ, but the browser's view is identical: one origin.
| Piece | On your computer (chapters 4–6) | In production (chapter 8) |
|---|---|---|
| Page + proxy | Vite dev server, http://localhost:5173, reloads as you edit | nginx serving the built files, forwarding /api and /ws |
| Backend | ./mvnw spring-boot:run on port 8080 | Docker container, port 8080 inside a private network |
| PostgreSQL | Docker, port 5432 | Docker container or a managed database (e.g. Amazon RDS) |
| Redis | Docker, port 6379 | Docker container or a managed service |
| S3 | RustFS (S3-compatible) in Docker, port 9000 | Amazon S3, ideally behind CloudFront |
Why one origin? A word about CORS
An origin is scheme + host + port. http://localhost:5173 and http://localhost:8080 are different origins, even on the same computer. Browsers block JavaScript from reading responses from another origin unless that server explicitly allows it with CORS headers. This "same-origin policy" protects you: without it, any website you visit could read your data from other sites you are logged in to.
If our React app called http://localhost:8080/api/posts directly, the browser would block it and we'd have to configure CORS. Instead, the app calls /api/posts on its own origin, and the proxy forwards it. The browser is happy, the backend needs no CORS rules, and the same frontend code works unchanged in production. These few lines of the Vite configuration do it:
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [react()],
server: {
// The browser talks only to Vite (localhost:5173). Vite forwards /api to Spring Boot,
// so both look like the same origin and the browser never needs CORS.
proxy: {
'/api': 'http://localhost:8080',
},
},
});When the app is deployed, nginx plays the same role. The one place Chirp does need CORS is S3, because the browser uploads images straight to a different origin; chapter 6 sets that up.
Common mistakes
Trusting a user id sent by the browser
An endpoint like DELETE /api/posts/5?userId=3 lets anyone claim to be user 3 by editing the URL.
Fix: always take the caller's identity from the verified token (@AuthenticationPrincipal AuthUser me in Chirp), never from the request body or URL.
Putting secrets in the frontend
Database passwords, the JWT secret or AWS keys inside React code are visible to every visitor: the built JavaScript is downloaded in full and can be read.
Fix: secrets live only on the server, in environment variables (chapter 8). If the browser needs to do something privileged, like uploading to S3, the server hands out a narrow, short-lived permission instead (chapter 6).
Treating the JWT payload as private
The payload is only encoded, not encrypted. Anyone with the token can read it.
Fix: put only what's needed to identify the user (id, username, expiry). Keep tokens short-lived, and send them only over HTTPS.
Using GET for actions that change data
GET /api/posts/5/delete can be triggered by a link, a prefetching browser, a crawler or a cache retrying it.
Fix: GET only reads. Changes use POST, PUT, PATCH or DELETE.
Answering 200 OK with an error inside
200 {"error":"not found"} fools monitoring, caches and the frontend's error handling, which all look at the status code first.
Fix: use the right status code and a consistent error body. Chirp uses problem details for every error.
Confusing 401 and 403
Returning 403 for a missing token (or 401 for "not your post") makes clients react wrongly: a 401 should send the user to the login page, a 403 should not.
Fix: 401 means "I don't know who you are", 403 means "I know, and no".
Calling the backend's own address from the browser and fighting CORS
Hard-coding http://localhost:8080 in fetch calls triggers CORS errors in development and breaks in production, where the address is different.
Fix: use relative paths (/api/…) and a proxy, as above.
Key takeaways
- The frontend makes things convenient; the backend makes things safe. The browser never talks to the database.
- Every request passes the security filter, then controller → service → repository → database, and back.
- REST: nouns in URLs, verbs in HTTP methods, meaning in status codes, details in a consistent JSON error body.
- Authentication (who?) gives 401 when it fails; authorization (allowed?) gives 403.
- A JWT is signed, not encrypted: anyone can read it, nobody without the secret can change it.
- Caches keep copies of hot data; WebSockets let the server speak first; a same-origin proxy avoids CORS.
Check your understanding
Bob is logged in and tries to delete Alice's post. Which status code should Chirp send?
- 401 Unauthorized
- 403 Forbidden
- 404 Not Found
- 200 OK with an error message
An attacker copies Alice's JWT and changes "sub":"3" to "sub":"1" in the payload. What happens?
- They become user 1, because the payload is trusted
- Nothing: the server ignores the payload
- The signature no longer matches, so the request is treated as anonymous and gets 401
- The server decrypts the payload and notices
Which layer should contain the rule "a user can't follow themselves"?
- The service (UserService)
- The controller
- The React component only
- The proxy
Why does the React app call /api/posts instead of http://localhost:8080/api/posts?
- Relative URLs are faster
- Spring Boot only accepts relative URLs
- It hides the backend's address from hackers
- The page and the API then share one origin, so no CORS is needed, and the same code works in development and production
/api to the backend. The browser sees one origin.Exercise: design two endpoints
Using the REST pattern from this chapter, design endpoints for bookmarks (save a post privately) and editing your bio. For each: method, URL, request body (if any), success status code, and one error case with its status code. Then say which layer checks that only you can edit your own bio.
Show a sample answer
Bookmark: POST /api/posts/{id}/bookmark → 204; DELETE on the same URL to remove; GET /api/bookmarks?cursor=… → 200 with a page of posts. Error: bookmarking a post that doesn't exist → 404.
Bio: PATCH /api/users/me with {"bio":"…"} → 200 with the updated profile. Error: a bio over 160 characters → 400 with an errors map. Using me instead of a username in the URL means there is no way to even ask to edit someone else's bio: the service updates the user whose id is in the token. If you chose PATCH /api/users/{username}, the service must compare the username with the token's and answer 403 on a mismatch.
Finished this chapter? Tick it off. Progress is saved in this browser only.