#Astro DB and api route?

4 messages · Page 1 of 1 (latest)

brazen mist
#

How do I use astro db and api route together? provide an example of get and post request.

earnest lichenBOT
#

Hi @brazen mist. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Astro provides a way to interact with databases and handle API routes. Here's how you can use Astro DB and API routes together:

Astro DB

Astro DB is a fully-managed SQL database designed for the Astro ecosystem. It allows you to develop locally in Astro and deploy from your Astro Studio dashboard. With Astro DB, you can query and model content as a relational database. You can view, manage, and deploy your hosted remote data through your interactive Studio dashboard. source (https://docs.astro.build/en/guides/integrations-guide/db#_top)

API Routes

In Astro, an API route is a .js or .ts file in the src/pages/ folder, that takes a request and returns a response. API routes work by exporting a function that implements an HTTP method. source (https://astro.build/blog/experimental-server-side-rendering#api-routes)

Here's an example of how you can use Astro DB and API routes together for GET and POST requests:

GET Request

// src/pages/api/comments/[id].ts
import type { APIRoute } from "astro";
import { db, Comment } from 'astro:db';

export const GET: APIRoute = async (ctx) => {
  const comment = await db.select().from(Comment).where({ id: ctx.params.id });
  return new Response(JSON.stringify(comment), { status: 200 });
}

In this example, we're using a GET request to fetch a comment from the database using its ID.

POST Request

// src/pages/index.astro
---
import { db, Comment } from 'astro:db';

if (Astro.request.method === 'POST') {
  const formData = await Astro.request.formData();
  const author = formData.get('author');
  const content = formData.get('content');
#

if (typeof author === 'string' && typeof content === 'string') {
await db.insert(Comment).values({ author, content });
}
}

In this example, we're using a POST request to insert a new comment into the database. **source** (<https://docs.astro.build/en/guides/astro-db#insert>)

Remember to configure your Astro project for on-demand rendering and add an SSR adapter for your deployment environment when accepting user input.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------