My API request functions properly on local but not on Test Flight

I’m encountering an issue where my API request works perfectly in the local development environment but fails when running the app through TestFlight. The problem specifically occurs when making a POST request to the OpenAI API for generating notes based on user input.

Welcome to the dev community @deionstfleur13

How do you know it’s failing? Do you see any errors?

1 Like

this is my code and it works on my local development but after i push to test flight and test on my phone i get the error, which I don’t get on my local development.

const fetchNotesFromOpenAI = async () => {
      setLoading(true); // Start the loading spinner
    
      const prompt = [
        {
          role: "system",
          content: "You are a helpful assistant."
        },
        {
          role: "user",
          content: `Generate notes based on the following text: ${documentText}`
        }
      ];
    
      try {
        const response = await fetch('${url}', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${myApi}`
          },
          body: JSON.stringify({
            model: "gpt-3.5-turbo",
            messages: prompt,
          }),
        });
    
        const data = await response.json();
    
        if (response.ok) {
          setGeneratedNotes(data.choices[0].message.content); // Store generated notes
        } else {
          console.error("Error:", data);
          Alert.alert('Error', 'Something went wrong while fetching the notes.');
        }
      } catch (error) {
        console.error("Error in fetching data from OpenAI:", error);
        Alert.alert('Error', 'Failed to fetch notes from OpenAI.');
      } finally {
        setLoading(false); // Stop the loading spinner
      }
    };
1 Like

Right, but what error code are you getting?

Or does it just fail?

https://platform.openai.com/docs/guides/error-codes

2 Likes

It is just failing when I go to test on my phone.

Check the server logs to see what error it’s throwing or have it print error to screen maybe.

1 Like

I am getting this error, however I am providing the api key in my .env. Also it works on local . Do you know how I can resolve this?

Verify that the API key is correctly retrieved from secure storage in the TestFlight environment. Try logging the value to ensure it’s being accessed correctly (Do this temporarily, and make sure to remove any sensitive logs afterward).

You need to include the authorization header containing a valid API key in your API calls.

e.g

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
     "model": "gpt-4o-mini",
     "messages": [{"role": "user", "content": "Say this is a test!"}],
     "temperature": 0.7
   }'

Here’s authentication docs.

This is expected? Environment dependent symbol?