Creating Images with Gemini's REST API
Introduction to Gemini 3.1 Flash and Go
Welcome to the first lesson of our course, "Creating Images with Gemini 3.1 Flash and Go." In this course, you will explore AI-driven image generation using Google's Gemini API and its Gemini 3.1 Flash image model. Our journey begins with understanding how to set up the environment and generate a simple image using Go. This foundational lesson will set the stage for more advanced topics in subsequent units.
Setting Up the Environment
Before we dive into generating images, it's crucial to set up our environment correctly. First, ensure you have access to the Gemini API by retrieving your API key. This key is essential for authenticating your requests to the API. You can set this key in your environment variables. For this lesson, you'll need to use Go Modules, Go's package management system, to install the necessary libraries. You can use the net/http package for making HTTP requests.
Note that the environment will be fully set up for the practices section, so you can focus on the exercises without worrying about the setup.
Getting the URL and API Keys
You can get more details about how to use the Gemini Image Generation API from Google's documents. There, you can get the important details about connecting to the API, namely the GEMINI_BASE_URL and the GEMINI_API_KEY.
For example, when connecting directly to Gemini, the GEMINI_BASE_URL will be https://generativelanguage.googleapis.com/ and the GEMINI_API_KEY is your own secret. In all of our examples and practices, we will provide these variables to you so you don't need to be concerned with them for now.
Using libraries
Although Go client libraries exist for many Gemini workflows, this course uses the REST API directly for image generation so the request structure is clear and consistent with the practices.
We will later encapsulate this REST request behind a reusable helper function.
Retrieving your URL and API Keys
First, we need to retrieve the Base URL and API key from your environment variables. From there, we can construct an API request to the Image Generation model, which has a full URL of:
From there, we attach the API key as a request header and we have a fully constructed request:
This setup ensures that your application can securely communicate with the Gemini API.

