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});
7
8app.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=10
2app.get("/api/search", ctx -> {
3 String page = ctx.queryParam("page");
4 String limit = ctx.queryParam("limit");
5
6 int pageNum = page != null ? Integer.parseInt(page) : 1;
7 int limitNum = limit != null ? Integer.parseInt(limit) : 20;
8
9 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);
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});

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-exist
3HTTP/1.1 404 Not Found
4
5# 405 Method Not Allowed (path exists, wrong method)
6$ curl -i -X POST http://localhost:8080/api/users/1
7HTTP/1.1 405 Method Not Allowed

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}