Gemini API quickstart

This quickstart shows you how to get started with the Gemini API using the SDK of your choice.


Prerequisites

This quickstart assumes you're familiar with building applications with Dart.

To complete this quickstart, make sure that your development environment meets the following requirements:

  • Dart 3.2.0+

Install the Gemini API SDK

To use the Gemini API in your own application, you need to add the google_generative_ai package to your Dart or Flutter app:

Dart

dart pub add google_generative_ai

Flutter

flutter pub add google_generative_ai

Set up authentication

The easiest way to authenticate to the Gemini API is to configure an API key, as described in this section. If you need stricter access controls, you can use OAuth instead.

If you don't already have an API key, create one in Google AI Studio.

Get an API key from Google AI Studio

Then, configure your key.

It is strongly recommended that you do not check an API key into your version control system but assign it as a process environment variable instead. If you're developing a Flutter app, you can use String.fromEnvironment and pass --dart-define=API_KEY=$API_KEY to flutter build or flutter run to compile with the API key since the process environment will be different when running the app.

Import the library

Import and configure the Google Generative AI library.

import 'package:google_generative_ai/google_generative_ai.dart';

// Access your API key as an environment variable (see "Set up your API key" above)
final apiKey = Platform.environment['API_KEY'];
if (apiKey == null) {
  print('No \$API_KEY environment variable');
  exit(1);
}

Make your first request

Use the generateContent method to generate text.

// Make sure to include this import:
// import 'package:google_generative_ai/google_generative_ai.dart';
final model = GenerativeModel(
  model: 'gemini-1.5-flash',
  apiKey: apiKey,
);
final prompt = 'Write a story about a magic backpack.';

final response = await model.generateContent([Content.text(prompt)]);
print(response.text);

What's next

Now that you're set up to make requests to the Gemini API, you can use the full range of Gemini API capabilities to build your apps and workflows. To get started with Gemini API capabilities, see the following guides:

For in-depth documentation of Gemini API methods and request parameters, see the guides in the API reference.