Endpoints & API Routes
route ที่ return data ไม่ใช่หน้า
หัวข้อที่มีชื่อว่า “route ที่ return data ไม่ใช่หน้า”ไม่ใช่ทุก route ที่ render HTML ไฟล์ใน src/pages/ ที่นามสกุล .ts (หรือ .js) คือ API endpoint: แทนที่จะมี template จะ export function ที่ตั้งชื่อตาม HTTP method (GET, POST, PUT, DELETE) ซึ่งแต่ละตัว return Response มาตรฐาน
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
อ่าน params และ body
หัวข้อที่มีชื่อว่า “อ่าน params และ body”handler รับ context ที่มี request, params, cookies และอื่น ๆ:
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)"]
static vs on-demand endpoint
หัวข้อที่มีชื่อว่า “static vs on-demand endpoint”เหมือนหน้า endpoint จะ build ครั้งเดียวหรือรันต่อ request ก็ได้:
- static — เมื่อ
output: 'static'GETendpoint จะรันตอน build แล้วเขียน body ของResponseลงไฟล์ เหมาะกับการ generaterss.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;endpoint vs Actions
หัวข้อที่มีชื่อว่า “endpoint vs Actions”ทั้งคู่รัน 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 หรือ
Responseplumbing หยิบมาใช้กับ mutation และ form ของแอปตัวเอง
หลักจำง่าย ๆ: สัญญาแบบ public/external → endpoint; internal app logic ที่เรียกจาก frontend ตัวเอง → Action