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});56app.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);56 if (req == null) {7 ctx.status(400).json(java.util.Map.of("error", "body required"));8 return;9 }1011 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";23export 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 " + token9 }10 });1112 if (!res.ok) {13 const err = await res.json();14 throw new Error(err.error || "Request failed");15 }1617 return res.json();18}