Krave
How to Setup Your AI API

Gemini API

Before getting started, make sure you have completed the Next.js installation.

Installation

npm install @google/genai

Project Structure

src/
├── app/
│   ├── api/
│   │   └── gemini/
│   │       └── route.ts
│   ├── favicon.ico
│   ├── globals.css
│   ├── layout.tsx
│   └── page.tsx

Get your API key here:

aistudio.google.com

Usage

.env
GEMINI_API_KEY=YOUR_GEMINI_API_KEY
src/app/api/gemini/route.ts
import { GoogleGenAI } from "@google/genai";
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
    const apiKey = process.env.GEMINI_API_KEY;
    const { prompt } = await req.json();

    if (!apiKey) {
        return NextResponse.json({ error: "API Key is missing." }, { status: 400 });
    }

    if (!prompt) {
        return NextResponse.json({ error: "Prompt is required." }, { status: 400 });
    }

    try {
        const ai = new GoogleGenAI({ apiKey });
        const response = await ai.models.generateContent({
            model: "gemini-3-flash-preview",
            contents: { text: prompt },
        });

        return NextResponse.json({ text: response.text })
    } catch (error: any) {
        console.error("Error generating content:", error);
        return NextResponse.json(
            { error: error.message || "Something went wrong" },
            { status: 400 }
        );
    }
}

Testing

Start the development server:

Terminal
npm run dev

Using Postman

  1. Create a new POST request to http://localhost:3000/api/gemini
  2. In the Body tab, select raw and add:
{
    "prompt": "What is API?"
}
  1. Click Send

Expected Response

{
    "text": "Generated response from Gemini"
}

On this page