Nyx by Example

nyx-serve JSON API

response_json takes a raw JSON string; response_json_map serializes a Map to JSON with proper escaping. Request bodies are accessible via req.body.

Code

// nyx-serve JSON API -- request parsing and response_json_map

import "std/http"
import "std/web"
import "std/json"

fn echo_json(req: Request) -> Response {
    // req.body contains the raw request body as a String
    // Use std/json to parse structured input
    let data: String = req.body

    // response_json_map builds a JSON object from a Map
    var result: Map = Map.new()
    result.insert("received", data)
    result.insert("method", req.method)
    result.insert("path", req.path)
    return response_json_map(200, result)
}

fn health_check(req: Request) -> Response {
    // response_json takes a raw JSON string
    return response_json(200, "{\"status\": \"ok\", \"service\": \"api\"}")
}

fn not_found(req: Request) -> Response {
    return response_json(404, "{\"error\": \"not found\"}")
}

fn main() -> int {
    let app: App = app_new()

    app_get(app, "/health", health_check)
    app_post(app, "/echo", echo_json)

    print("JSON API configured")
    print("  GET  /health -> {\"status\": \"ok\"}")
    print("  POST /echo   -> echoes request body as JSON")
    return 0
}

Output

JSON API configured
  GET  /health -> {"status": "ok"}
  POST /echo   -> echoes request body as JSON

Explanation

Two helpers cover 95% of JSON response needs. response_json(status, raw) trusts you to produce valid JSON — fast, zero overhead, but one missing backslash and clients choke. Use it for constant replies like {"status": "ok"} where you control the entire string.

response_json_map(status, map) walks a Map and emits properly escaped JSON: quotes are backslashed, control characters are \u00XX, and nested Maps/Arrays are recursed. Always use this when any piece of the output comes from user input. Pair it with std/json::parse to read the request body into a Map, mutate, and serialize back — a zero-ceremony request-response cycle.

Both helpers set Content-Type: application/json; charset=utf-8 automatically. For custom headers, build a Response with response_new and response_set_header.

← Previous Next →

Source: examples/by-example/79-serve-json-api.nx