Skip to content

REST API

Track IOUs between roommates behind a small JSON API: list users, add one, and record a loan, keeping each user’s debts and balance.

Adapted from Exercism’s problem specification (MIT). Listed under Parsing & Validation.

// FILE: rest_api.nomi
//# A small REST API for an IOU tracker between roommates, over JSON.

import std::json.{FromJson, Json, ToJson}

/// A roommate: who they owe and how much, who owes them, and the
/// difference, what they are owed less what they owe.
pub struct User
    name:    String
    owes:    Map<String, Float> = {}
    owed_by: Map<String, Float> = {}
    balance: Float = 0.0
end

derive ToJson for User
derive FromJson for User

/// The body of a `/users` response and of the database: users by name.
pub struct Users
    users: List<User>
end

derive ToJson for Users
derive FromJson for Users

/// The payload of `GET /users`: the users to list.
struct UserNames
    users: List<String>
end

derive FromJson for UserNames

/// The payload of `POST /add`.
struct NewUser
    user: String
end

derive FromJson for NewUser

/// The payload of `POST /iou`: `borrower` owes `lender` `amount` more.
struct Iou
    lender:   String
    borrower: String
    amount:   Float
end

derive FromJson for Iou

/// Why a request has no response.
pub enum Error
    /// The payload or the database is not JSON of the expected shape; the
    /// error says where.
    InvalidJson Json.Error
    /// No method handles this URL.
    NotFound String
    UnknownUser String
    UserExists String
end

/// The IOU tracker: every user by name. Each request returns JSON text, and
/// a `POST` returns the tracker after it too.
pub opaque struct RestApi
    users: Map<String, User>
end

impl RestApi
    /// The tracker over `database`, a JSON object `{"users": [...]}`.
    pub fn new(database: String) -> Result<RestApi, Error>
        database: Users = Json.decode_as(database) |> Result.map_err(Error.InvalidJson)?

        Ok({users: database.users |> Iter.map(&(&1.name, &1)) |> Iter.to_map()})
    end

    /// Returns a `GET` of `url`: `/users` lists every user, or the users
    /// `payload` names, by name.
    pub fn get(api: RestApi, url: String, payload: Maybe<String> = None) -> Result<String, Error>
        if url != "/users" then return Err(.NotFound(url))

        names = case payload
            Some(text) ->
                query: UserNames = Json.decode_as(text) |> Result.map_err(Error.InvalidJson)?
                query.users

            None ->
                Map.keys(api.users)
        end

        users = names |> Iter.map(&find(api, &1)) |> Result.collect()?
        Ok(Json.encode_as(Users{users: Iter.sort_by(users, .name)}))
    end

    /// Returns a `POST` of `payload` to `url`, and the tracker after it.
    /// `/add` adds a user and returns it; `/iou` records a loan and returns
    /// the lender and the borrower, by name.
    pub fn post(api: RestApi, url: String, payload: String) -> Result<(String, RestApi), Error>
        case url
            "/add" ->
                request: NewUser = Json.decode_as(payload) |> Result.map_err(Error.InvalidJson)?

                if request.user in api.users then return Err(.UserExists(request.user))

                user = User{name: request.user}
                Ok((Json.encode_as(user), RestApi{users: Map.put(api.users, user.name, user)}))

            "/iou" ->
                iou: Iou = Json.decode_as(payload) |> Result.map_err(Error.InvalidJson)?
                lender = find(api, iou.lender)?
                borrower = find(api, iou.borrower)?
                net = net_owed(lender, borrower.name) + iou.amount
                lender = with_net(lender, borrower.name, net)
                borrower = with_net(borrower, lender.name, -net)

                users =
                    api.users |> Map.put(lender.name, lender) |> Map.put(borrower.name, borrower)

                answer = Users{users: Iter.sort_by([lender, borrower], .name)}
                Ok((Json.encode_as(answer), RestApi{users:}))

            _ ->
                Err(.NotFound(url))
        end
    end
end

fn find(api: RestApi, name: String) -> Result<User, Error>
    Map.get(api.users, name) |> Maybe.to_result(.UnknownUser(name))
end

/// What `other` owes `user`, less what `user` owes `other`.
fn net_owed(user: User, other: String) -> Float
    owed = Map.get(user.owed_by, other) |> Maybe.with_default(0.0)
    owing = Map.get(user.owes, other) |> Maybe.with_default(0.0)
    owed - owing
end

/// `user` with `other` owing them `net`, or owed `-net` by them when `net`
/// is negative, and nothing either way at zero.
fn with_net(user: User, other: String, net: Float) -> User
    owes = Map.remove(user.owes, other)
    owed_by = Map.remove(user.owed_by, other)

    owes = if net < 0.0 then Map.put(owes, other, -net) else owes

    owed_by = if net > 0.0 then Map.put(owed_by, other, net) else owed_by

    owed = owed_by |> Map.values() |> Iter.sum()
    owing = owes |> Map.values() |> Iter.sum()
    {..user, owes:, owed_by:, balance: owed - owing}
end

// FILE: rest_api_test.nomi
import
    std::json.Json
    rest_api.{RestApi, User, Users}
end

once adam_and_bob = `{"users":[{"name":"Adam","owes":{},"owed_by":{},"balance":0.0},{"name":"Bob","owes":{},"owed_by":{},"balance":0.0}]}`

once bob_owes_chuck = `{"users":[{"name":"Adam","owes":{},"owed_by":{},"balance":0.0},{"name":"Bob","owes":{"Chuck":3.0},"owed_by":{},"balance":-3.0},{"name":"Chuck","owes":{},"owed_by":{"Bob":3.0},"balance":3.0}]}`

once adam_owes_bob = `{"users":[{"name":"Adam","owes":{"Bob":3.0},"owed_by":{},"balance":-3.0},{"name":"Bob","owes":{},"owed_by":{"Adam":3.0},"balance":3.0}]}`

group "user management"
    test "no users"
        api = RestApi.new(`{"users":[]}`)?
        answer = RestApi.get(api, "/users")?
        assert Json.decode_as<Users>(answer) == Ok({users: []})
    end

    test "add user"
        api = RestApi.new(`{"users":[]}`)?
        (answer, _api) = RestApi.post(api, "/add", `{"user":"Adam"}`)?
        user: User = Json.decode_as(answer)?

        assert user == {name: "Adam", owes: {}, owed_by: {}, balance: 0.0}
    end

    test "get single user"
        api = RestApi.new(adam_and_bob)?
        answer = RestApi.get(api, "/users", Some(`{"users":["Bob"]}`))?
        users: Users = Json.decode_as(answer)?

        expected: Users = Json.decode_as(
            `{"users":[{"name":"Bob","owes":{},"owed_by":{},"balance":0.0}]}`
        )?

        assert users == expected
    end
end

test "iou"
    [
        (
            "both users have 0 balance",
            adam_and_bob,
            `{"lender":"Adam","borrower":"Bob","amount":3.0}`,
            `{"users":[{"name":"Adam","owes":{},"owed_by":{"Bob":3.0},"balance":3.0},{"name":"Bob","owes":{"Adam":3.0},"owed_by":{},"balance":-3.0}]}`,
        ),
        (
            "borrower has negative balance",
            bob_owes_chuck,
            `{"lender":"Adam","borrower":"Bob","amount":3.0}`,
            `{"users":[{"name":"Adam","owes":{},"owed_by":{"Bob":3.0},"balance":3.0},{"name":"Bob","owes":{"Adam":3.0,"Chuck":3.0},"owed_by":{},"balance":-6.0}]}`,
        ),
        (
            "lender has negative balance",
            bob_owes_chuck,
            `{"lender":"Bob","borrower":"Adam","amount":3.0}`,
            `{"users":[{"name":"Adam","owes":{"Bob":3.0},"owed_by":{},"balance":-3.0},{"name":"Bob","owes":{"Chuck":3.0},"owed_by":{"Adam":3.0},"balance":0.0}]}`,
        ),
        (
            "lender owes borrower",
            adam_owes_bob,
            `{"lender":"Adam","borrower":"Bob","amount":2.0}`,
            `{"users":[{"name":"Adam","owes":{"Bob":1.0},"owed_by":{},"balance":-1.0},{"name":"Bob","owes":{},"owed_by":{"Adam":1.0},"balance":1.0}]}`,
        ),
        (
            "lender owes borrower less than new loan",
            adam_owes_bob,
            `{"lender":"Adam","borrower":"Bob","amount":4.0}`,
            `{"users":[{"name":"Adam","owes":{},"owed_by":{"Bob":1.0},"balance":1.0},{"name":"Bob","owes":{"Adam":1.0},"owed_by":{},"balance":-1.0}]}`,
        ),
        (
            "lender owes borrower same as new loan",
            adam_owes_bob,
            `{"lender":"Adam","borrower":"Bob","amount":3.0}`,
            `{"users":[{"name":"Adam","owes":{},"owed_by":{},"balance":0.0},{"name":"Bob","owes":{},"owed_by":{},"balance":0.0}]}`,
        ),
    ]
    |> subtests (description, database, payload, expected), description
        assert Ok(api) = RestApi.new(database)
        assert Ok((answer, _api)) = RestApi.post(api, "/iou", payload)
        assert Ok(wanted) = Json.decode_as<Users>(expected)
        assert Json.decode_as<Users>(answer) == Ok(wanted)
    end
end
  • Every request and response is JSON text read and written with std/json. The shapes are structs with derive ToJson and derive FromJson: User, Users (the {"users": [...]} of the database and of the responses), and the three payloads, UserNames, NewUser and Iou, which stay private. User’s owes, owed_by and balance have defaults, so a new user is User{name: request.user}.
  • RestApi is a value, an opaque struct of the users by name. RestApi.new(database) reads the database; RestApi.get(api, url, payload) returns the text; RestApi.post(api, url, payload) returns the text and the tracker after the request, since nothing changes in place.
  • Each failure is an Error variant: JSON that is not of the expected shape (holding std/json’s Json.Error), an unknown URL, an unknown user, and a user added twice. The canonical data has no failing case.
  • A loan is kept as one number per pair: what the borrower owes the lender, less what the lender already owed the borrower, plus the new amount. with_net writes that number into one side of each user’s maps, or neither when it is zero, and works the balance out again from the maps, so the canonical “lender owes borrower” cases need no case analysis.
  • Text becomes a typed value in one call, Json.decode_as, whose T comes from the binding’s annotation (iou: Iou = ...), and its Json.Error becomes Error.InvalidJson with Result.map_err. Json.encode_as is the other direction, from a value to text.
  • The tests compare responses as values, not text. Json.encode writes Float(3.0) as 3, and the canonical data writes 3.0; the two are the same JSON number, so each response and each expected text are read back into Users or User and compared with ==. The JSON is written in backtick raw strings, so its quotes need no escapes.
  • The canonical “user management” group is a group of three tests, since each case sends a different request; the six “iou” cases are one subtests table. A subtests row cannot use ?, so the table takes each step apart with assert Ok(...) = ....