ข้ามไปยังเนื้อหา

Endpoints & API Routes

ไม่ใช่ทุก route ที่ render HTML ไฟล์ใน src/pages/ ที่นามสกุล .ts (หรือ .js) คือ API endpoint: แทนที่จะมี template จะ export function ที่ตั้งชื่อตาม HTTP method (GET, POST, PUT, DELETE) ซึ่งแต่ละตัว return Response มาตรฐาน

src/pages/api/health.ts
import type { APIRoute } from 'astro';
export const GET: APIRoute = () => {
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
};

ตอนนี้ GET /api/health return JSON แล้ว type APIRoute ให้ context argument แบบ typed และ return เป็น Response — รูปแบบ web-standard เดียวกับที่อื่นใน Astro

handler รับ context ที่มี request, params, cookies และอื่น ๆ:

src/pages/api/users/[id].ts
import type { APIRoute } from 'astro';
export const GET: APIRoute = async ({ params }) => {
const user = await db.users.find(params.id); // [id] from the path
if (!user) return new Response('Not found', { status: 404 });
return Response.json(user); // shorthand JSON response
};
export const POST: APIRoute = async ({ request }) => {
const body = await request.json(); // parse the request body
const created = await db.users.create(body);
return Response.json(created, { status: 201 });
};
flowchart LR
  req["GET or POST /api/..."] --> handler["exported handler
(GET / POST / ...)"]
  handler --> read["read params, request body, cookies"]
  read --> resp["return a Response
(JSON, file, status)"]
endpoint map method ไปสู่ Response

เหมือนหน้า endpoint จะ build ครั้งเดียวหรือรันต่อ request ก็ได้:

  • static — เมื่อ output: 'static' GET endpoint จะรันตอน build แล้วเขียน body ของ Response ลงไฟล์ เหมาะกับการ generate rss.xml, sitemap, หรือ static JSON API ที่ไม่เปลี่ยนต่อ request (static endpoint รองรับแค่ GET)
  • on-demand — เพิ่ม export const prerender = false (และ adapter) เพื่อรัน endpoint ต่อ request เปิดใช้ POST/PUT/DELETE, request body และ live data
// A dynamic endpoint that handles form posts:
export const prerender = false;

ทั้งคู่รัน server code แต่แก้คนละปัญหา:

  • endpoint คือ HTTP route ดิบที่คุณออกแบบเอง — คุณเป็นเจ้าของ URL, method, status code และรูปแบบ response หยิบมาใช้กับ webhook, integration กับ third-party, การดาวน์โหลดไฟล์ หรือ REST/JSON API สาธารณะ
  • Action (บทถัดไป) คือ type-safe function ที่คุณเรียกจาก client code ของตัวเองพร้อม input validation อัตโนมัติ — ไม่มี URL หรือ Response plumbing หยิบมาใช้กับ mutation และ form ของแอปตัวเอง

หลักจำง่าย ๆ: สัญญาแบบ public/external → endpoint; internal app logic ที่เรียกจาก frontend ตัวเอง → Action

คุณ define API endpoint ใน Astro อย่างไร?
static (build-time) endpoint รองรับ method อะไรบ้าง?
เมื่อไรควรใช้ Action แทน endpoint?
endpoint handler return อะไร?