#Astro API best practices

3 messages · Page 1 of 1 (latest)

unkempt meteor
#

Quick question, is each .ts page in something like pages/api/waitlist.ts it's own route? Like if I want to create a callback, I would create pages/api/callback.ts?

storm needleBOT
#

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", }, 
  })
}

You can find more information about API routes in Astro in this blog post (https://astro.build/blog/experimental-server-side-rendering#api-routes).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: