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>

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 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. 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.

Import the library

Import and configure the Google Generative AI library.

<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 = "...";
  </script>
</body>
</html>

Make your first request

Use the generateContent method to generate text.

// Make sure to include these imports:
// import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

const prompt = "Write a story about a magic backpack.";

const result = await model.generateContent(prompt);
console.log(result.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.