How to Setup Your AI API
OpenAI API
Before getting started, make sure you have completed the Next.js installation.
Installation
npm install openaiProject Structure
src/
├── app/
│ ├── api/
│ │ └── openai/
│ │ └── route.ts
│ ├── favicon.ico
│ ├── globals.css
│ ├── layout.tsx
│ └── page.tsxGet your API key here:
aistudio.google.comUsage
OPENAI_API_KEY=YOUR_OPENAI_API_KEYimport OpenAI from "openai";
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
const apiKey = process.env.OPENAI_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 OpenAI({ apiKey });
const response = await ai.responses.create({
model: "gpt-5-nano",
input: prompt
});
return NextResponse.json({ text: response.output_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:
npm run devUsing Postman
- Create a new POST request to
http://localhost:3000/api/openai - In the Body tab, select raw and add:
{
"prompt": "What is API?"
}- Click Send
Expected Response
{
"text": "Generated response from Gemini"
}