Cookbook: Building a REST API

In this practical recipe, we build a complete in-memory CRUD REST API service using Djazair's http and json standard library modules.

Complete Server Code

djazair
use http
use json

# In-memory database
let products = [
    {"id": 1, "name": "Laptop", "price": 1200},
    {"id": 2, "name": "Mechanical Keyboard", "price": 150}
]
let nextId = 3

let server = http.createServer(fn(req, res)
    res.setHeader("Content-Type", "application/json")

    # GET /api/products
    if req.method == "GET" and req.pathname == "/api/products"
        res.status(200).send(json.encode(products))
        return
    end

    # POST /api/products
    if req.method == "POST" and req.pathname == "/api/products"
        let payload = json.decode(req.body)
        payload["id"] = nextId
        nextId++
        products.append(payload)
        res.status(201).send(json.encode(payload))
        return
    end

    # 404 Fallback
    res.status(404).send(json.encode({"error": "Route not found"}))
end)

print("Product REST API live at http://localhost:3000")
server.listen(3000)