Guides · 03
Build a JSON REST API
Build a concurrent HTTP/1.1 JSON REST API in Ochre with http_serve, json_parse, json_stringify, validated status codes, and body-less 204 responses.
Ochre's standard library includes a multi-threaded HTTP/1.1 server (http_serve) and native JSON utilities (json_parse, json_stringify) — no external packages required.
HTTP Handler & Status Contract (v0.1.0-alpha.4)
Before writing routes, understand the exact contract enforced by the type checker and runtime:
- Handler signature: Must accept 1 argument (
req: Map<Str, Any>) and return a responseMap. Wrong arity is rejected both at compile time and before binding the TCP port. - Request keys:
req["method"]("GET","POST", etc.),req["path"], andreq["body"]. - Response keys:
"status":Int(200..=599) or numericStr("200".."599"). Missing"status"defaults to200. Informational (1xx) or invalid statuses are logged server-side and return a clean500 Internal Server Errorwithout exposing internal runtime details."content_type": defaults to"text/plain; charset=utf-8"."body": response body string. For204 No Contentand304 Not Modified, Ochre automatically omits the body andContent-Lengthheader per RFC 9110.
Complete REST API (api.och)
fn json_response(status: Str, payload: Str) -> Map<Str, Str> {
return #{
"status": status,
"content_type": "application/json",
"body": payload,
}
}
fn handle(req: Map<Str, Str>) -> Map<Str, Str> {
let method = req["method"] ?? "GET"
let path = req["path"] ?? "/"
let body = req["body"] ?? ""
if method == "GET" && path == "/health" {
return json_response("200", json_stringify(#{ "status": "ok", "runtime": "ochre" }))
}
if method == "POST" && path == "/echo" {
return match json_parse(body) {
Ok(parsed) => json_response("201", json_stringify(#{ "received": parsed })),
Err(_) => json_response("400", json_stringify(#{ "error": "invalid JSON body" })),
}
}
if method == "DELETE" && path == "/cache" {
return #{ "status": "204" }
}
if path == "/health" || path == "/echo" {
return json_response("405", json_stringify(#{ "error": "method not allowed" }))
}
return json_response("404", json_stringify(#{ "error": "not found", "path": path }))
}
fn main() {
let port = int(env("PORT") ?? "8080")
println("Ochre API listening on http://127.0.0.1:{port}")
match http_serve(port, handle) {
Ok(_) => println("server stopped"),
Err(err) => println("failed to bind port {port}: {err}"),
}
}
Testing Your API with curl
ochre api.och
In another terminal:
curl -i http://127.0.0.1:8080/health
curl -i -X POST http://127.0.0.1:8080/echo -d '{"hello": "ochre"}'
curl -i -X DELETE http://127.0.0.1:8080/cache
curl -i -X PUT http://127.0.0.1:8080/health
Notice that /cache returns HTTP/1.1 204 No Content with no body, and PUT /health returns HTTP/1.1 405 Method Not Allowed.