nano / API_REFERENCE.md
tomo2chin2's picture
Upload 6 files
9ab8670 verified

A newer version of the Gradio SDK is available: 6.6.0

Upgrade

NanoBanana API Reference

Base Information

Authentication

API Key Authentication

When API_KEY environment variable is set, all API endpoints require authentication.

Header: X-API-Key: your-api-key

Example:

curl -H "X-API-Key: your-api-key" https://tomo2chin2-nano.hf.space/api/health

If authentication fails, you'll receive:

{
  "detail": "Invalid API key"
}

Endpoints

1. Health Check

GET /api/health

Check if the service is running and configured properly.

Response

{
  "status": "healthy",
  "gemini_configured": true,
  "dataset_configured": true,
  "auth_required": true,
  "timestamp": "2025-01-17T12:00:00Z"
}

2. Image Generation

2.1 Generate Image (URL Only)

POST /api/generate/url

Generate an image and return only the URL (lightweight response).

Request Body
{
  "prompt": "A beautiful sunset over mountains",
  "size": "1024x1024",
  "style": "Default",
  "save_to_dataset": true,
  "dataset_folder": "custom_folder",
  "name": "my-image"
}
Parameters
Parameter Type Required Default Description
prompt string Yes - Text description for image generation
size string No "1024x1024" Image dimensions (WxH)
style string No "Default" Image style preset
save_to_dataset boolean No true Save to HF dataset if configured
dataset_folder string No YYYY_MM_DD Custom folder name for dataset
name string No auto-generated Custom filename (without extension)
Response
{
  "url": "/api/images/generated_1234567890.png",
  "size": "1024x1024",
  "style": "Default",
  "dataset_saved": true,
  "dataset_folder": "custom_folder",
  "timestamp": "2025-01-17T12:00:00Z",
  "status": "βœ… Generated successfully"
}

2.2 Generate Image (Full Data)

POST /api/generate/full

Generate an image and return the URL plus base64 encoded image data.

Request Body

Same as /api/generate/url

Response
{
  "url": "/api/images/generated_1234567890.png",
  "image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
  "size": "1024x1024",
  "style": "Default",
  "dataset_saved": true,
  "dataset_folder": "custom_folder",
  "timestamp": "2025-01-17T12:00:00Z",
  "status": "βœ… Generated successfully"
}

2.3 Generate Image (Flexible)

POST /api/generate

Generate an image with optional full data return.

Request Body
{
  "prompt": "A beautiful sunset over mountains",
  "size": "1024x1024",
  "style": "Default",
  "save_to_dataset": true,
  "dataset_folder": "custom_folder",
  "name": "my-sunset",
  "return_image": false
}
Additional Parameter
Parameter Type Required Default Description
return_image boolean No false Include base64 image in response
Response

Returns either URL-only or full data response based on return_image parameter.


3. Image Editing

3.1 Edit Image (URL Only)

POST /api/edit/url

Edit an existing image and return only the URL.

Request Body
{
  "image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
  "instruction": "Make the sky purple",
  "size": "1024x1024",
  "save_to_dataset": true,
  "dataset_folder": "edited",
  "name": "purple-sky"
}
Parameters
Parameter Type Required Default Description
image string Yes - Base64 encoded input image
instruction string Yes - Edit instruction text
size string No "1024x1024" Output image dimensions
save_to_dataset boolean No true Save to HF dataset if configured
dataset_folder string No YYYY_MM_DD Custom folder name for dataset
name string No auto-generated Custom filename (without extension)
Response
{
  "url": "/api/images/edited_1234567890.png",
  "size": "1024x1024",
  "dataset_saved": true,
  "dataset_folder": "edited",
  "timestamp": "2025-01-17T12:00:00Z",
  "status": "βœ… Edited successfully"
}

3.2 Edit Image (Full Data)

POST /api/edit/full

Edit an image and return the URL plus base64 encoded result.

Request Body

Same as /api/edit/url

Response
{
  "url": "/api/images/edited_1234567890.png",
  "image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
  "size": "1024x1024",
  "dataset_saved": true,
  "dataset_folder": "edited",
  "timestamp": "2025-01-17T12:00:00Z",
  "status": "βœ… Edited successfully"
}

3.3 Edit Image (Flexible)

POST /api/edit

Edit an image with optional full data return.

Request Body

Includes all parameters from /api/edit/url plus:

{
  "return_image": false
}

4. Image Composition

POST /api/compose

Combine multiple images into one composition.

Request Body
{
  "images": [
    "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
    "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
  ],
  "instruction": "Combine these images into a collage",
  "size": "1024x1024",
  "save_to_dataset": true,
  "dataset_folder": "compositions",
  "name": "my-collage",
  "return_image": false
}
Parameters
Parameter Type Required Default Description
images array[string] Yes - Array of base64 encoded images (2-10)
instruction string Yes - Composition instruction
size string No "1024x1024" Output dimensions
save_to_dataset boolean No true Save to dataset
dataset_folder string No YYYY_MM_DD Custom folder
name string No auto-generated Custom filename (without extension)
return_image boolean No false Include base64 in response
Response

Similar structure to generation endpoints.


5. History

GET /api/history

Get recent generation history (last 10 items).

Query Parameters
Parameter Type Required Default Description
limit integer No 10 Number of items to return (max 50)
Response
{
  "history": [
    {
      "prompt": "A beautiful sunset",
      "timestamp": "2025-01-17T12:00:00Z",
      "url": "/api/images/generated_1234567890.png",
      "type": "generation"
    },
    {
      "instruction": "Make it purple",
      "timestamp": "2025-01-17T11:55:00Z",
      "url": "/api/images/edited_1234567889.png",
      "type": "edit"
    }
  ],
  "total": 2
}

6. Dataset Operations

6.1 List Dataset Folders

GET /api/dataset/folders

Get list of available folders in the dataset repository.

Response
{
  "folders": [
    "2025_01_17",
    "custom_folder",
    "edited",
    "compositions"
  ],
  "dataset_repo": "username/dataset-name",
  "total": 4
}

6.2 List Images in Folder

GET /api/dataset/images/{folder_name}

Get list of images in a specific dataset folder.

Path Parameters
Parameter Type Required Description
folder_name string Yes Name of the folder
Response
{
  "folder": "custom_folder",
  "images": [
    {
      "filename": "generated_1234567890.png",
      "url": "https://huggingface.co/datasets/username/dataset-name/resolve/main/custom_folder/generated_1234567890.png",
      "metadata": {
        "prompt": "A beautiful sunset",
        "timestamp": "2025-01-17T12:00:00Z",
        "size": "1024x1024"
      }
    }
  ],
  "total": 1
}

7. Static Image Access

GET /api/images/{filename}

Access generated images directly.

Path Parameters
Parameter Type Required Description
filename string Yes Image filename
Response

Returns the image file with appropriate content-type header.


Error Responses

Validation Error (422)

{
  "detail": [
    {
      "loc": ["body", "prompt"],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}

Authentication Error (403)

{
  "detail": "Invalid API key"
}

Server Error (500)

{
  "detail": "Internal server error: [error message]"
}

Rate Limits

Currently, there are no enforced rate limits. However, please use the API responsibly:

  • Avoid making more than 10 requests per minute
  • Implement proper error handling and retry logic
  • Cache responses when appropriate

Code Examples

Python Example

import requests
import json

# Configuration
API_URL = "https://tomo2chin2-nano.hf.space"
API_KEY = "your-api-key"  # Optional if authentication is enabled

headers = {
    "Content-Type": "application/json"
}

# Add API key if configured
if API_KEY:
    headers["X-API-Key"] = API_KEY

# Generate an image
data = {
    "prompt": "A futuristic city at night with neon lights",
    "size": "1024x1024",
    "style": "Cyberpunk"
}

response = requests.post(
    f"{API_URL}/api/generate/url",
    headers=headers,
    json=data
)

if response.status_code == 200:
    result = response.json()
    print(f"Image URL: {API_URL}{result['url']}")
else:
    print(f"Error: {response.text}")

JavaScript/Node.js Example

const API_URL = "https://tomo2chin2-nano.hf.space";
const API_KEY = "your-api-key"; // Optional

async function generateImage(prompt) {
    const headers = {
        "Content-Type": "application/json"
    };

    if (API_KEY) {
        headers["X-API-Key"] = API_KEY;
    }

    const response = await fetch(`${API_URL}/api/generate/url`, {
        method: "POST",
        headers: headers,
        body: JSON.stringify({
            prompt: prompt,
            size: "1024x1024",
            style: "Default"
        })
    });

    if (response.ok) {
        const data = await response.json();
        console.log(`Image URL: ${API_URL}${data.url}`);
        return data;
    } else {
        throw new Error(`Error: ${response.statusText}`);
    }
}

// Usage
generateImage("A serene Japanese garden in autumn")
    .then(result => console.log(result))
    .catch(error => console.error(error));

cURL Example

# Generate image (URL only)
curl -X POST "https://tomo2chin2-nano.hf.space/api/generate/url" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key" \
  -d '{
    "prompt": "A beautiful mountain landscape",
    "size": "1024x1024",
    "style": "Default"
  }'

# Generate image with full data
curl -X POST "https://tomo2chin2-nano.hf.space/api/generate/full" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key" \
  -d '{
    "prompt": "A cute robot assistant",
    "save_to_dataset": true,
    "dataset_folder": "robots"
  }'

# Check health
curl "https://tomo2chin2-nano.hf.space/api/health" \
  -H "X-API-Key: your-api-key"

Image Styles

Available style presets for image generation:

  • Default: Standard Gemini generation
  • Photorealistic: Ultra-realistic photography style
  • Anime: Japanese anime art style
  • Oil Painting: Classical oil painting technique
  • Watercolor: Soft watercolor painting style
  • Sketch: Pencil sketch drawing
  • Digital Art: Modern digital illustration
  • 3D Render: 3D rendered graphics
  • Pixel Art: Retro pixel art style
  • Minimalist: Simple, clean minimalist design
  • Cyberpunk: Futuristic cyberpunk aesthetic
  • Fantasy: Fantasy and magical themes
  • Abstract: Abstract artistic interpretation
  • Pop Art: Bold pop art style
  • Vintage: Retro vintage photography

Size Options

Supported image dimensions:

  • 512x512 - Square, small
  • 768x768 - Square, medium
  • 1024x1024 - Square, large (default)
  • 1024x768 - Landscape, standard
  • 768x1024 - Portrait, standard
  • 1920x1080 - Landscape, Full HD
  • 1080x1920 - Portrait, Full HD

Dataset Integration

When HF_TOKEN and DATASET_REPO_ID environment variables are configured:

  1. Images are automatically saved to Hugging Face dataset repository
  2. Images are organized in folders by date (YYYY_MM_DD) or custom folder names
  3. Metadata (prompt, timestamp, parameters) is saved alongside images
  4. Dataset can be browsed via the Dataset Gallery tab in the UI

Dataset Folder Structure

dataset-repo/
β”œβ”€β”€ 2025_01_17/
β”‚   β”œβ”€β”€ generated_1234567890.png
β”‚   └── metadata.json
β”œβ”€β”€ custom_folder/
β”‚   β”œβ”€β”€ generated_1234567891.png
β”‚   └── metadata.json
└── README.md

Best Practices

For Photorealistic Images

  • Use camera terms: lens type (85mm, wide-angle), lighting (golden hour, studio)
  • Add details: textures, materials, weather, time of day
  • Example: "Portrait photo, 85mm lens, golden hour lighting, shallow depth of field"

For Artistic Styles

  • Mention artist names or art movements for inspiration
  • Specify medium and technique details
  • Example: "Oil painting in the style of Van Gogh, thick brushstrokes, vibrant colors"

For Better Results

  • Be specific and descriptive in your prompts
  • Use style presets for consistent results
  • Include negative prompts to avoid unwanted elements
  • Experiment with different sizes for optimal composition

Limitations

  • Maximum prompt length: 2000 characters
  • Image generation timeout: 60 seconds
  • Maximum file upload size: 10MB
  • Supported input formats: PNG, JPEG, WebP
  • Maximum images for composition: 10

Support


Changelog

Version 4.0.0 (2025-01-17)

  • Added API key authentication
  • Implemented AuthManager for secure access
  • Fixed f-string syntax issues
  • Deployed to production

Version 3.0.0 (2025-01-17)

  • Added dataset integration
  • Implemented dual response modes (URL/full)
  • Added Dataset Gallery UI
  • Custom folder support

Version 2.0.0

  • Integrated Gemini 2.5 Flash Image Preview
  • Added multiple style presets
  • Implemented placeholder generation

Version 1.0.0

  • Initial MVP release
  • Basic image generation functionality