return new Response(JSON.stringify(result), {
status: 200,
headers: {
"Content-Type": "application/json"
}
});
} catch (error) {
return new Response(JSON.stringify({ error: 'Error updating resource' }), {
status: 500,
headers: {
"Content-Type": "application/json"
}
});
}
}
// DELETE request handler
export async function DELETE({ params }) {
const { id } = params;
// Process deletion (example)
const result = {
id,
deleted: true,
method: 'DELETE'
};
return new Response(JSON.stringify(result), {
status: 200,
headers: {
"Content-Type": "application/json"
}
});
}
// Catch-all handler for other HTTP methods
export async function ALL({ request }) {
return new Response(JSON.stringify({
error: Method ${request.method} Not Allowed
}), {
status: 405,
headers: {
"Content-Type": "application/json",
"Allow": "GET, POST, PUT, DELETE"
}
});
}
This template includes handlers for GET, POST, PUT, and DELETE requests, as well as a catch-all handler for other HTTP methods. It demonstrates how to:
- Access query parameters and route parameters
- Parse request bodies
- Use secret environment variables
- Handle different types of responses and status codes
- Implement error handling
Remember to adjust the file name and path according to your desired API endpoint structure. Also, ensure that you have SSR mode enabled in your Astro configuration (`output: 'server'`) and that you're using an appropriate adapter for your deployment platform.