14. Building A Native API
This chapter builds a small API using Alef's standard library.
State
fn initial_state() {
return {
"accounts" => [
{ "id" => "acct_ada", "name" => "Ada AI Studio" }
]
}
}
Handler
import std.http { json_response }
fn with_state(response, state) {
return { "response" => response, "state" => state }
}
fn list_accounts(request, state) {
return with_state(json_response(json_encode({
"data" => state["accounts"]
})), state)
}
Routes
fn app() {
let app = std.http.with_state(std.http.app(), initial_state())
return std.http.route(app, "GET", "/api/accounts", list_accounts)
}
Listen
fn main() {
std.http.listen_options("127.0.0.1:8090", app(), {
"shutdown_path" => "/__shutdown"
})
}
This is an Alef program using the HTTP module. The framework is not hidden somewhere else.