
Now that your environment is set up and your API key is ready, it's time for the most exciting part: making your very first call to the Gemini API. This tutorial will show you how to send a simple text prompt to the model and retrieve its generated response. We'll use the gemini-2.5-flash
model, which is an excellent choice for fast, cost-effective text generation.
The process is straightforward:
- Instantiate the client: Create an instance of the Gemini client using the SDK. This is where your API key is used for authentication.
- Select the model: Specify which Gemini model you want to use for your task.
- Send a prompt: Provide a text input to the model.
- Process the response: The API will return a response object from which you can extract the generated text.
Let's walk through the code for each language.
Python
If you're using Python, your code will look like this. Make sure your GOOGLE_API_KEY
is set as an environment variable before running.
import os
import google.generativeai as genai
Configure the SDK with your API key from environment variables
genai.configure(api_key=os.environ.get("GOOGLE_API_KEY"))
Initialize the generative model
model = genai.GenerativeModel('gemini-2.5-flash')
Define your text prompt
prompt = "Write a short, engaging story about a robot who discovers it can dream."
try:
# Make the API call to generate content
response = model.generate_content(prompt)
# Print the generated text
print(response.text)
except Exception as e:
print(f"An error occurred: {e}")
JavaScript (Node.js)
For Node.js, the process is asynchronous, so we'll use async
/await
. Ensure your GOOGLE_API_KEY
is set in your .env
file or environment variables.
require('dotenv').config();
const { GoogleGenerativeAI } = require("@google/generative-ai");
async function run() {
// Access your API key as an environment variable
const genAI = new GoogleGenerativeAI(process.env.GOOGLE_API_KEY);
// Initialize the generative model
const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" });
// Define your text prompt
const prompt = "Write a short, engaging story about a robot who discovers it can dream.";
try {
// Make the API call to generate content
const result = await model.generateContent(prompt);
const response = await result.response;
const text = response.text();
// Print the generated text
console.log(text);
} catch (error) {
console.error("An error occurred:", error);
}
}
run();
Go
With Go, you'll use a context
to manage the request lifecycle and handle the API key from your environment variables.
package main
import (
"context"
"fmt"
"log"
"os"
"[github.com/google/generative-ai-go/genai](https://github.com/google/generative-ai-go/genai)"
"google.golang.org/api/option"
)
func main() {
ctx := context.Background()
// Use your API key from an environment variable
apiKey := os.Getenv("GOOGLE_API_KEY")
if apiKey == "" {
log.Fatal("GOOGLE_API_KEY environment variable not set")
}
// Create the client
client, err := genai.NewClient(ctx, option.WithAPIKey(apiKey))
if err != nil {
log.Fatal(err)
}
defer client.Close()
// Initialize the generative model
model := client.GenerativeModel("gemini-2.5-flash")
// Define your text prompt
prompt := "Write a short, engaging story about a robot who discovers it can dream."
// Make the API call to generate content
response, err := model.GenerateContent(ctx, genai.Text(prompt))
if err != nil {
log.Fatal(err)
}
// Print the generated text
if len(response.Candidates) > 0 && len(response.Candidates[0].Content.Parts) > 0 {
fmt.Println(response.Candidates[0].Content.Parts[0].(genai.Text))
} else {
fmt.Println("No content generated.")
}
}
Java
For Java, the process involves creating a client and then calling the generateContent
method, which is wrapped in a try-catch
block to handle potential exceptions.
import com.google.cloud.generativeai.v1beta.GenerativeModel;
import com.google.cloud.generativeai.v1beta.GenerateContentResponse;
import com.google.cloud.generativeai.v1beta.Content;
import com.google.cloud.generativeai.v1beta.Part;
import com.google.api.gax.rpc.ApiException;
public class FirstApiCall {
public static void main(String[] args) {
// Your API key should be set as an environment variable (e.g., GOOGLE_API_KEY)
// or a system property for security.
String apiKey = System.getenv("GOOGLE_API_KEY");
if (apiKey == null || apiKey.isEmpty()) {
System.err.println("GOOGLE_API_KEY environment variable not set.");
return;
}
try {
// Initialize the generative model
GenerativeModel model = new GenerativeModel(
"gemini-2.5-flash",
apiKey
);
// Define your text prompt
Content content = Content.newBuilder()
.addParts(Part.newBuilder().setText("Write a short, engaging story about a robot who discovers it can dream."))
.build();
// Make the API call to generate content
GenerateContentResponse response = model.generateContent(content);
// Print the generated text
System.out.println(response.getCandidates(0).getContent().getParts(0).getText());
} catch (ApiException e) {
System.err.println("An API error occurred: " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
System.err.println("An unexpected error occurred: " + e.getMessage());
e.printStackTrace();
}
}
}
Congratulations! You've successfully made your first request to the Gemini API. You now have a foundational understanding of how to send a prompt and receive a response.
In the next tutorial, we will explore the different Gemini models in more detail, helping you choose the best one for your specific needs.