příklady / api

Hello API

Minimalistické JSON API v jednom souboru. Úvod do služeb za 30 vteřin.

denohttpjson

Každá Frontback služba je jeden default export: handler ve stylu fetch, který dostane Request a vrátí Response, tedy stejná signatura, jakou znáte z webové platformy. Tento příklad routuje podle cesty v URL a nabízí JSON přehled, pozdrav s parametrem v cestě, aktuální čas serveru a echo endpoint, který přečte JSON tělo.

Nasazením vznikne jeden projekt s jednou službou. Žádná konfigurace, žádné secrets, žádná databáze. Služba běží na vlastní URL pár vteřin po nasazení. Začněte tady a pak pokračujte na příklady s úložištěm a cronem.

kód
main.ts
// A Frontback service is one file with one default export: a fetch-style
// handler that takes a Request and returns a Response. Deploy it and it
// is live at its own URL a few seconds later.
//
// This service is a tiny JSON API that routes on the URL pathname.

export default async (req: Request): Promise<Response> => {
  const { pathname } = new URL(req.url);

  // GET / -> a small index of what this API can do.
  if (pathname === "/") {
    return json({
      name: "hello-api",
      endpoints: ["GET /", "GET /hello/:name", "GET /time", "POST /echo"],
    });
  }

  // GET /hello/:name -> a path parameter is just a slice of the pathname.
  if (req.method === "GET" && pathname.startsWith("/hello/")) {
    const name = decodeURIComponent(pathname.slice("/hello/".length));
    if (!name) return json({ error: "Add a name, e.g. /hello/ada" }, 422);
    return json({ message: `Hello, ${name}!` });
  }

  // GET /time -> the current server time.
  if (req.method === "GET" && pathname === "/time") {
    return json({ now: new Date().toISOString() });
  }

  // POST /echo -> read the JSON body and send it straight back.
  if (req.method === "POST" && pathname === "/echo") {
    const body = await req.json().catch(() => null);
    if (body === null) return json({ error: "Send a JSON body" }, 422);
    return json({ received: body });
  }

  // Anything else: answer with a 4xx, not a 5xx — an expected miss should
  // not mark the run as failed in the dashboard.
  return json({ error: "Not found", hint: "GET /hello/world" }, 404);
};

// One helper keeps every response consistent: pretty JSON + charset header.
function json(data: unknown, status = 200): Response {
  return new Response(JSON.stringify(data, null, 2) + "\n", {
    status,
    headers: { "content-type": "application/json; charset=utf-8" },
  });
}

Go beyond what seems possible.