API Call
src/pages/api
directory. src/routes/api
directory. Any file inside the src/pages
ending with .js
/.ts
can be an API enpoint.
The good thing with APIs with Launchfa.st is that you get to use the Web APIs on top of Astro. This ensures that the code can be reused in any number of projects irresepctive of their stack.
Find more on the API Routes in Astro at https://docs.astro.build/en/core-concepts/endpoints.
Any file inside the src/routes
ending with +server.ts
can be an API enpoint.
Find more on the API Routes in SvelteKit at https://kit.svelte.dev/docs/routing#server.
Protected API Routes
To illustrate, to create an API route that returns whether a user is logged in or not, follow the steps in the LaunchFa.st template:
- Create a file:
src/pages/api/test.js
. - Add the content below to the
test.js
:
// Filename: src/pages/api/test.js
// Handle GET Request to /api/test
export async function GET({ request }) {
// Get the user session from the 'request'
const session = getSession(request)
if (!session) {
return new Response('unauthenticated', {
status: 403,
})
}
return new Response('authenticated', {
status: 200,
})
}
// Handle POST Request to /api/test
export async function POST({ request }) {
// Parse the incoming form data from the 'request'
const context = await request.formData()
// Get the user session from the 'request'
const session = getSession(request)
if (!session) {
return new Response('unauthenticated', {
status: 403,
})
}
return new Response('authenticated', {
status: 200,
})
}
- Create a file:
src/route/api/test/+server.ts
. - Add the content below to the
+server.ts
:
import { json, error } from '@sveltejs/kit'
import type { RequestEvent } from './$types'
import { getSession } from '@/lib/utils/auth'
// Handle GET Request to /api/test
export async function GET(event: RequestEvent) {
// Get the user session from the 'request'
const user = getSession(event.request)
if (!user) {
throw error(403)
}
// Extract the 'file' parameter from the request URL and do something
const url = new URL(event.request.url)
const file = url.searchParams.get('file')
}
// Handle POST Request to /api/test
export async function POST(event: RequestEvent) {
// Get the user session from the 'request'
const user = getSession(event.request)
if (!user) {
throw error(403)
}
if (user.email) {
const data = await event.request.formData()
// Get the 'file' field from the form data
const file = data.get('file')
}
}