JSON API Endpoints
Not every endpoint needs to return HTML. JSON APIs power mobile apps, single-page frontends, and third-party integrations. The only difference from an HTML endpoint is the content type and the format of the body.
Return JSON by setting the content type to application/json:
GET "/api/status" :\n string body = "{\\"status\\": \\"ok\\", \\"version\\": \\"1.0\\"}"\n return http.respond(200, "application/json", body)\n\n GET "/api/users/:id" :\n string id = req.param("id")\n string params = "[\\"" + id + "\\"]"\n string result = db.query("SELECT username, email FROM users WHERE id = ? LIMIT 1", params)\n string username = json.get(result, "data.rows.0.username")\n if username == ""\n return http.respond(404, "application/json", "{\\"error\\": \\"Not found\\"}")\n string email = json.get(result, "data.rows.0.email")\n string body2 = "{\\"username\\": \\"" + username + "\\", \\"email\\": \\"" + email + "\\"}"\n return http.respond(200, "application/json", body2)GET /api/status → {"status": "ok", "version": "1.0"}\nGET /api/users/1 → {"username": "alice", "email": "alice@example.com"}\nGET /api/users/999 → 404 {"error": "Not found"}Set content type to application/json for all API responses — both success and error. In Clean Language, JSON strings are built with escaped quotes inside the string literal. Return consistent JSON error objects so API consumers can parse errors the same way as successes.
A health check endpoint is a good first API to add to any server:
GET "/api/health" :\n string db_result = db.query("SELECT 1 as ok", "[]")\n string db_ok = json.get(db_result, "data.rows.0.ok")\n string status = "ok"\n if db_ok != "1"\n status = "degraded"\n string body = "{\\"status\\": \\"" + status + "\\"}"\n return http.respond(200, "application/json", body)GET /api/health → {"status": "ok"}SELECT 1 as ok is the simplest possible database ping. If the database is reachable, it returns 1. This health check pattern lets load balancers and monitoring tools verify your server is alive without touching real data.
Quick recap
- Set content type to application/json for API endpoints
- Return JSON for both success and error responses — never HTML from an API
- Use 404 with a JSON error body for not-found resources
- A /api/health endpoint that pings the DB is a good first thing to add