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 using JavaScript to develop web apps. This guide is framework-independent.

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

  • (Optional) Node.js
  • Modern web browser

Install the Gemini API SDK

To use the Gemini API in your own web app, import @google/generative-ai:

<script type="importmap">
  {
    "imports": {
      "@google/generative-ai": "https://esm.run/@google/generative-ai"
    }
  }
</script>

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. Instead, you should pass your API key to your app right before initializing the model.

This guide assumes that you're accessing your API key as a global constant.

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.

<html>
<body>
  <!-- ... Your HTML and CSS -->
  <!-- Import @google/generative-ai, as shown above. -->
  <script type="module">
      import { GoogleGenerativeAI } from "@google/generative-ai";

      // Fetch your API_KEY
      const API_KEY = "...";

      // Access your API key (see "Set up your API key" above)
      const genAI = new GoogleGenerativeAI(API_KEY);

      const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash"});
  </script>
</body>
</html>

Make your first request

Generate text

async function run() {
  const prompt = "Write a story about an AI and magic"

  const result = await model.generateContent(prompt);
  const response = await result.response;
  const text = response.text();
  console.log(text);
}

run();

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.