astrobench · play with code
Step
7/10

An API endpoint

Sometimes you want data, not HTML. Astro can do both.

Until now, every file in src/pages/ returned HTML. But your project is about to want something else — JSON . For the search island you'll build next, for syndication feeds, for embeds.

 

Astro lets you write API routes the same way you wrote pages. The trick: the file ends in .ts (or .js ) instead of .astro , and you export an HTTP method function.

src/pages/api/logs.json.ts — server-only read-only
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { getCollection } from "astro:content";
import type { APIRoute } from "astro";

export const GET: APIRoute = async () => {
  const logs = await getCollection("logs");

  const body = logs.map((log) => ({
    id: log.id,
    title: log.data.title,
    date: log.data.date,
    author: log.data.author,
  }));

  return new Response(JSON.stringify(body), {
    headers: { "Content-Type": "application/json" },
  });
};

Visit /api/logs.json in your browser. You'll see:

GET /api/logs.json — response read-only
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[
  {
    id: launch-day,
    title: Launch day,
    date: 2026-10-14,
    author: Mae Jemison
  },
  {
    id: first-eva,
    title: First EVA,
    date: 2026-10-18,
    author: Sergei Volkov
  }
]

Same content collection you used in lesson 3 — just rendered as JSON instead of HTML. One source of truth, two output shapes.

 

This file is server-only. No JS reaches the browser. The endpoint is generated at build time as a static .json file.

— page 7 —
in the binder open binder →
saved a moment ago
progress 70%
earn +80 XP