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 Google AI 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

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

export API_KEY=<YOUR_API_KEY>

Import the library

Import the Google Generative AI library and create a client.

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()

Make your first request

Use the generateContent method to generate text.

model := client.GenerativeModel("gemini-1.5-flash")
resp, err := model.GenerateContent(ctx, genai.Text("Write a story about a magic backpack."))
if err != nil {
	log.Fatal(err)
}

printResponse(resp)

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.