Saltar al contenido principal

Restful API estáticos

  • Funcionan sin backend porque es generado de manera estática
  • Se crea el archivo con extensión json, ej. src/pages/api/get-product.json.ts
  • El archivo puede estar en cualquier ubicación, pero para agruparlos o simplificar las rutas, se puede crear una carpeta llamada /api
  • Se ingresa a la url como localhost:4321/api/get-product.json
  • Por defecto siempre devuelve el body en tipo texto
  • Al hacer la construcción a producción (bun run build) se genera el archivo en formato json, ej. dist/api/get-product.json y este solo tiene la sintaxis de JSON
src\pages\api\get-person.json.ts
import type { APIRoute } from "astro";

export const GET: APIRoute = async ({ params, request }) => {
  const person = {
    name: "John Doe",
    age: 30,
  };

  return new Response(JSON.stringify(person), {
    status: 200,
    headers: {
      "Content-Type": "application/json",
    },
  });
};
src\pages\api\posts\index.ts
import type { APIRoute } from "astro";
import { getCollection } from "astro:content";

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

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