Generating a Simple Image with Gemini and FastAPI

Introduction to Gemini Image Generation with Python

Welcome to the first lesson of our course, "Generating a Simple Image with Gemini and FastAPI". In this course, you will explore the fascinating world of AI image generation using Python and Google's Gemini API.

Our journey begins with learning how to set up the environment, configure the Gemini client, generate an image from a text prompt, and save the image to a local folder. We'll use the google-genai SDK to communicate with Gemini and Pillow behind the scenes through Gemini's part.as_image() helper to work with generated image data.

This foundational lesson will prepare you for more advanced image generation topics in later units, including prompt refinement, styles, photography modifiers, and text placement.

Setting Up the Environment

Before we generate images, we need to set up our environment. First, ensure you have access to the Gemini API and have retrieved your API key. This key authenticates your requests to the API. In this course, we will read the key from an environment variable named GEMINI_API_KEY.

Shell
pip install google-genai pillow

On CodeSignal, many libraries may already be installed, but it's still important to know which dependencies your project needs when running locally.

Configuring the Gemini API Client

With the environment ready, the next step is configuring the Gemini API client. The code below reads the API key and base URL from environment variables, validates that they exist, and initializes the Gemini client.

from google import genai
from google.genai import types
import os

# Model ID for Gemini 3 image generation
GEMINI_IMAGE_MODEL = "gemini-3.1-flash-image"

# Retrieve API key from system environment variable
api_key = os.getenv("GEMINI_API_KEY")

if not api_key:
    raise ValueError("GEMINI_API_KEY not found in environment variables. Set it before running the script.")

base_url = os.getenv("GEMINI_BASE_URL")

if not base_url:
    raise ValueError("GEMINI_BASE_URL not found in environment variables. Set it before running the script.")

# Initialize the Gemini client
client = genai.Client(
    api_key=api_key,
    http_options=types.HttpOptions(
        base_url=base_url,
    ),
)

This setup ensures that your application can securely communicate with the Gemini API.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal