🔌

Astro の API エンドポイントで JSON を返す

エンドポイントとは

.ts ファイルを src/pages/ に置き、GET 関数を export すると、 HTML ではなく任意のレスポンス(JSON など)を返せます。

例: 記事一覧を JSON で返す

import { getCollection } from "astro:content";

export async function GET() {
  const posts = await getCollection("blog");
  const data = posts.map((p) => ({ slug: p.id, title: p.data.title }));
  return new Response(JSON.stringify(data), {
    headers: { "Content-Type": "application/json" },
  });
}

/search.json のようなエンドポイントを用意しておくと、クライアント側の検索やAPI連携に使えます。