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 // SECURITY: Use pathParamAsLong or pathParamAsInt when passing to a database.3 // Raw pathParam("id") could contain SQL injection vectors or non-numeric garbage.4 long id = ctx.pathParamAsLong("id");5 ctx.json(java.util.Map.of("id", id, "name", "Demo User"));6});78app.post("/api/users", ctx -> {9 CreateUserReq req = ctx.body(CreateUserReq.class);10 if (req == null || req.getEmail() == null) {11 ctx.status(400).json(java.util.Map.of("error", "email is required"));12 return;13 }14 ctx.status(201).json(java.util.Map.of("message", "created"));15});
Query Parameters
Extract query parameters natively. If a parameter is missing, it returns null.
query-params
1// Example: /api/search?page=1&limit=102app.get("/api/search", ctx -> {3 String page = ctx.queryParam("page");4 String limit = ctx.queryParam("limit");56 int pageNum = page != null ? Integer.parseInt(page) : 1;7 int limitNum = limit != null ? Integer.parseInt(limit) : 20;89 ctx.json(java.util.Map.of("page", pageNum, "limit", limitNum));10});
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});
404 Not Found vs 405 Method Not Allowed
NioFlow strictly distinguishes between a path that does not exist (404) and a path that exists but was called with the wrong HTTP method (405). This adheres to REST best practices and prevents confusing client errors.
curl-tests
1# 404 Not Found (path doesn't exist)2$ curl -i -X GET http://localhost:8080/does-not-exist3HTTP/1.1 404 Not Found45# 405 Method Not Allowed (path exists, wrong method)6$ curl -i -X POST http://localhost:8080/api/users/17HTTP/1.1 405 Method Not Allowed
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}