Flex App
FLEX APP
Pricing
Back to blogs
How to Integrate OpenAI GPT API with React Native and Expo: Step-by-Step Guide
May 18, 2025

How to Integrate OpenAI GPT API with React Native and Expo: Step-by-Step Guide

Adding AI-powered features to mobile apps has never been easier, especially with the rise of powerful APIs like OpenAI's GPT. This blog walks through integrating OpenAI's GPT API into a React Native app using Expo — a combination that allows you to build intelligent, user-friendly applications with speed.

Whether you're creating a chatbot, a content assistant, or any interactive AI feature, this guide will help you set up the basics and understand the building blocks behind the implementation.


Why Integrate OpenAI into a Mobile App?

OpenAI's API gives your app the ability to:

  • Generate human-like text
  • Summarize content
  • Translate text
  • Answer questions
  • Simulate conversations

... and much more. With mobile devices becoming primary tools for communication, education, and productivity, integrating GPT into a React Native app opens up a world of opportunities.


Prerequisites

Before we begin, make sure you have the following:

  • Node.js and npm installed
  • Expo CLI installed (npm install -g expo-cli)
  • An OpenAI account and API key from OpenAI's API dashboard

Step 1: Create a New Expo Project

First, start with a new Expo project:

expo init openai-expo-app
cd openai-expo-app

Choose the blank template (JavaScript or TypeScript, depending on your preference).


Step 2: Install Axios

We'll use axios to make API requests to OpenAI.

npm install axios

Why Axios? It simplifies working with HTTP requests and has a cleaner syntax than fetch.


Step 3: Set Up the OpenAI API Call

Let’s create a utility function to interact with OpenAI.

services/openai.js

import axios from 'axios';

const API_KEY = 'your-openai-api-key-here';

export const getChatResponse = async (userPrompt) => {
  try {
    const response = await axios.post(
      'https://api.openai.com/v1/chat/completions',
      {
        model: 'gpt-3.5-turbo',
        messages: [
          { role: 'system', content: 'You are a helpful assistant.' },
          { role: 'user', content: userPrompt }
        ],
      },
      {
        headers: {
          'Authorization': `Bearer ${API_KEY}`,
          'Content-Type': 'application/json',
        },
      }
    );
    return response.data.choices[0].message.content;
  } catch (error) {
    console.error('OpenAI API error:', error);
    return 'Sorry, something went wrong.';
  }
};

Explanation

  • This function sends a POST request to OpenAI’s chat/completions endpoint.
  • The model used is gpt-3.5-turbo, which is efficient and powerful for conversational applications.
  • The messages array starts with a system message that defines the assistant’s role.
  • Then it adds the userPrompt, representing what the user types.
  • It returns the AI's response or an error message if something goes wrong.

🔐 Note: Replace 'your-openai-api-key-here' with your actual API key. Never commit it to source control. Use secure environment variables in production.


Step 4: Build the UI

Let’s create a simple interface where the user can type a question and receive a response.

App.js

import React, { useState } from 'react';
import { StyleSheet, Text, TextInput, View, Button, ScrollView } from 'react-native';
import { getChatResponse } from './services/openai';

export default function App() {
  const [input, setInput] = useState('');
  const [response, setResponse] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSend = async () => {
    if (!input.trim()) return;
    setLoading(true);
    const reply = await getChatResponse(input);
    setResponse(reply);
    setLoading(false);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Ask AI Anything</Text>

      <TextInput
        style={styles.input}
        placeholder="Type your question..."
        value={input}
        onChangeText={setInput}
      />

      <Button title={loading ? 'Thinking...' : 'Ask'} onPress={handleSend} disabled={loading} />

      <ScrollView style={styles.responseBox}>
        <Text style={styles.responseText}>{response}</Text>
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    paddingTop: 60,
    paddingHorizontal: 20,
    flex: 1,
    backgroundColor: '#fff',
  },
  title: {
    fontSize: 24,
    marginBottom: 20,
    fontWeight: 'bold',
  },
  input: {
    borderColor: '#ccc',
    borderWidth: 1,
    padding: 10,
    borderRadius: 6,
    marginBottom: 10,
  },
  responseBox: {
    marginTop: 20,
    backgroundColor: '#f0f0f0',
    padding: 10,
    borderRadius: 6,
  },
  responseText: {
    fontSize: 16,
  },
});

How This Works:

  • Users type into the TextInput, and the text is stored in input.
  • On button click, getChatResponse is called.
  • The returned response is displayed inside a ScrollView for better UX.
  • While waiting for a reply, the button is disabled and shows “Thinking…”.

Step 5: Run Your App

You can now start your Expo app:

expo start

Scan the QR code using your Expo Go app. Once loaded, type a question and watch AI magic happen!


Tips & Best Practices

  • 🔐 Secure your API key using environment variables
  • 📉 Handle rate limits by monitoring the API response and implementing retries/backoffs
  • 🔁 Throttle requests to prevent excessive usage and token consumption
  • 💬 Enhance the conversation by storing and sending full message history
  • 🛡 Gracefully handle errors to improve UX when API fails or limits are hit

What’s Next?

Here are a few ideas to expand the app:

  • 🗣 Voice input and output with expo-speech and expo-speech-to-text
  • 🖼 Image generation using OpenAI's DALL·E API
  • 🧠 Maintain conversation context/history
  • 🎭 Build custom personas with detailed system instructions
  • ☁️ Sync chat data with Firebase or Supabase

Conclusion

Integrating OpenAI into a React Native app using Expo makes it easy to create smart, conversational features. Whether it’s a chatbot, an educational assistant, or a content generator, you’ve now got the tools to get started.

Keep experimenting, keep building — the possibilities are endless with AI!