A Complete Guide to Using the Gemini API by Programming Language [Java/Python/JavaScript/C#/GAS/Shell Supported]

先生

A Complete Guide to Using the Gemini API by Programming Language [Java/Python/JavaScript/C#/GAS/Shell Supported

The Gemini API (Google’s generative AI API) supports integration with a wide variety of programming languages. In this article, we provide a comprehensive guide to using the Gemini API in major languages, with sample code and step-by-step instructions for setup and execution.


1. What Is the Gemini API?

The Gemini API is a multimodal generative AI API provided by Google. It supports text generation, image generation, code generation, and more—competing with OpenAI’s ChatGPT. Hosted on Google Cloud, it can be accessed from various programming languages by obtaining an API key.


2. Getting Started: Obtain API Key and Set Up Environment

First, create a project in the Google Cloud Console, enable the Gemini API, and retrieve your API key. You can either set the key as an environment variable or include it directly in your code.


3. Example: Python

import google.generativeai as genai

genai.configure(api_key="YOUR_API_KEY")
model = genai.GenerativeModel("gemini-pro")
response = model.generate_content("Hello, please introduce yourself.")
print(response.text)

4. Example: Java

In Java, you can use the built-in HttpClient to send a request to the Gemini API.

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=YOUR_API_KEY"))
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString("{\"contents\": [{\"parts\": [{\"text\": \"Hello, please introduce yourself.\"}]}]}"))
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());

5. Example: C#

var client = new HttpClient();
var request = new HttpRequestMessage
{
    Method = HttpMethod.Post,
    RequestUri = new Uri("https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=YOUR_API_KEY"),
    Content = new StringContent("{\"contents\": [{\"parts\": [{\"text\": \"Hello, please introduce yourself.\"}]}]}", Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);

6. Example: Google Apps Script (GAS)

function callGemini() {
  var apiKey = "YOUR_API_KEY";
  var url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=" + apiKey;
  var payload = {
    "contents": [
      {
        "parts": [
          {"text": "Hello, please introduce yourself."}
        ]
      }
    ]
  };
  var options = {
    "method" : "post",
    "contentType": "application/json",
    "payload" : JSON.stringify(payload)
  };
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText());
}

7. Example: JavaScript (Node.js)

const fetch = require("node-fetch");

const url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=YOUR_API_KEY";
const body = {
  contents: [
    {
      parts: [{ text: "Hello, please introduce yourself." }]
    }
  ]
};

fetch(url, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(body)
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));

8. Example: Shell Script (cURL)

curl -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "parts": [
          {"text": "Hello, please introduce yourself."}
        ]
      }
    ]
  }' \
  "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=YOUR_API_KEY"

9. Reference Link

10. Conclusion

The Gemini API offers a powerful and accessible way to implement generative AI across many programming languages. With official libraries for Python and JavaScript, getting started is especially easy for beginners. Use the code examples in this article to integrate Gemini into your projects and unlock the full potential of AI.