Saltar al contenido principal

API Endpoints

  • Pueden estar todos los endpoints en el mismo archivo, mientras los métodos sean diferentes (get, post, put, etc.)
src\pages\api\posts[slug].ts
export const GET: APIRoute = async ({ request, params }) => {
  const { slug } = params;

  const post = await getEntry("blog", slug as any);

  if (!post) {
    return new Response("Not found", { status: 404 });
  }

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

};

export const POST: APIRoute = async ({ request, params }) => {
  const body = await request.json();

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

export const PUT: APIRoute = async ({ request, params }) => {
};

export const PATCH: APIRoute = async ({ request, params }) => {
};

export const DELETE: APIRoute = async ({ request, params }) => {
};

Ejemplo uso

src\components\likes\LikeCounter.svelte
// GET
const resp = await fetch(`/api/posts/likes/${postId}`);
const data = await resp.json();

// PUT
fetch(`/api/posts/likes/${postId}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ likes: likeClicks }),
});

Segmentos de ruta

  • Los segmentos de ruta o params se obtienen de forma diferente si es una API endpoint o una página como page/products.astro
mypage.com/api/posts/first-post
src\pages\api\posts[slug].ts
export const GET: APIRoute = async ({ request, params }) => {
  // Extraer segmento de ruta
  const { slug } = params;
  const post = await getEntry("blog", slug as any);

  if (!post) {
    return new Response("Not found", { status: 404 });
  }

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

};

Query parameters

  • Las query parameters solo funcionan en SSR (server) y no en SSG (static)
  • Los query parameters son opcionales
  • Se envían en la URL, ej. mipagina.com/post?slug=titulo
  • Si se requieren parámetros obligatorios, se hace como segmentos de URL pagina.com/año/mes/dia
mypage.com/api/posts?slug=post-name
src\pages\api\posts\index.ts
import type { APIRoute } from "astro";
import { getCollection, getEntry } from "astro:content";

export const GET: APIRoute = async ({ request, url }) => {
  const slug = url.searchParams.get("slug");

  if (slug) {
    // Get a single post
    const post = await getEntry("blog", slug);
    if (!post) {
      return new Response("Not found", { status: 404 });
    }

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

  // Get all posts
  const posts = await getCollection("blog");

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

};