Routing + Frontend Integration

Build custom routes and return API responses that frontend clients can consume directly.

Custom Routes

routes
1app.get("/api/users/:id", ctx -> {
2 String id = ctx.pathParam("id");
3 ctx.json(java.util.Map.of("id", id, "name", "Demo User"));
4});
5
6app.post("/api/users", ctx -> {
7 CreateUserReq req = ctx.body(CreateUserReq.class);
8 if (req == null || req.getEmail() == null) {
9 ctx.status(400).json(java.util.Map.of("error", "email is required"));
10 return;
11 }
12 ctx.status(201).json(java.util.Map.of("message", "created"));
13});

Request & Response Model

http-context
1app.post("/api/items/:id", ctx -> {
2 String id = ctx.pathParam("id");
3 String auth = ctx.header("Authorization");
4 ItemReq req = ctx.body(ItemReq.class);
5
6 if (req == null) {
7 ctx.status(400).json(java.util.Map.of("error", "body required"));
8 return;
9 }
10
11 ctx.header("X-Request-Id", "abc-123");
12 ctx.status(200).json(java.util.Map.of(
13 "id", id,
14 "authorized", auth != null,
15 "name", req.getName()
16 ));
17});

Frontend fetch() Example

frontend-fetch
1const base = "https://your-api-domain";
2
3export async function fetchTasks(token) {
4 const res = await fetch(base + "/api/tasks/", {
5 method: "GET",
6 headers: {
7 "Content-Type": "application/json",
8 "Authorization": "Bearer " + token
9 }
10 });
11
12 if (!res.ok) {
13 const err = await res.json();
14 throw new Error(err.error || "Request failed");
15 }
16
17 return res.json();
18}