Integrating External APIs in Flutter

Integrating External APIs in Flutter

Date
1/25/2026

Flutter is a powerful framework for developing cross-platform mobile apps. One of Flutter's strengths is the easy integration of external APIs, allowing developers to enrich their apps with dynamic content and advanced features. In this article, I’ll show you how to integrate an external API into a Flutter app using the example of the OpenAI API. You’ll also learn how to securely store your personal API key by using the dotenv library.

What are APIs?

APIs (Application Programming Interfaces) are interfaces that allow different software applications to communicate with each other. They enable you to use data and functions from external services without having to write all the code yourself. An API provides a collection of endpoints that you can access to retrieve or send information. Examples of such services include Google Maps, weather services, and of course, the OpenAI API.

In this tutorial, we use the OpenAI API to integrate the power of GPT-4 into our Flutter app. We’ll show you how to fetch data from the API using HTTP requests.

Steps to Integrate the OpenAI API in Flutter

  1. Set up a Flutter project

Before we start integrating the API, create a new Flutter project:

flutter create openai_flutter_demo

  1. Add required packages

To communicate with the API, we need the http package, which enables HTTP requests in Flutter. Additionally, we use the flutter_dotenv package to securely store our API key. To use this package, we’ll create a .env file in our project folder, which we’ll need to access later. To make it accessible from Dart, add it to your assets. Open pubspec.yaml and add the following dependencies and assets:

dependencies:
  flutter:
    sdk: flutter
  http: ^0.14.0
  flutter_dotenv: ^5.0.2

assets:
  -.env

Then save the pubspec.yaml or run the following command in the terminal.

flutter pub get

  1. Obtain an API key from OpenAI

To access the OpenAI API, you need an API key. This can be generated via the OpenAI website. Log in there, create a project, and copy your API key.

  1. Store the API key securely

It’s important to store your API key securely and not embed it directly in your code. The flutter_dotenv package helps us manage environment variables in a .env file. This also protects the API key from being uploaded to Github and downloaded by other users.

Create a .env file in the root directory of your project and add your API key there:

OPENAI_API_KEY=#your_api_key#

Now we need to ensure that the .env file is loaded. To do this, open the main.dart file and load the environment variables at the very beginning of the main method:

import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

void main() async {
  await dotenv.load();  // Loads the .env file
  runApp(MyApp());
}

  1. Send an HTTP request to the OpenAI API

Now that we have installed the necessary packages and securely stored the API key, we can send a request to the OpenAI API. For this, we’ll create a simple function that sends a request to the OpenAI API to get a response from the GPT-3 or GPT-4 model.

Add the following function to your Dart file:

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';

Future<String> fetchOpenAIResponse(String prompt) async {
  final apiKey = dotenv.env['OPENAI_API_KEY'];  // Access the API key from the .env file
  if (apiKey == null) {
    throw Exception('API key missing!');
  }

  final url = Uri.parse('https://api.openai.com/v1/chat/completions');
  final headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer $apiKey',
  };

  final body = jsonEncode({
    'model': 'gpt-4o',  // GPT-4 model, can be changed as needed
    'messages': [
        {
          "role": "user",
          "content": [
            {
              "type": "text",
              "text": prompt
            }
          ]
        }
    ],
  });

  final response = await http.post(url, headers: headers, body: body);

  if (response.statusCode == 200) {
    final data = jsonDecode(response.body);
    return data['choices'][0]['message']['content'];
  } else {
    throw Exception('Error requesting the API: ${response.statusCode}');
  }
}

This fetchOpenAIResponse function sends a request to the OpenAI API and returns the model’s response as text. You can adjust the model and other parameters, such as max_completion_tokens, to control the output. The OpenAI API documentation provides more information about the parameters to pass and the response. In the example, we retrieve the AI’s answer from the response, which is returned in JSON format. A response body might look like this:

{
  "id": "chatcmpl-xxx",
  "object": "chat.completion",
  "created": 1677652288,
  "model": "gpt-4o",
  "system_fingerprint": "fp_44709d6fcb",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "Hello! How can I help you?",
    },
    "logprobs": null,
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 12,
    "total_tokens": 21,
    "completion_tokens_details": {
      "reasoning_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    }
  }
}

As you can see, the answer to our prompt is located under choices –> index 0 (since it’s a list) –> message –> content. 

  1. Display results in the app

To display the response from OpenAI in your app, you can create a simple user interface. In the main.dart file, add a simple UI that shows the text from the OpenAI model:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter OpenAI Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: Scaffold(
        appBar: AppBar(title: Text('OpenAI Flutter Demo')),
        body: OpenAIResponseWidget(),
      ),
    );
  }
}

class OpenAIResponseWidget extends StatefulWidget {
  @override
  _OpenAIResponseWidgetState createState() => _OpenAIResponseWidgetState();
}

class _OpenAIResponseWidgetState extends State<OpenAIResponseWidget> {
  String _response = '';
  final TextEditingController _controller = TextEditingController();

  void _getResponse() async {
    final prompt = _controller.text;
    final response = await fetchOpenAIResponse(prompt);
    setState(() {
      _response = response;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: [
          TextField(
            controller: _controller,
            decoration: InputDecoration(labelText: 'Enter your text'),
          ),
          SizedBox(height: 10),
          ElevatedButton(
            onPressed: _getResponse,
            child: Text('Generate response'),
          ),
          SizedBox(height: 20),
          Text(
            _response.isEmpty ? 'Response will appear here' : _response,
            style: TextStyle(fontSize: 18),
          ),
        ],
      ),
    );
  }
}

Here, users can enter text, which is then sent as a prompt to the OpenAI API. The response is displayed below the text field.

Conclusion

Integrating external APIs into Flutter apps is a great way to add extra features like AI, weather data, geolocation, or social networks to your app. In this example, we saw how to integrate the OpenAI API to bring GPT-4 into a Flutter app. By using the dotenv library, we securely stored the API key and thus avoided potential security risks.

With these basics, you can integrate many more APIs and expand your app with interesting and useful features.

Comments

Please sign in to leave a comment.