AxiosError: Request failed with status code 401 [Solved]

Getting the “AxiosError: Request failed with status code 401” every time I run this nodejs code (I’ve simplified the prompt for the purposes of this post) to call the openai API in the mac terminal.
I’ve checked - the api key is correct, the endpoint is correct, and I even updated my installation of node, npm, axios and dotenv.
Perhaps the API key doesn’t have the right privileges but there is no way to check this as far as I know - I’ve looked at the doc and everywhere on the dashboard.
What am I missing? I looked at similar posts on this forum but nothing seems directly relevant. There is an example implementation by Twilio but it uses the “got” package for HTTP requests and not axios - though that shouldn’t matter since this seems like an authentication denial from openai?

const axios = require('axios');
require('dotenv').config()
const openai_api_key = process.env.OPENAI_API_KEY

// Define the prompt
const prompt = `Hello`;

// Make the API call
axios.post('https://api.openai.com/v1/engines/davinci/completions', {
    prompt: prompt,
    max_tokens: 1024,
    temperature: 0.5
  },
  {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${openai_api_key}`
    }
  }
)
.then(response => {
    // Extract the generated text from the API response
    const generatedText = response.data.choices[0].text;
    console.log(generatedText)
  })
  .catch(error => {
    console.log(error);
  });

I tried this in playground generating curl code and it worked (after I created a new API key and deleted the old key). It didn’t work in nodejs even with the new key. Which was puzzling…

Thx to デベロッパー on the discord OpenAI/api-support for pointing out that the endpoint in the nodejs code was indeed wrong.

I had originally asked chatGPT to generate the nodejs code and it put the wrong endpoint (https://api.openai.com/v1/engines/davinci/completions) in there. The correct endpoint is https://api.openai.com/v1/completions as is mentioned in the doc.
I’ve since submitted a prompt to chatgpt to correct the model so that it now generates the correct endpoint -
mark this as solved -

2 Likes

please suggest me which file add axios file then work properly

I know is late reply. But did you try to extend timeout? Axios by default set zero value to timeout.