Search code examples
next.jsopenai-apinext.js14

How to send GET request to Open AI API with Next.js 14


I'm trying to make a simple GET request to the open ai gpt API with Next.js 14 and then just display the results in console log but I get this error: Failed to parse URL from /api/codelang

Here is the app/test/page.js:

export default async function Page() {
  const res = await fetch('/api/codelang', {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' }
  });
  
  if (res.ok) {
    const data = await res.json();
    console.log(data);
  } else {
    console.error('HTTP error:', res.status, res.statusText);
  }
}

Here is my app/api/code/route.js:

import { NextResponse } from "next/server";
import OpenAI from "openai"

export async function GET(request) {

  const openai = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY
  })

  const response = await openai.chat.completions.create({
    model: "gpt-3.5-turbo-0125",
    response_format: { type: "json_object" },
    messages: [
      {
        role: "system",
        content: `provide some examples of Python code in JSON format`
      },
      {
        role: "user",
        content: "I want to see some examples of Python. Please provide the JSON output."
      }
    ],
    temperature: 0.8,
    max_tokens: 1024,
    top_p: 1,
    frequency_penalty: 0,
    presence_penalty: 0,
  })

  return NextResponse.json(response)
}

Solution

  •   const res = await fetch('/api/codelang', {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
      });
    

    When fetching on the server, you need to pass the full URL not only the pathname.

      // You can make the base url in a shared variable or environment variable
      const res = await fetch(`${config.APP_URL}/api/codelang`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
      });