Skip to content

A server endpoint ​

Two ways to answer HTTP: a typed endpoint from a file under routes/, and a router in code.

A typed endpoint ​

routes/api/books/server.weft
weft
import { books } from "lib/server/books"
import type { Book } from "lib/server/books"

/// GET /api/books?author=…&limit=…
export async fn get(args: { author?: string, limit?: number }): Book[] {
  let mut found = await books()
  if let a = args.author {
    found = found.filter(b => b.author == a)
  }
  return found[..args.limit ?? 50]
}
lib/server/books.weft
weft
export type Book = { id: string, title: string, author: string, year: number }

let shelf: Book[] = [
  Book { id: "1", title: "The Dispossessed", author: "Le Guin", year: 1974 },
  Book { id: "2", title: "The Left Hand of Darkness", author: "Le Guin", year: 1969 },
  Book { id: "3", title: "Kindred", author: "Butler", year: 1979 },
]

export action fn books(): Book[] {
  return shelf
}
sh
curl 'localhost:3000/api/books?author=Le%20Guin&limit=1'
text
[{"author":"Le Guin","id":"1","title":"The Dispossessed","year":1974}]

The function's name is the method (get, post, …) and its parameter the query string or the JSON body, checked against its type before the code runs:

text
$ curl 'localhost:3000/api/books?limit=many'
{"error":{"name":"TypeError","message":"field limit: expected number | null, got string","data":null}}

That answer is a 400. The result is sent as JSON. In the app, the same endpoint is a typed call: routes.api.books.get({ author: "Butler" }).

Requests and responses ​

For full control, export a handler per method that takes the Request and returns a Response:

routes/api/echo/server.weft
weft
import { json, text } from "std/http"
import type { Request, Response } from "std/http"
import { now } from "std/time"

export async fn POST(req: Request): Response {
  if req.headers.get("content-type") != "application/json" {
    return text("send JSON", { status: 415 })
  }
  let body, err = try req.json()
  if err != null {
    return text(`not JSON: ${err.message}`, { status: 400 })
  }
  return json({ got: body, at: now().epochMs })
}

A router in code ​

A plain program, or an app's app.weft, can build its API as code, with middleware:

server/main.weft
weft
import { router, json, serve, cors } from "std/http"
import type { Request, Response, Handler } from "std/http"
import { log } from "std/log"
import { now } from "std/time"

let mut hits = 0

// Middleware: answers itself, or calls `next` with the request.
async fn timed(req: Request, next: Handler): Response {
  let start = now().epochMs
  let res = try await next(req)
  log(`${req.method} ${req.path} ${res.status} in ${now().epochMs - start} ms`)
  return res
}

let api = router()
  .use(timed)
  .use(cors({ origins: ["https://example.com"] }))
  .get("/health", async req => json({ ok: true }))
  .get("/hits", async req => {
    hits += 1
    return json({ hits })
  })
  .get("/hello/:name", async req => json({ hello: req.params.name }))

try await serve({ port: 8080 }, api)

weft run server/main.weft serves it on port 8080. A route's req.params is typed by its path: /hello/:name gives { name: string }. cors and files (static files) are the middleware in the box. Module state (hits) lives as long as the process. A path the router and the file routes both define is a compile error. Everything std/http has: std/http.

Weft is in development. The reference is the spec as it stands today.