Skip Navigation
Show nav
Dev Center
  • Get Started
  • Documentation
  • Changelog
  • Search
  • Get Started
    • Node.js
    • Ruby on Rails
    • Ruby
    • Python
    • Java
    • PHP
    • Go
    • Scala
    • Clojure
    • .NET
  • Documentation
  • Changelog
  • More
    Additional Resources
    • Home
    • Elements
    • Products
    • Pricing
    • Careers
    • Help
    • Status
    • Events
    • Podcasts
    • Compliance Center
    Heroku Blog

    Heroku Blog

    Find out what's new with Heroku on our blog.

    Visit Blog
  • Log inorSign up
View categories

Categories

  • Heroku Architecture
    • Compute (Dynos)
      • Dyno Management
      • Dyno Concepts
      • Dyno Behavior
      • Dyno Reference
      • Dyno Troubleshooting
    • Stacks (operating system images)
    • Networking & DNS
    • Platform Policies
    • Platform Principles
  • Developer Tools
    • Command Line
    • Heroku VS Code Extension
  • Deployment
    • Deploying with Git
    • Deploying with Docker
    • Deployment Integrations
  • Continuous Delivery & Integration (Heroku Flow)
    • Continuous Integration
  • Language Support
    • Node.js
      • Working with Node.js
      • Node.js Behavior in Heroku
      • Troubleshooting Node.js Apps
    • Ruby
      • Rails Support
      • Working with Bundler
      • Working with Ruby
      • Ruby Behavior in Heroku
      • Troubleshooting Ruby Apps
    • Python
      • Working with Python
      • Background Jobs in Python
      • Python Behavior in Heroku
      • Working with Django
    • Java
      • Java Behavior in Heroku
      • Working with Java
      • Working with Maven
      • Working with Spring Boot
      • Troubleshooting Java Apps
    • PHP
      • PHP Behavior in Heroku
      • Working with PHP
    • Go
      • Go Dependency Management
    • Scala
    • Clojure
    • .NET
      • Working with .NET
  • Databases & Data Management
    • Heroku Postgres
      • Postgres Basics
      • Postgres Getting Started
      • Postgres Performance
      • Postgres Data Transfer & Preservation
      • Postgres Availability
      • Postgres Special Topics
      • Migrating to Heroku Postgres
    • Heroku Key-Value Store
    • Apache Kafka on Heroku
    • Other Data Stores
  • AI
    • Working with AI
    • Heroku Inference
      • Inference API
      • Quick Start Guides
      • AI Models
      • Inference Essentials
    • Vector Database
    • Model Context Protocol
  • Monitoring & Metrics
    • Logging
  • App Performance
  • Add-ons
    • All Add-ons
  • Collaboration
  • Security
    • App Security
    • Identities & Authentication
      • Single Sign-on (SSO)
    • Private Spaces
      • Infrastructure Networking
    • Compliance
  • Heroku Enterprise
    • Enterprise Accounts
    • Enterprise Teams
    • Heroku Connect (Salesforce sync)
      • Heroku Connect Administration
      • Heroku Connect Reference
      • Heroku Connect Troubleshooting
  • Patterns & Best Practices
  • Extending Heroku
    • Platform API
    • App Webhooks
    • Heroku Labs
    • Building Add-ons
      • Add-on Development Tasks
      • Add-on APIs
      • Add-on Guidelines & Requirements
    • Building CLI Plugins
    • Developing Buildpacks
    • Dev Center
  • Accounts & Billing
  • Troubleshooting & Support
  • Integrating with Salesforce
  • AI
  • Heroku Inference
  • Quick Start Guides
  • Ruby Quick Start Guide for /v1/images/generations API

Ruby Quick Start Guide for /v1/images/generations API

Last updated May 13, 2025

Table of Contents

  • Prerequisites
  • Ruby Example Code

The Stability AI Stable Image Ultra (stability-image-ultra) model allows you to generate high-quality, detailed images from descriptive text prompts. This guide walks you through how to access the v1-images-generations API using Ruby.

Prerequisites

Before making requests, provision access to the model of your choice.

  1. If it’s not already installed, install the Heroku CLI. Then install the Heroku AI plugin:

    heroku plugins:install @heroku/plugin-ai
    
  2. Attach the image model to an app of yours:

    # If you don't have an app yet, you can create one with:
    heroku create $APP_NAME # specify the name you want for your app (or skip this step to use an existing app you have)
    
    # Create and attach the image model to your app, $APP_NAME.
    heroku ai:models:create -a $APP_NAME stability-image-ultra --as DIFFUSION
    

Ruby Example Code

# frozen_string_literal: true

require 'net/http'
require 'json'
require 'uri'
require 'base64'

DIFFUSION_URL = ENV.fetch('DIFFUSION_URL') do
  raise <<~ERROR
    Environment variable 'DIFFUSION_URL' is missing.
    Set it using:
      export DIFFUSION_URL=$(heroku config:get -a $APP_NAME DIFFUSION_URL)
  ERROR
end

DIFFUSION_KEY = ENV.fetch('DIFFUSION_KEY') do
  raise <<~ERROR
    Environment variable 'DIFFUSION_KEY' is missing.
    Set it using:
      export DIFFUSION_KEY=$(heroku config:get -a $APP_NAME DIFFUSION_KEY)
  ERROR
end

DIFFUSION_MODEL_ID = ENV.fetch('DIFFUSION_MODEL_ID') do
  raise <<~ERROR
    Environment variable 'DIFFUSION_MODEL_ID' is missing.
    Set it using:
      export DIFFUSION_MODEL_ID=$(heroku config:get -a $APP_NAME DIFFUSION_MODEL_ID)
  ERROR
end

##
# Opens an image file using the default image viewer based on the operating system.
#
# @param filename [String] The name of the file to open.
def open_image_file(filename)
  case RUBY_PLATFORM
  when /darwin/  then system('open', filename)      # macOS
  when /linux/   then system('xdg-open', filename)  # Linux
  when /mingw|mswin/
    system('start', filename)                       # Windows
  else
    puts 'Automatic image opening is not supported on this platform.'
  end
end

##
# Parses and processes the API response for the image generation request.
#
# @param response   [Net::HTTPResponse] The response from the API.
# @param payload    [Hash] The original request payload.
# @param open_image [Boolean] Flag to automatically open the image after creation.
# @param filename   [String, nil] Filename to save. If not provided, a default is generated.
def parse_image_output(response, payload, open_image: false, filename: nil)
  if response.is_a?(Net::HTTPSuccess)
    result = JSON.parse(response.body)

    if payload[:response_format] == 'base64'
      # Generate a default filename if none is provided, based on the prompt
      filename ||= payload[:prompt][0..19].gsub(' ', '_').downcase + '.png'
      File.open(filename, 'wb') do |file|
        file.write(Base64.decode64(result.dig('data', 0, 'b64_json')))
      end

      puts "Image saved as #{filename}"
      open_image_file(filename) if open_image
    else
      puts "Download the image from: #{result.dig('data', 0, 'url')}"
    end
  else
    puts "Request failed: #{response.code}, #{response.body}"
  end
end

##
# Generates an image using the Stability AI Stable Image Ultra model and saves it to a file.
#
# @param payload    [Hash] The parameters for the image generation.
# @param open_image [Boolean] Flag to open the image automatically after generation.
# @param filename   [String, nil] Name of the saved file. Defaults to a truncated version of the prompt.
def generate_image(payload, open_image: false, filename: nil)
  uri = URI.join(DIFFUSION_URL, '/v1/images/generations')
  request = Net::HTTP::Post.new(uri)
  request['Authorization'] = "Bearer #{DIFFUSION_KEY}"
  request['Content-Type']  = 'application/json'
  request.body             = payload.to_json

  response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
    http.request(request)
  end

  parse_image_output(response, payload, open_image: open_image, filename: filename)
end

# Example payload
payload = {
  model:           DIFFUSION_MODEL_ID,
  prompt:          'A surreal landscape with glowing mushrooms under a night sky.',
  aspect_ratio:    '16:9',
  output_format:   'png',
  seed:            123,
  negative_prompt: 'crowded, noisy, chaotic',
  response_format: 'base64'  # Add this key if you want the base64 variant
}

# Generate the image with the given payload
generate_image(payload, open_image: true)

Keep reading

  • Quick Start Guides

Feedback

Log in to submit feedback.

Information & Support

  • Getting Started
  • Documentation
  • Changelog
  • Compliance Center
  • Training & Education
  • Blog
  • Support Channels
  • Status

Language Reference

  • Node.js
  • Ruby
  • Java
  • PHP
  • Python
  • Go
  • Scala
  • Clojure
  • .NET

Other Resources

  • Careers
  • Elements
  • Products
  • Pricing
  • RSS
    • Dev Center Articles
    • Dev Center Changelog
    • Heroku Blog
    • Heroku News Blog
    • Heroku Engineering Blog
  • Twitter
    • Dev Center Articles
    • Dev Center Changelog
    • Heroku
    • Heroku Status
  • Github
  • LinkedIn
  • © 2025 Salesforce, Inc. All rights reserved. Various trademarks held by their respective owners. Salesforce Tower, 415 Mission Street, 3rd Floor, San Francisco, CA 94105, United States
  • heroku.com
  • Legal
  • Terms of Service
  • Privacy Information
  • Responsible Disclosure
  • Trust
  • Contact
  • Cookie Preferences
  • Your Privacy Choices