Introduction to the Image Generator Service with FastAPI

Introduction to the Image Generator Service

Welcome to the third lesson of our course on building an image generation service with FastAPI! In our previous lessons, we created the PromptManager to format user inputs into detailed prompts and the ImageManager to handle storing and processing generated images. Now, we're ready to build the core component that brings everything together: the ImageGeneratorService.

The ImageGeneratorService is the central piece of our application that will:

  1. Connect to Google's Gemini API to generate images via the gemini-3.1-flash-image model
  2. Use our PromptManager to format user inputs into effective prompts
  3. Extract the image data from the Gemini response and store them using our ImageManager
  4. Provide access to all previously generated images

This service acts as the bridge between our application's components and the external AI service that actually creates the images. By encapsulating all the image generation logic in a dedicated service class, we maintain a clean separation of concerns in our application architecture.

In this lesson, we'll implement this service step by step, from setting up the API client to handling responses and errors. By the end, you'll have a fully functional image generation service that you can later integrate into a FastAPI web application.

Setting Up the Gemini API Client

Before we can generate images, we need to set up a client to communicate with Google's Gemini API. The Gemini API provides access to Google's powerful native image generation models, allowing us to create high-quality images from text prompts.

First, we need to install the Google Generative AI library. In a typical development environment, you would run:

pip install google-genai

Remember that in the CodeSignal environment, this library is already installed, so you won't need to run this command there.

Now, let's create our ImageGeneratorService class and set up the client in the constructor. We'll create a new file called image_generator_service.py in the app/services directory:

import os
from google import genai
from google.genai import types
from models.image_manager import ImageManager
from models.prompt_manager import PromptManager

GEMINI_IMAGE_MODEL = "gemini-3.1-flash-image"

class ImageGeneratorService:
    def __init__(self):
        self.image_manager = ImageManager()

        api_key = os.getenv("GEMINI_API_KEY")
        if not api_key:
            raise ValueError("GEMINI_API_KEY not found in environment variables.")

        base_url = os.getenv("GEMINI_BASE_URL")
        if not base_url:
            raise ValueError("GEMINI_BASE_URL not found in environment variables.")

        self.gemini_client = genai.Client(
            api_key=api_key,
            http_options=types.HttpOptions(
                base_url=base_url,
            ),
        )

In this constructor, we're doing two important things:

  1. Creating an instance of our ImageManager class to handle storing and retrieving images
  2. Safely retrieving our environment variables and initializing the Gemini client.

The genai.Client is the main interface for interacting with Google's Generative AI services. We'll use this client to access the native Gemini image generation model.

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