HTTP Server
A REST API server with JSON handling and middleware.
HTTP Server
A complete REST API server for managing a collection of items with CRUD operations, JSON encoding, and middleware.
Code
use httpuse jsonuse fs
const DATA_FILE = "items.json"
action loadItems() -> list if not fs#exists(DATA_FILE) ret [] fin if @raw = fs#read(DATA_FILE) ret json#parse(raw).
action saveItems(@items: list) fs#write(DATA_FILE, json#stringify(items)).
action listItems(@req: http#Request) -> http#Response @items = loadItems() ret http#json(200, items).
action getItem(@req: http#Request) -> http#Response @id = req#params#id @items = loadItems()
for @i = 0 to items#length if items[i]#id == id ret http#json(200, items[i]) fin if fin for
ret http#json(404, {"error": "Not found"}).
action createItem(@req: http#Request) -> http#Response @body = json#parse(req#body)
if not body#name ret http#json(400, {"error": "Name is required"}) fin if
@items = loadItems() @newItem = { "id": items#length + 1, "name": body#name, "description": body#description or "" } items#push(newItem) saveItems(items) ret http#json(201, newItem).
action logger(@req: http#Request, @next: fn -> http#Response) -> http#Response io#println(req#method + " " + req#path) ret next().
action main() @server = http#Server(8080)
server#use(logger) server#get("/items", listItems) server#get("/items/:id", getItem) server#post("/items", createItem) server#listen()
io#println("API server running on :8080").Run
draft run main.draftTest with curl
# List itemscurl http://localhost:8080/items
# Create an itemcurl -X POST http://localhost:8080/items \ -H "Content-Type: application/json" \ -d '{"name":"Draft","description":"A programming language"}'Expected Output
$ curl http://localhost:8080/items[{"id":1,"name":"Draft","description":"A programming language"}]