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 that you're familiar with building applications with Go.

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

  • Go 1.20+

Install the Gemini API SDK

To use the Gemini API in your own application, you need to get the Go SDK package in your module directory:

go get github.com/google/generative-ai-go

Authenticate

Set up your API key

To use the Gemini API, you'll need an API key. If you don't already have one, create a key in Google AI Studio.

Get an API key

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 an environment variable instead:

export API_KEY=<YOUR_API_KEY>

Initialize the model

Before you can make any API calls, you need to import and initialize the model. Gemini 1.5 models are versatile and work with both text-only and multimodal prompts.

import "github.com/google/generative-ai-go/genai"
import "google.golang.org/api/option"

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
    log.Fatal(err)
}
defer client.Close()

model := client.GenerativeModel("gemini-1.5-flash")

Make your first request

Generate text

resp, err := model.GenerateContent(ctx, genai.Text("Write a story about a AI and magic"))
if err != nil {
  log.Fatal(err)
}

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:

If you're new to working with generative AI or the Gemini API, check out the following guides, which will help you understand the Gemini API programming model:

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