Why does using OpenAI API to generate image not work

Hi there. I successfully did the chat completions api but when i change the endpoint and body for image generations i get a “Failed to fetch” error.

try {
const openaiResponse = await fetch(‘https://api.openai.com/v1/chat/completions’, {
method: ‘POST’,
headers: {
‘Authorization’: Bearer ${API_KEY},
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
model: ‘gpt-4o’,
messages: [
{ role: ‘system’, content: ‘You are a helpful game assistant.’ },
{ role: ‘user’, content: prompt }
],
temperature: 0.7,
}),
})

    if (!openaiResponse.ok) {
      const jsonResp = await openaiResponse.json()
      return {
        statusCode: openaiResponse.status,
        body: JSON.stringify({
          success: false,
          error: jsonResp,
        }),
      }
    } else {
      const jsonResp = await openaiResponse.json()
      return {
        statusCode: openaiResponse.status,
        body: JSON.stringify({
          success: true,
          imageInfo: jsonResp,
        }),
      }
    }
  } catch (error) {
    return {
      statusCode: 500,
      body: JSON.stringify({ error: 'OpenAI API call failed' }),
    };
  }

and i check the response in game.js like this

game(‘/startGame’, {
method: ‘POST’,
})
.then((body) => {
if(!body.data.success){
console.log(‘checking body success’)
AIWord = JSON.stringify(body.data.error, null, 2)
} else {
AIWord = JSON.stringify(body.data.imageInfo, null, 2)
}
})
.catch((err) => {
console.error(err)
})

If you run the code outside of 8th Wall does it fetch without errors?

Hi George, I tested using Postman and received successfull response. Any idea how to make it work on 8thWall?

Sounds like you’re probably running into a CORs issue. You probably need to Proxy your request through a Backend Function (I also recommend doing this to avoid leaking your API key on the client side)