← Back to posts

Getting Started with the Stockimg.ai API: A Complete Guide

2025.04.30

thumb

The Stockimg.ai API gives developers direct access to powerful AI image generation capabilities, allowing you to integrate professional-quality visuals into your applications, websites, and workflows. This guide will walk you through everything you need to know to start generating images programmatically—from initial setup to building a fully functional demo app.

Whether you're building a content creation tool, enhancing a CMS, or automating your marketing visuals, this guide will help you harness the full potential of the Stockimg.ai API.

Get Your API Key Now | View API Documentation | See Demo App in Action

What You Can Build with the API

what you can build

The possibilities are vast, but here are some popular ways developers are using our API:

Automated Content Creation

  • Generate social media graphics on demand
  • Create dynamic ad visuals tailored to different audiences
  • Produce product mockups without a designer

Application Integration

  • Add image generation features to web apps
  • Build custom plugins for design tools
  • Enhance CMS platforms with AI visuals

Product Visualization

  • Create product images in different contexts
  • Generate e-commerce listing photos at scale
  • Visualize customizable products with different options

The API supports a wide range of visual formats—from logos and illustrations to stock photos and UI designs—making it versatile enough for almost any visual need.

Get Your API Key

getting the api key

Before you can start making API calls, you'll need an API key. Here's how to get one:

  1. Sign up or log in to your Stockimg.ai account
  2. Navigate to the API Dashboard
  3. Click "Generate API Key"
  4. Copy your API key to a secure location

⚠️ Security Best Practice: Never expose your API key in client-side code. Use environment variables or a backend service to make API calls and handle the responses.

With your API key in hand, you're ready to start integrating Stockimg.ai into your applications.

Understanding the API Structure

understanding the api structure

The Stockimg.ai API follows RESTful principles and is organized around predictable resource-oriented URLs. All requests use standard HTTP methods and return JSON responses.

Base URL

All API requests are made to:

https://api.stockimg.app

Authentication

Every API request requires authentication using a Bearer token header:

Authorization: Bearer YOUR_API_KEY

Common Endpoints

  • /v1/text-to-image/{model} : Generate images from text prompts
  • /v1/image-to-image/{transformation} : Transform existing images
  • /v1/video/{model} : Generate video content

Rate Limits

Rate limits vary by plan. Check your dashboard for your current limits and usage statistics.

Available Models & Use Cases

available models

Stockimg.ai offers a variety of specialized models, each designed for specific use cases:

Text-to-Image Models

Stock Image (4 variants)

  • Stockimg: Standard professional photography style
  • Cinematic: Film-inspired dramatic visuals
  • Knolling: Organized, overhead product arrangements
  • Polaroid: Nostalgic instant photo style

Creative Models

  • Flux (3 variants): Creative artistic styles
  • Art (5 variants): Fine art inspired visuals
  • Illustration (2 variants): Stylized drawings

Design & Marketing

  • Ads: Advertising-optimized visuals
  • Logo: Brand identity designs
  • Social Media Template: Ready-to-share social content
  • Poster: Promotional designs
  • Thumbnail: Video and content thumbnails

Specialized Graphics

  • Wallpaper: Background imagery
  • Mockup: Product visualization
  • Sticker: Shareable visual elements
  • Card And Invites: Celebration designs
  • Book Cover: Publishing visuals
  • Pattern: Repeatable textures
  • Mobile Icon: App icon designs
  • UI Design: Interface elements

Image-to-Image Models

These models transform existing images:

  • Upscale: Enhance resolution
  • Avatar: Generate profile images
  • Product: Enhance product photography
  • Remove Background: Create transparent backgrounds

Video Models

For dynamic content creation:

  • Kling: AI-generated video content
  • Haiper: Video transformation tool

Each model is optimized for specific scenarios, so choose the one that best matches your use case.

Code Walkthrough: JavaScript API Call

code walkthrouh

Let's examine how to make an API call using JavaScript. This example shows a basic text-to-image generation request:

const apiKey = "YOUR_API_KEY"; // Replace with your actual key

async function generateImage() {
  const body = {
    "prompt": "A modern workspace with a computer and coffee cup",
    "image_size": {
      "width": 1024,
      "height": 1024
    },
    "safety_checker": true
  };

  try {
    const response = await fetch(
      "https://api.stockimg.app/v1/text-to-image/stock-image/stockimg", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${apiKey}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify(body)
    });
    
    const data = await response.json();
    
    if (data.data && data.data.images && data.data.images[0].url) {
      const imageUrl = data.data.images[0].url;
      console.log("Generated image URL:", imageUrl);
      return imageUrl;
    } else {
      console.error("Failed to generate image:", data);
      return null;
    }
  } catch (error) {
    console.error("API request error:", error);
    return null;
  }
}

Breaking Down the Code

  1. Request Body: Contains the prompt and image dimensions
  2. Endpoint: Targets the specific model (/v1/text-to-image/stock-image/stockimg)
  3. Headers: Includes authentication and content type
  4. Response Handling: Parses the JSON response and extracts the image URL

This pattern can be adapted for any of the available models by changing the endpoint and adjusting the request parameters.

Try the Demo App

trying the demo app

Let's build a simple web application that demonstrates the Stockimg.ai API in action. Our demo will allow users to:

  • Enter a text prompt
  • Select an image size (horizontal, vertical, or square)
  • Choose a model
  • Generate and display an image

HTML Structure (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Stockimg API Demo</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <!-- Image element to display the generated image -->
  <img id="image" alt="Generated Image" />
  <!-- Input field where the user types the image prompt -->
  <input type="text" id="promptInput" placeholder="Enter your prompt here...">
  <!-- Dropdown menu to select the image dimensions -->
  <select id="imageOptions">
    <option value="horizontal">Horizontal (1280x736)</option>
    <option value="vertical">Vertical (736x1280)</option>
    <option value="square">Square (1024x1024)</option>
  </select>
  <!-- Dropdown menu to select the AI model for generation -->
  <select id="modelOptions">
    <option value="/v1/text-to-image/stock-image/stockimg">Stockimg</option>
    <option value="/v1/text-to-image/stock-image/cinematic">Cinematic</option>
    <option value="/v1/text-to-image/stock-image/knolling">Knolling</option>
    <option value="/v1/text-to-image/stock-image/polaroid">Polaroid</option>
    <option value="/v1/text-to-image/wallpaper">Wallpaper</option>
    <option value="/v1/text-to-image/art/art">Art</option>
    <option value="/v1/text-to-image/flux/pro">Flux Pro</option>
    <option value="/v1/text-to-image/flux/dev">Flux Dev</option>
    <option value="/v1/text-to-image/flux/scnell">Flux Schnell</option>
  </select>
  <!-- Button that triggers the image generation process -->
  <button id="generateButton">Generate</button>
  <!-- Spinner element displayed during image generation -->
  <div id="spinner"></div>
  <!-- Toast notification for success and error messages -->
  <div id="toast"></div>
  <script src="script.js"></script>
</body>
</html>

JavaScript Implementation (script.js)

// Your API Key for authenticating requests. Get it from: https://stockimg.ai/api-dashboard
const apiKey = "YOUR_API_KEY"; // <-- Replace with your actual API key

// Function to show a small toast notification with a message
function showToast(message) {
    const toast = document.getElementById("toast");
    toast.innerText = message;
    toast.className = "show";
    setTimeout(() => { toast.className = toast.className.replace("show", ""); }, 3000);
}

// Add an event listener to the 'Generate' button
document.getElementById('generateButton').addEventListener('click', async () => {

    // Get user inputs: prompt text, selected size and selected model
    const prompt = document.getElementById('promptInput').value;
    const selectedSize = document.getElementById('imageOptions').value;
    const selectedModel = document.getElementById('modelOptions').value;

    // Validate that the user entered a prompt
    if (!prompt) {
        showToast('Please enter a prompt.');
        return;
    }

    // Select UI elements we need to manipulate
    const button = document.getElementById('generateButton');
    const spinner = document.getElementById('spinner');
    const imageElement = document.getElementById('image');
    const promptInput = document.getElementById('promptInput');
    const imageOptions = document.getElementById('imageOptions');
    const modelOptions = document.getElementById('modelOptions');

    // Disable inputs and show spinner while generating image
    button.disabled = true;
    promptInput.disabled = true;
    imageOptions.disabled = true;
    modelOptions.disabled = true;
    spinner.style.display = 'block';
    imageElement.style.display = 'none'; // Hide previous image while loading new one

    // Default image dimensions (square)
    let width = 1024;
    let height = 1024;

    // Adjust image dimensions based on selected aspect ratio
    if (selectedSize === 'vertical') {
        width = 736;
        height = 1280;
    } else if (selectedSize === 'horizontal') {
        width = 1280;
        height = 736;
    } else if (selectedSize === 'square') {
        width = 1024;
        height = 1024;
    }

    // Prepare the request body
    let bodyContent = {
        prompt: prompt,
        image_size: {
            width: width,
            height: height
        },
        safety_checker: true
    };
    
    // Add additional parameters for specific models as needed
    if (selectedModel.includes("/stock-image/")) {
        // Uncomment if you want to send colors
        // bodyContent.colors = ["#05f124", "#55357f"];
    }

    // Add model-specific parameters for other models
    if (selectedModel.includes("/flux/")){
        // bodyContent.seed = 42; // Example seed value for reproducibility
        // bodyContent.guide_scale = 7; // Example guide scale value
        // bodyContent.num_inference_steps = 50; // Example inference steps
    }

    try {
        // Make the POST request to the Stockimg API
        const response = await fetch(`https://api.stockimg.app${selectedModel}`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Authorization": `Bearer ${apiKey}` // Attach the API Key
            },
            body: JSON.stringify(bodyContent) // Send the request body as JSON
        });

        const data = await response.json(); // Parse the JSON response

        // If the image URL exists, display it
        if (data.data && data.data.images && data.data.images[0].url) {
            const imageUrl = data.data.images[0].url;
            imageElement.src = imageUrl;
            imageElement.style.display = 'block';
            showToast('Image generated successfully!');
        } else {
            showToast('Failed to generate image.');
        }

    } catch (error) {
        // Catch any error that happens during the request
        console.error('Error:', error);
        showToast('An error occurred.');
    } finally {
        // Re-enable all inputs and hide the spinner
        button.disabled = false;
        promptInput.disabled = false;
        imageOptions.disabled = false;
        modelOptions.disabled = false;
        spinner.style.display = 'none';
    }
});

CSS Styling (style.css)

For a complete experience, you can customize the styles for your web project. We will not go through the styling for this project. You can find the full css file on Github page.

Customize Your Output

customizing the output

The Stockimg.ai API offers extensive customization options to tailor your generated images. Here are the key parameters you can adjust:

Common Parameters for All Models

  • prompt : Text description of the image to generate
  • image_size : Width and height dimensions
  • safety_checker : Enable/disable content filtering

Model-Specific Parameters

Different models support specific parameters to customize your output:

Text-to-Image Models

Stock Image, Ads, Logo, Social Media Template, Poster, Wallpaper, Mockup, Illustration, Thumbnail, Art, Sticker, Card And Invites, Book Cover, Pattern, Mobile Icon, UI Design

These models share common parameters:

  • colors: Array of color hex codes used for the prompt (e.g., ["#05f124", "#55357f"])
  • prompt (Required): Text description for image generation (e.g., "A beautiful view")
  • image_size (Required): Object defining dimensions:
    • width: Width in pixels
    • height: Height in pixels
  • safety_checker (Default: true): Flag to ensure generated content is appropriate

Flux Models have additional parameters:

  • seed: Integer for reproducible results (e.g., 42)
  • guidance_scale: Integer that controls how closely the image follows the prompt (e.g., 7)
  • num_inference_steps: Integer controlling generation quality/speed (e.g., 50)
  • enable_safety_checker: Boolean to enable/disable content safety checking

Image-to-Image Models

Upscale

  • face: Boolean indicating whether to enhance faces in the image
  • image_url (Required): URL of the image to be upscaled

Avatar

  • seed: Integer seed value for reproducible generation
  • prompt (Required): Text prompt describing the desired image
  • face_image_url (Required): URL to a face image to be used in generation
  • enable_safety_checker (Default: true): Flag to enable content safety checking

Product Photo

  • prompt (Required): Text prompt to guide image processing (e.g., "Place this product on a white background")
  • image_url (Required): URL of the product image to be processed
  • padding_values: Object with custom padding values:
    • top: Top padding in pixels
    • left: Left padding in pixels
    • right: Right padding in pixels
    • bottom: Bottom padding in pixels
  • placement_type: Method for determining product placement (Options: "original", "automatic", "manual_placement", "manual_padding")
  • background_image_url: Optional URL for a custom background image
  • manual_placement_selection: Position to place product when using manual placement (Options include: "upper_left", "upper_right", "bottom_left", "bottom_right", "right_center", "left_center", "upper_center", "bottom_center", "center_vertical", "center_horizontal")

Remove Background

  • image_url (Required): URL of the image to be processed
  • output_mask: Boolean indicating whether to output a mask of the removed parts

Video Models

Kling AI

  • prompt (Required): Prompt for video generation
  • duration: Duration of the video in seconds (Options: 5, 10)
  • aspect_ratio: Aspect ratio for the generated video (Options: "16:9", "1:1", "9:16")

Haiper AI

  • seed: Seed value for reproducible generation
  • prompt (Required): Prompt for video generation
  • duration: Duration of the video in seconds (Options: 4, 6)

Where to Go Next

exploring the options

Now that you have a working demo, here are some ways to expand your skills with the Stockimg.ai API:

  1. Explore the Full API Documentation

    • Complete parameter lists
    • Response formats
    • Error handling
    • Advanced techniques
  2. Try Different Models

    • Each model has unique characteristics
    • Compare outputs for the same prompt across models
  3. Build Practical Applications

    • Integrate with your CMS
    • Create a browser extension
    • Build an image generation workflow

The API Documentation provides complete details on all available endpoints, parameters, and features.

Support & Community

where do we go now o a a a a

If you need technical help or have questions about the API:

  • Contact our support team at [email protected]
  • Check your free trial credits in your account dashboard
  • Business users get priority support with faster response times

We love seeing what developers build with our API! Feel free to share your projects and implementations with us.

Final Words

The Stockimg.ai API puts powerful visual generation at your fingertips. Whether you're building a design tool, enhancing an e-commerce experience, or automating content creation, our API provides the technology to make it happen.

Get your API key today and start transforming your ideas into stunning visuals with just a few lines of code.

Get Your API Key Now →

Author: Yağız Şimşek

Related:

← Back to posts

logo
Get started with Stockimg AI.
Enhance your design process with Stockimg.ai, saving time and money.
Get Started
© 2025 Stockimg AI, Inc. All rights reserved.