Skip to content
Weaverv0.5.0

An HTTP service

With weft/rest, an HTTP service is a contract: its methods, annotated with a verb and a path, are the routes. #Rest reads the contract at compile time and writes the router that serves an implementation of it, and a client that calls it over HTTP with the same methods. There is no routing table to keep in step with the code, and no reflection at run time.

Terminal window
wv add weft/rest
wv add weft/json

A small service of tasks to do, kept in memory:

import weaver.io.{print, IoError}
import weaver.task.{Shared}
import weaver.test.{assert, assertEq}
import weft.json.{Json}
import weft.rest.{Rest, RestError, Reply}
/// Something to do.
#Json
type Task = { id: Int, title: String, done: Bool }
/// What a client sends to create a task.
#Json
type NewTask = { title: String }
/// Why a request fails: each variant has its HTTP status.
#Error #Json
enum TaskError =
| @status(404) NotFound(id: Int) `error("no task ${id}")`
| @status(400) Untitled `error("a task needs a title")`
| Rest(cause: RestError) `error("${cause.message()}")`
/// The tasks, as an HTTP service.
#Rest("/tasks")
contract TasksApi {
/// The tasks, those done or not if asked.
@get("")
fn list(self, done: Bool?): Task[] ! TaskError
@get("/{id}")
fn show(self, id: Int): Task ! TaskError
/// Creates a task: 201, and its address in `Location`.
@post("")
@status(201)
fn create(self, task: NewTask, reply: mut Reply): Task ! TaskError
/// Marks a task done.
@put("/{id}/done")
fn finish(self, id: Int): Task ! TaskError
@delete("/{id}")
fn remove(self, id: Int): () ! TaskError
}
/// The tasks in memory, shared by the tasks that serve the connections.
sync type Store = { tasks: Shared<Task[]>, next: Shared<Int> }
impl TasksApi for Store {
fn list(self, done: Bool?): Task[] ! TaskError =
self.tasks.get().filter(t => done.map(d => t.done == d) ?? true)
fn show(self, id: Int): Task ! TaskError =
self.tasks.get().seq().filter(t => t.id == id).first() ?? fail TaskError.NotFound(id)
fn create(self, task: NewTask, reply: mut Reply): Task ! TaskError {
if task.title.trim().isEmpty() { fail Untitled }
val id = self.next.update(n => n + 1)
val added = Task{id, title: task.title.copy(), done: false}
self.tasks.write(ts => ts.push(added.copy()))
reply.header("Location", "/tasks/${id}")
return added
}
fn finish(self, id: Int): Task ! TaskError {
val t = self.show(id)!.with(done: true)
self.tasks.write(ts => {
for mut x in ts { if x.id == id { x = t.copy() } }
})
return t
}
fn remove(self, id: Int): () ! TaskError {
val _ = self.show(id)!
self.tasks.update(ts => ts.filter(t => t.id != id))
}
}
fn newStore(): Store = Store{tasks: Shared.new([]), next: Shared.new(0)}
fn main(args: String[]) ! IoError {
val Some(at) = args.first() else {
print("usage: tasks <address>, such as tasks 127.0.0.1:8080")
return
}
print("tasks at http://${at}/tasks")
Rest.serve(at, [TasksApi.router(newStore())])!
}
@test("the service, through its client")
fn throughClient() ! TaskError {
val api = TasksApi.clientOf(Rest.handler([TasksApi.router(newStore())]))
var reply = Reply.new()
val milk = api.create(NewTask{title: "buy milk"}, &reply)!
assertEq(reply.headers.get("Location"), Some("/tasks/1"))
val _ = api.create(NewTask{title: "call Ada"}, &reply)!
assertEq(api.finish(milk.id)!.done, true)
assertEq(api.list(Some(false))!.map(t => t.title), ["call Ada"])
assert(api.show(7) is Err(NotFound(_)), "no task 7")
assert(api.create(NewTask{title: " "}, &reply) is Err(Untitled), "a title is required")
}
  • The contract is the API. @get, @post, @put, @patch and @delete give each method its verb and its path, below the contract’s prefix, /tasks. A method without one is refused at compile time.
  • Parameters come from where their name and type say: id is in the path, {id}; done, a scalar not in the path, from the query, ?done=false, and may be absent since it is optional; task, a type that adopts Json, from the body; reply, the response being made, where create sets a header. @header("X-Name") reads a header.
  • Results: a type that adopts Json is the body, with 200 or the status @status gives; () is 204.
  • Errors are written as problem JSON, RFC 9457, with the status of their variant, @status(404); a variant without one is a 500, whose detail is not sent. The variant holding a RestError is what the client fails with when the network does.
  • sync type Store holds the state: each connection is served by a task of its own, and they share the store through a Shared value, read by snapshot, written one writer at a time.
Terminal window
wv build -o tasks main.wft
./tasks 127.0.0.1:8080
$ curl -i -X POST -d '{"title": "buy milk"}' http://127.0.0.1:8080/tasks
HTTP/1.1 201 Created
Content-Type: application/json
Location: /tasks/1
{"id":1,"title":"buy milk","done":false}
$ curl -X POST -d '{"title": "call Ada"}' http://127.0.0.1:8080/tasks
{"id":2,"title":"call Ada","done":false}
$ curl -X PUT http://127.0.0.1:8080/tasks/1/done
{"id":1,"title":"buy milk","done":true}
$ curl 'http://127.0.0.1:8080/tasks?done=false'
[{"id":2,"title":"call Ada","done":false}]
$ curl -i -X DELETE http://127.0.0.1:8080/tasks/2
HTTP/1.1 204 No Content

An error of the service comes back with its status, its message, and the variant itself, which the client reads back:

$ curl -i http://127.0.0.1:8080/tasks/9
HTTP/1.1 404 Not Found
Content-Type: application/problem+json
{"status":404,"title":"Not Found","detail":"no task 9","error":{"NotFound":{"id":9}}}

A request that does not fit the contract never reaches the code: the router answers it.

$ curl -X POST -d '{"name": 3}' http://127.0.0.1:8080/tasks
{"status":400,"title":"Bad Request","detail":"the body does not decode: $: missing key `title` (line 1, column 1)"}
$ curl http://127.0.0.1:8080/tasks/abc
{"status":400,"title":"Bad Request","detail":"path parameter id: an integer, not \"abc\""}
$ curl -i -X PATCH http://127.0.0.1:8080/tasks/1
HTTP/1.1 405 Method Not Allowed
Allow: GET, DELETE, HEAD
{"status":405,"title":"Method Not Allowed","detail":"PATCH is not allowed at /tasks/1"}

HEAD is answered by the GET of the same path. TasksApi.routes() lists the routes, and wv expand main.wft shows the code #Rest wrote.

The same contract gives the client: TasksApi.client(base) is an any TasksApi whose methods send the requests, and read the answers back into the result, or into the same error variant.

fn main(args: String[]) ! TaskError {
val api = TasksApi.client(args[0])
var made = Reply.new()
val t = api.create(NewTask{title: "write the docs"}, &made)!
print("created ${t.id} at ${made.headers.get("Location") ?? "?"}")
for task in api.list(None)! { print("${if task.done { "x" } else { " " }} ${task.title}") }
val missing = api.show(42) catch e => {
print("${e}")
return
}
print(missing.title)
}
$ ./client http://127.0.0.1:8080
created 2 at /tasks/2
x buy milk
write the docs
no task 42

TasksApi.clientOf(router) is a client that calls a router in the same task, without a socket. The test of the program above goes through every layer, the routing, the parameters, the JSON both ways and the error statuses, in a few milliseconds:

Terminal window
wv test main.wft

A middleware runs around the routes: it reads the request, answers by itself, or passes it on with next.run. Given to Rest.serve, it wraps every route; @use(mw) puts it on one contract or one method.

/// Refuses a request without a token, before any route runs.
val requireToken = Middleware.of((r, body, next) => {
if r.request.headers.get("Authorization") != Some("Bearer s3cret") {
return restProblem(401, "a bearer token is required", None)
}
return next.run(r, &body)
})
fn main(args: String[]) ! IoError {
for r in TasksApi.routes() { print("${r.method} ${r.path}") }
Rest.serve(args[0], [TasksApi.router(newStore())], middleware: [requireToken])!
}
$ curl http://127.0.0.1:8080/tasks
{"status":401,"title":"Unauthorized","detail":"a bearer token is required"}
$ curl -H "Authorization: Bearer s3cret" http://127.0.0.1:8080/tasks
[]

A middleware can also attach a value to the request, the caller its token names, which a route then takes as a parameter of its type.

  • Nested resources. @mount("/{id}/comments") on a method returning any CommentsApi puts another contract’s routes below a task. #Rest follows the mounts at compile time, and reports two routes in conflict, or a path parameter no method takes, at the annotation.
  • Uploads and downloads. @part reads a part of a multipart body, a FilePart a file; body: mut BodyReader reads a body as it arrives, without holding it; a Response result is sent as it is.
  • Static files. Rest.static("/app", dir: "dist", fallback: "index.html") is a router like the others: ETags, ranges, gzip copies, and no path that leaves the directory.
  • A reverse proxy. Rest.proxy("/api", to: "http://10.0.0.2:8080") forwards a prefix to another server.
  • The repository’s examples/rest uses each of them, and the registry documents weft/rest in full.