Skip to content
Sign in

Postman/cURL guide

Quick testingAPI debuggingUpdated: 2025-11-27

Introduction

This guide walks through calling the SeaWhale AI image and video generation APIs with Postman and cURL, so you can test and debug the endpoints quickly.

The tools

ToolTypeCharacteristicsBest for
PostmanGraphical• Intuitive UI
• Easy to use
• Feature-rich
Beginners, API testers
cURLCommand line• Lightweight
• Script friendly
• Cross-platform
Developers, operations

Which should you use?

  • 🎯 New to APIs → Postman (visual)
  • 🎯 Developers → cURL (scriptable)
  • 🎯 Quick tests → either works
  • 🎯 Production → use an official SDK or your own HTTP client

What this guide covers

Using text-to-image as the example, it walks through the full flow from creating a task to fetching the result:

1. Create a generation task (POST)

2. Receive a task_id

3. Poll for the result (GET)

4. Get the image/video URL

5. Download and save the result

Important

  • Postman and cURL are for quick testing and debugging only
  • In production, use an official SDK or your own HTTP client
  • Image and video generation are asynchronous, so they take two steps

The asynchronous call flow

Because image and video generation takes a while (from a dozen seconds to several minutes), the SeaWhale AI HTTP API uses an asynchronous flow.

Flow diagram

mermaid
sequenceDiagram
    participant Client as Client
    participant API as SeaWhale AI API
    participant Engine as Generation engine

    Client->>API: 1. POST to create a task
    API->>Engine: Submit the generation task
    API-->>Client: 2. Return task_id

    loop Polling
        Client->>API: 3. GET the result
        API->>Engine: Check task status
        alt Task complete
            Engine-->>API: Return the result URL
            API-->>Client: 4. Return the image/video URL
        else Task in progress
            API-->>Client: Return RUNNING status
        end
    end

    Client->>Client: 5. Download and save the result

The two steps

Step 1: create the task

Method: POST

Purpose: submit the task and receive a task_id immediately

Example response:

json
{
  "output": {
    "task_id": "abc123-def456-ghi789",
    "task_status": "PENDING"
  },
  "request_id": "req-001"
}

Step 2: fetch the result

Method: GET

Purpose: poll with the task_id until the task finishes

Example response (in progress):

json
{
  "output": {
    "task_id": "abc123-def456-ghi789",
    "task_status": "RUNNING",
    "task_metrics": {
      "TOTAL": 1,
      "SUCCEEDED": 0,
      "FAILED": 0
    }
  }
}

Example response (complete):

json
{
  "output": {
    "task_id": "abc123-def456-ghi789",
    "task_status": "SUCCEEDED",
    "results": [
      {
        "url": "https://example.com/image.jpg"
      }
    ]
  }
}

Task statuses

StatusMeaningWhat to do
PENDINGQueuedKeep polling
RUNNINGIn progressKeep polling
SUCCEEDEDFinished successfullyRead the result URL
FAILEDFailedRead the error details
UNKNOWNStatus unknownQuery again or contact support

Polling recommendations

  • First query: wait 3–5 seconds
  • Interval: every 2–3 seconds
  • Timeouts:
    • Text-to-image: 30–60 seconds
    • Text-to-video: 5–10 minutes
  • task_id lifetime: 24 hours
  • Result URL lifetime: 24 hours (download promptly)

Before you begin

1. Get an API key

  1. Open the SeaWhale AI console
  2. Sign up and log in
  3. Generate an API key on the API management page
  4. Make sure your account has enough balance

New user credit

  • 🎁 New accounts receive free credit
  • 💰 Usable across all model inference services

2. Install the tools

  1. Visit the Postman downloads page
  2. Download the installer for your platform
  3. Install and launch Postman
PlatformDownloadNotes
WindowsDownloadWindows 10+
macOSDownloadmacOS 10.12+
LinuxDownloadMajor distributions

cURL (developer tool)

Most systems ship with cURL already. To check:

bash
curl --version
cmd
curl --version

If it is missing:

bash
brew install curl
bash
sudo apt-get install curl
powershell
# Windows 10+ includes curl
# Or install Git for Windows, which bundles curl

3. Set the API key as an environment variable (cURL users)

Storing the key in an environment variable keeps commands short:

bash
# Current terminal only
export DASHSCOPE_API_KEY="sk-xxxxxxxxxxxxxxxx"

# Persistent (append to ~/.bashrc or ~/.zshrc)
echo 'export DASHSCOPE_API_KEY="sk-xxxxxxxxxxxxxxxx"' >> ~/.zshrc
source ~/.zshrc
powershell
# Current session only
$env:DASHSCOPE_API_KEY="sk-xxxxxxxxxxxxxxxx"

# Persistent (user environment variable)
[Environment]::SetEnvironmentVariable("DASHSCOPE_API_KEY", "sk-xxxxxxxxxxxxxxxx", "User")
cmd
# Current session only
set DASHSCOPE_API_KEY=sk-xxxxxxxxxxxxxxxx

# Persistent
setx DASHSCOPE_API_KEY "sk-xxxxxxxxxxxxxxxx"

Verify it:

bash
echo $DASHSCOPE_API_KEY
powershell
$env:DASHSCOPE_API_KEY
cmd
echo %DASHSCOPE_API_KEY%

Option 1: Postman

Postman is a capable API testing tool with an intuitive interface, well suited to quick tests.

Step 1: create the generation task

1.1 Configure the request

  1. Open Postman
  2. Click "New""HTTP Request"
  3. Fill in:
SettingValueNotes
MethodPOSTCreating a task uses POST
URLhttps://api.your-domain.com/api/v1/services/aigc/text2image/image-synthesisUse your actual API host

Regional endpoints

  • Mainland China: https://api.your-domain.com/api/v1/services/aigc/text2image/image-synthesis
  • International: https://api-intl.your-domain.com/api/v1/services/aigc/text2image/image-synthesis

Choose the URL that matches your API key's region.

1.2 Configure the headers

Switch to the Headers tab and add:

KeyValueNotes
X-DashScope-AsyncenableEnables async mode
AuthorizationBearer sk-xxxxxxxxxxxxxxxxYour API key
Content-Typeapplication/jsonJSON format

Security

  • 🔒 The Authorization value is Bearer + a space + your API key
  • 🔒 Do not omit the Bearer prefix
  • 🔒 Never share your API key

1.3 Configure the body

Switch to the Body tab:

  1. Select raw
  2. Choose the JSON format
  3. Enter:
json
{
  "model": "wanx2.1-t2i-turbo",
  "input": {
    "prompt": "A flower shop with delicate windows and a beautiful wooden door, flowers on display"
  },
  "parameters": {
    "size": "1024*1024",
    "n": 1
  }
}
  1. Click Beautify on the right to format the JSON
Parameter reference

model (required)

  • The model name
  • Text-to-image: wanx2.1-t2i-turbo, wanx2.1-t2i-plus
  • Text-to-video: wanx2.1-t2v-turbo

input.prompt (required)

  • What to generate
  • Tip: be detailed and specific; any language works
  • Length: 10–500 characters works well

parameters.size

  • Image dimensions
  • Options: 1024*1024, 720*1280, 1280*720

parameters.n

  • How many images to generate
  • Range: 1–4
  • Note: more images means more tokens consumed

1.4 Send the request and get the task_id

  1. Click Send
  2. Review the response

Successful response:

json
{
  "output": {
    "task_id": "abc123-def456-ghi789",
    "task_status": "PENDING"
  },
  "request_id": "req-001",
  "code": "200",
  "message": "success"
}
  1. Note the task_id: abc123-def456-ghi789

Important

  • Save the task_id right away — you need it to fetch the result
  • ⏰ The task_id is valid for 24 hours
  • ❌ After that you cannot retrieve the result

Step 2: fetch the result

2.1 Configure the query request

  1. Create a new HTTP request
  2. Fill in:
SettingValueNotes
MethodGETFetching results uses GET
URLhttps://api.your-domain.com/api/v1/tasks/{task_id}Replace {task_id} with your task ID

Example URL:

https://api.your-domain.com/api/v1/tasks/abc123-def456-ghi789

2.2 Configure the headers

Switch to the Headers tab and add:

KeyValue
AuthorizationBearer sk-xxxxxxxxxxxxxxxx

2.3 Send the request and read the result

  1. Click Send
  2. Review the response

Task in progress:

json
{
  "output": {
    "task_id": "abc123-def456-ghi789",
    "task_status": "RUNNING",
    "task_metrics": {
      "TOTAL": 1,
      "SUCCEEDED": 0,
      "FAILED": 0
    }
  }
}

Task complete:

json
{
  "output": {
    "task_id": "abc123-def456-ghi789",
    "task_status": "SUCCEEDED",
    "results": [
      {
        "url": "https://example.com/generated-image.jpg",
        "code": "200"
      }
    ],
    "task_metrics": {
      "TOTAL": 1,
      "SUCCEEDED": 1,
      "FAILED": 0
    },
    "usage": {
      "image_count": 1
    }
  },
  "request_id": "req-002"
}
  1. The image URL: https://example.com/generated-image.jpg

2.4 Download the image

  1. Copy the url value
  2. Open it in your browser
  3. Save the image

Important

  • ⏰ The image URL is valid for 24 hours
  • ❌ It becomes inaccessible after that
  • ✅ Download and store it promptly

Postman tips

1. Save as a collection

Saving your requests as a collection makes them easy to reuse:

  1. Click Save
  2. Create a new collection (for example "SeaWhale AI image generation")
  3. Save both requests into it

2. Use environment variables

So you do not have to edit the API key each time:

  1. Click Environments in the top right
  2. Create an environment (for example "SeaWhale AI dev")
  3. Add variables:
    • api_key: sk-xxxxxxxxxxxxxxxx
    • base_url: https://api.your-domain.com
  4. Reference them in requests as and

3. Automate with tests

Add a script on the Tests tab:

javascript
// Extract task_id automatically
if (pm.response.code === 200) {
  const response = pm.response.json()
  const taskId = response.output.task_id
  pm.environment.set('task_id', taskId)
  console.log('Task ID:', taskId)
}

This saves the task_id into an environment variable so step two can use directly.


Option 2: cURL

cURL is a command-line HTTP tool, well suited to developers and automation.

Step 1: create the generation task

Open a terminal (Terminal, PowerShell, CMD) and run:

bash
curl -X POST https://api.your-domain.com/api/v1/services/aigc/text2image/image-synthesis \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wanx2.1-t2i-turbo",
    "input": {
        "prompt": "A flower shop with delicate windows and a beautiful wooden door, flowers on display"
    },
    "parameters": {
        "size": "1024*1024",
        "n": 1
    }
}'
bash
curl -X POST https://api-intl.your-domain.com/api/v1/services/aigc/text2image/image-synthesis \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wanx2.1-t2i-turbo",
    "input": {
        "prompt": "A flower shop with delicate windows and a beautiful wooden door, flowers on display"
    },
    "parameters": {
        "size": "1024*1024",
        "n": 1
    }
}'

Successful response:

json
{
  "output": {
    "task_id": "abc123-def456-ghi789",
    "task_status": "PENDING"
  },
  "request_id": "req-001"
}

Note the task_id: abc123-def456-ghi789

Windows users

Windows CMD does not support single quotes, so use double quotes and escape the inner ones:

cmd
curl -X POST https://api.your-domain.com/api/v1/services/aigc/text2image/image-synthesis ^
    -H "X-DashScope-Async: enable" ^
    -H "Authorization: Bearer %DASHSCOPE_API_KEY%" ^
    -H "Content-Type: application/json" ^
    -d "{\"model\":\"wanx2.1-t2i-turbo\",\"input\":{\"prompt\":\"A flower shop with delicate windows\"},\"parameters\":{\"size\":\"1024*1024\",\"n\":1}}"

PowerShell is the easier option.


Step 2: fetch the result

Replace {task_id} with the ID from step 1:

bash
curl -X GET https://api.your-domain.com/api/v1/tasks/abc123-def456-ghi789 \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY"
bash
curl -X GET https://api-intl.your-domain.com/api/v1/tasks/abc123-def456-ghi789 \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY"

Task in progress:

json
{
  "output": {
    "task_status": "RUNNING"
  }
}

Task complete:

json
{
  "output": {
    "task_id": "abc123-def456-ghi789",
    "task_status": "SUCCEEDED",
    "results": [
      {
        "url": "https://example.com/generated-image.jpg"
      }
    ]
  }
}

Polling

Because generation takes a while:

  1. Wait 3–5 seconds before the first query
  2. If you get RUNNING, wait 2–3 seconds and query again
  3. Repeat until the status is SUCCEEDED or FAILED

Automation scripts

Bash example

Create generate_image.sh:

bash
#!/bin/bash

# Configuration
API_KEY="sk-xxxxxxxxxxxxxxxx"
BASE_URL="https://api.your-domain.com"
PROMPT="A flower shop with delicate windows and a beautiful wooden door, flowers on display"

# Step 1: create the task
echo "Creating the generation task..."
RESPONSE=$(curl -s -X POST "${BASE_URL}/api/v1/services/aigc/text2image/image-synthesis" \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer ${API_KEY}" \
    -H 'Content-Type: application/json' \
    -d "{
    \"model\": \"wanx2.1-t2i-turbo\",
    \"input\": {
        \"prompt\": \"${PROMPT}\"
    },
    \"parameters\": {
        \"size\": \"1024*1024\",
        \"n\": 1
    }
}")

# Extract the task_id
TASK_ID=$(echo $RESPONSE | jq -r '.output.task_id')
echo "Task created, task_id: ${TASK_ID}"

# Step 2: poll for the result
echo "Waiting for generation to finish..."
while true; do
    sleep 3

    RESULT=$(curl -s -X GET "${BASE_URL}/api/v1/tasks/${TASK_ID}" \
        -H "Authorization: Bearer ${API_KEY}")

    STATUS=$(echo $RESULT | jq -r '.output.task_status')
    echo "Current status: ${STATUS}"

    if [ "$STATUS" = "SUCCEEDED" ]; then
        IMAGE_URL=$(echo $RESULT | jq -r '.output.results[0].url')
        echo "Generation succeeded."
        echo "Image URL: ${IMAGE_URL}"

        # Download the image
        curl -o generated_image.jpg "$IMAGE_URL"
        echo "Image saved as generated_image.jpg"
        break
    elif [ "$STATUS" = "FAILED" ]; then
        echo "Generation failed."
        echo $RESULT | jq
        break
    fi
done

How to run it:

bash
chmod +x generate_image.sh
./generate_image.sh

Python example

Create generate_image.py:

python
import requests
import time
import json

# Configuration
API_KEY = "sk-xxxxxxxxxxxxxxxx"
BASE_URL = "https://api.your-domain.com"
PROMPT = "A flower shop with delicate windows and a beautiful wooden door, flowers on display"

# Step 1: create the task
print("Creating the generation task...")
response = requests.post(
    f"{BASE_URL}/api/v1/services/aigc/text2image/image-synthesis",
    headers={
        "X-DashScope-Async": "enable",
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    },
    json={
        "model": "wanx2.1-t2i-turbo",
        "input": {
            "prompt": PROMPT
        },
        "parameters": {
            "size": "1024*1024",
            "n": 1
        }
    }
)

data = response.json()
task_id = data["output"]["task_id"]
print(f"Task created, task_id: {task_id}")

# Step 2: poll for the result
print("Waiting for generation to finish...")
while True:
    time.sleep(3)

    result = requests.get(
        f"{BASE_URL}/api/v1/tasks/{task_id}",
        headers={
            "Authorization": f"Bearer {API_KEY}"
        }
    )

    data = result.json()
    status = data["output"]["task_status"]
    print(f"Current status: {status}")

    if status == "SUCCEEDED":
        image_url = data["output"]["results"][0]["url"]
        print("Generation succeeded.")
        print(f"Image URL: {image_url}")

        # Download the image
        image_data = requests.get(image_url).content
        with open("generated_image.jpg", "wb") as f:
            f.write(image_data)
        print("Image saved as generated_image.jpg")
        break
    elif status == "FAILED":
        print("Generation failed.")
        print(json.dumps(data, indent=2))
        break

How to run it:

bash
python generate_image.py

FAQ

Q1: Postman returns a 401 authentication error

Error message:

json
{
  "code": "InvalidApiKey",
  "message": "Invalid API-key provided"
}

Possible causes:

  1. ❌ The API key is wrong or expired
  2. ❌ The Authorization format is incorrect
  3. ❌ The Bearer prefix is missing

Fix:

Check the Authorization format:

Correct:   Bearer sk-xxxxxxxxxxxxxxxx
Incorrect: sk-xxxxxxxxxxxxxxxx
Incorrect: Bearer: sk-xxxxxxxxxxxxxxxx

Regenerate the API key:

  1. Open the SeaWhale AI console
  2. Delete the old API key
  3. Generate a new one
  4. Update your Postman/cURL configuration

Q2: The status stays RUNNING

Why:

  1. The task is still generating (normal)
  2. The service is busy, so processing takes longer

Fix:

Keep waiting and polling:

  • Text-to-image: usually 10–30 seconds
  • Text-to-video: usually 3–10 minutes

Increase the polling interval:

bash
# From 2 seconds to 5
sleep 5

Set an overall timeout:

python
import time

max_wait_time = 300  # 5 minutes
start_time = time.time()

while True:
    if time.time() - start_time > max_wait_time:
        print("Timed out — the task may have failed")
        break
    # Polling logic...

Q3: How do I generate several images at once?

Option 1: increase the n parameter

json
{
  "model": "wanx2.1-t2i-turbo",
  "input": {
    "prompt": "A cute kitten"
  },
  "parameters": {
    "size": "1024*1024",
    "n": 4 // Generate 4 at once
  }
}

Option 2: run tasks concurrently

python
import concurrent.futures

prompts = [
    "A cute kitten",
    "A beautiful landscape",
    "A sci-fi city"
]

def generate_image(prompt):
    # Full create-and-poll logic
    pass

with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
    futures = [executor.submit(generate_image, p) for p in prompts]
    for future in concurrent.futures.as_completed(futures):
        result = future.result()
        print(result)

Q4: The generated image URL will not open

Possible causes:

  1. ❌ The URL expired (24-hour lifetime)
  2. ❌ A network or firewall problem
  3. ❌ The task actually failed but was read as successful

Fix:

Check the expiry:

python
from datetime import datetime, timedelta

url_expire_time = datetime.now() + timedelta(hours=24)
print(f"The URL expires at {url_expire_time}")

Download it immediately:

bash
curl -o image.jpg "https://example.com/image.jpg"

Double-check the task status:

json
{
  "output": {
    "task_status": "SUCCEEDED", // Confirm it is SUCCEEDED
    "task_metrics": {
      "SUCCEEDED": 1, // Confirm the success count
      "FAILED": 0
    }
  }
}

Q5: How do I improve generation quality?

Better prompts

❌ A weak prompt:

a cat

✅ A strong prompt:

A cute orange kitten with big blue eyes, fluffy fur,
sitting on a windowsill with sunlight falling across it, warm atmosphere,
high-definition photography, soft lighting, shallow depth of field

Parameter tuning

Use a higher-quality model:

ModelSpeedQualityCost
wanx2.1-t2i-turbo⭐⭐⭐⭐⭐Low
wanx2.1-t2i-plus⭐⭐⭐⭐⭐Medium
wanx2.1-t2i-pro⭐⭐⭐⭐⭐High

Adjust the size:

json
{
  "parameters": {
    "size": "1280*1280", // Larger output
    "n": 1
  }
}

Best practices

1. Error handling

A complete error-handling example:

python
import requests
import time

def generate_image_with_retry(prompt, max_retries=3):
    """Image generation with retries"""
    for attempt in range(max_retries):
        try:
            # Create the task
            response = requests.post(
                f"{BASE_URL}/api/v1/services/aigc/text2image/image-synthesis",
                headers=headers,
                json=payload,
                timeout=30
            )
            response.raise_for_status()

            task_id = response.json()["output"]["task_id"]

            # Poll for the result
            for _ in range(60):  # At most 60 polls
                time.sleep(3)
                result = requests.get(
                    f"{BASE_URL}/api/v1/tasks/{task_id}",
                    headers=headers,
                    timeout=10
                )
                result.raise_for_status()

                data = result.json()
                status = data["output"]["task_status"]

                if status == "SUCCEEDED":
                    return data["output"]["results"][0]["url"]
                elif status == "FAILED":
                    raise Exception(f"Task failed: {data}")

            raise Exception("Polling timed out")

        except Exception as e:
            print(f"Attempt {attempt + 1} failed: {e}")
            if attempt == max_retries - 1:
                raise
            time.sleep(5)  # Back off before retrying

2. Performance

Use a connection pool:

python
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

# Create a session
session = requests.Session()

# Configure the retry policy
retry = Retry(
    total=3,
    backoff_factor=1,
    status_forcelist=[500, 502, 503, 504]
)

adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)

# Send requests through the session
response = session.post(url, headers=headers, json=payload)

Limit concurrency:

python
from concurrent.futures import ThreadPoolExecutor
import asyncio

# Cap concurrent requests
MAX_CONCURRENT = 5

async def generate_batch(prompts):
    with ThreadPoolExecutor(max_workers=MAX_CONCURRENT) as executor:
        futures = [executor.submit(generate_image, p) for p in prompts]
        results = [f.result() for f in futures]
    return results

3. Logging

Detailed logging:

python
import logging
from datetime import datetime

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('image_generation.log'),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger(__name__)

def generate_image(prompt):
    logger.info(f"Starting image generation, prompt: {prompt}")

    try:
        # Create the task
        logger.info("Creating the task...")
        response = create_task(prompt)
        task_id = response["task_id"]
        logger.info(f"Task created: {task_id}")

        # Poll for the result
        logger.info("Polling for the result...")
        result = poll_result(task_id)
        logger.info(f"Generation succeeded: {result['url']}")

        return result
    except Exception as e:
        logger.error(f"Generation failed: {e}", exc_info=True)
        raise

Other developer tools

ToolTypeBest forDocumentation
Postman/cURLAPI testingQuick tests, endpoint debuggingThis guide
DifyLow-code platformVisual application buildingRead
ClineVSCode extensionCode developmentRead
Claude CodeCLITerminal developmentRead

Support

ChannelResponse timeContact
📖 DocumentationImmediateRead the docs
💬 Live supportWeekdays 9:00–18:00Contact support
📧 Email supportWithin 24 hourssupport@atalk-ai.com
🐛 Bug reportsWithin 48 hoursSubmit feedback

External resources


Changelog

2025-11-27

  • ✨ Added the full Postman and cURL guide
  • 📝 Expanded the asynchronous call documentation
  • 🔧 Improved error handling and best practices
  • 📖 Added automation script examples
  • 🐛 Reworked the FAQ

2025-10-15

  • 🎉 Initial release

© 2024 SeaWhale AI. All rights reserved.

Last updated 2025-11-27

Home | API docs | Console