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);
});