Skip to content
Teasim
Documentation

Build an HTTP API

Define a typed route with Service and test it in process.

Define a route

In a Teasim workspace using Bun 1.4.4 or later, define a Service with a named path parameter. The handler receives the parameter from the matched URL.

ts
import { service } from "@teasim/service";

export const api = service().get("/orders/:id", ({ params }) => ({
  orderId: params.id,
}));

Handle a request in a test

The testing adapter gives you a Fetch interface for the same route. A request for order 42 returns a JSON object with orderId set to "42".

ts
import { handle } from "@teasim/service/testing";
import { api } from "./api";

const app = await handle(api);
try {
  const response = await app.fetch(new Request("http://localhost/orders/42"));
  console.log(await response.json());
} finally {
  await app.stop();
}

Listen on a port

Use the Bun adapter to serve the route. For routes that need a capability such as a store, supply the store through an application plugin. The assets API example uses this pattern.

ts
import { serve } from "@teasim/service/bun";
import { api } from "./api";

const server = await serve(api, { port: 3000 });