Below is a checklist and some changes you can try to resolve the “Network Request Failed” error when calling the OpenAI API from your Expo app:
1. Use the Correct Request Payload
For the Chat Completion endpoint the API expects a JSON body with a field named “messages” (an array of message objects) rather than “prompt.” For example:
await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": `Bearer ${process.env.EXPO_PUBLIC_API_KEY}`,
},
body: JSON.stringify({
model: "gpt-4o-mini",
messages: [
{
role: "user",
content: prompt,
}
],
temperature: 0.7,
}),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error("Error making request:", error.message, error.stack);
});
Making sure the payload matches the API’s specification will allow the server to interpret your request correctly.
2. Verify Your API Key
-
Environment Variable:
Make sure that process.env.EXPO_PUBLIC_API_KEY
is correctly set in your project. In Expo managed projects, environment variables may need to be passed through a Babel config or defined in your app.config.js
/app.json
(via extra config) so they can be injected at build time.
-
Key Validity:
Double-check that the API key is valid and not empty or malformed.
3. Android Network Permissions in Expo
In a managed Expo project, you don’t modify the native AndroidManifest.xml directly. Instead, add the permissions in your app.json
(or app.config.js
) like this:
{
"expo": {
"android": {
"permissions": ["INTERNET"]
}
}
}
Since your request uses HTTPS, you don’t need to enable cleartext traffic. In any case, Expo already handles many of the native configurations for you.
4. Check Network Conditions and Debugging
-
Simulator/Device Network:
Ensure that the device or emulator has an active internet connection. Sometimes network errors arise because of connectivity issues on the testing environment.
-
Detailed Error Logging:
The error “Network Request Failed” can sometimes mask the underlying cause. Adding more error logging or using tools like Flipper might help diagnose whether it’s a certificate issue, a DNS problem, or something else.
Recap
- Payload: Use “messages” rather than “prompt” when calling the chat completions endpoint.
- API Key: Confirm that your API key is correctly set up and valid.
- Expo Permissions: Ensure your Expo project has the necessary network permissions in
app.json
.
- Testing Environment: Verify your device/emulator’s connectivity.
Applying these changes should help you overcome the “Network Request Failed” error when interfacing with the OpenAI API.