Building APIs with Astro
Learn how to create powerful API endpoints using Astro's server-side capabilities.
Introduction
Astro isn't just for static sites - it's also great for building APIs!
Creating an API Endpoint
Create a file in src/pages/api/:
// src/pages/api/hello.ts
export async function GET() {
return new Response(JSON.stringify({ message: "Hello!" }), {
headers: { "Content-Type": "application/json" }
});
}
Handling POST Requests
export async function POST({ request }) {
const data = await request.json();
// Process data...
return new Response(JSON.stringify({ success: true }));
}
Best Practices
- Always validate input
- Use proper error handling
- Return appropriate status codes
Happy API building!
Comments
Sign in to leave a comment.