Serve a book as JSON
Build a read-only endpoint at GET /api/books/:id. You will define a route, start the server and send a request. Begin in a project with @chojs/web installed.
1. Define the application
Save this file as app.ts.
import { ChoWeb, Controller, Get, Module, Param, Args } from "@chojs/web";
@Controller({ route: "books" })
class Books {
@Get(":id")
@Args(Param("id"))
find(id: string) {
return { id, title: "The Odyssey" };
}
}
@Module({ controllers: [Books] })
export class Library {}
export const createApp = () => ChoWeb.create(Library, { prefix: "api" });The path has three pieces here. The application contributes api, the controller contributes books and the method captures one segment as id. CHO passes its decoded value to find and serializes the returned object as JSON. The fixed title keeps the example focused on routing.
2. Start a local server
Save this file beside it as main.ts. Keeping the listener in a separate file lets a test import app.ts directly.
import { serve } from "@chojs/web/serve";
import { createApp } from "./app.ts";
const app = await createApp();
const server = await serve(app.handler, { hostname: "127.0.0.1", port: 3000 });
console.log("Library listening on http://127.0.0.1:" + server.port);deno run --allow-net main.tsnpx tsx main.tsbun run main.ts3. Check the route
In a second terminal, run:
$ curl -i http://127.0.0.1:3000/api/books/42Expect status 200, a JSON content type and the body {"id":"42","title":"The Odyssey"}. Try /books/42 without the application prefix to see the router's 404. Stop the server with Ctrl+C.
Exercise the same route in memory
import { createApp } from "./app.ts";
const app = await createApp();
try {
const response = await app.handler(new Request("http://library/api/books/42"));
console.log(response.status, await response.json());
} finally {
await app.close();
}Next, build a catalog that accepts writes or test the endpoint.