#Astro API best practices
3 messages · Page 1 of 1 (latest)
Hi @unkempt meteor. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, you're correct. In Astro, each .ts or .js file in the src/pages/ directory is its own route. For example, a file named waitlist.ts in the src/pages/api/ directory would correspond to the /api/waitlist route. Similarly, if you want to create a callback route, you would create a file named callback.ts in the src/pages/api/ directory, which would correspond to the /api/callback route.
These files are known as API routes in Astro. They take a request and return a response. You can use them to build various server-side functionalities like form submission handlers, upload handlers, REST APIs, and dynamic asset routes.
Here's an example of an API route that saves a user profile:
// Example: src/pages/api/profile.js
export async function post(params, request) {
const profile = await request.json()
await saveProfile(profile)
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { "Content-Type": "application/json", },
})
}