Postman/cURL guide
Quick testingAPI debuggingUpdated: 2025-11-27Introduction
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
| Tool | Type | Characteristics | Best for |
|---|---|---|---|
| Postman | Graphical | • Intuitive UI • Easy to use • Feature-rich | Beginners, API testers |
| cURL | Command 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 resultImportant
- 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
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 resultThe two steps
Step 1: create the task
Method: POST
Purpose: submit the task and receive a task_id immediately
Example response:
{
"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):
{
"output": {
"task_id": "abc123-def456-ghi789",
"task_status": "RUNNING",
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 0,
"FAILED": 0
}
}
}Example response (complete):
{
"output": {
"task_id": "abc123-def456-ghi789",
"task_status": "SUCCEEDED",
"results": [
{
"url": "https://example.com/image.jpg"
}
]
}
}Task statuses
| Status | Meaning | What to do |
|---|---|---|
PENDING | Queued | Keep polling |
RUNNING | In progress | Keep polling |
SUCCEEDED | Finished successfully | Read the result URL |
FAILED | Failed | Read the error details |
UNKNOWN | Status unknown | Query 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
- Open the SeaWhale AI console
- Sign up and log in
- Generate an API key on the API management page
- 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
Postman (recommended for beginners)
- Visit the Postman downloads page
- Download the installer for your platform
- Install and launch Postman
| Platform | Download | Notes |
|---|---|---|
| Windows | Download | Windows 10+ |
| macOS | Download | macOS 10.12+ |
| Linux | Download | Major distributions |
cURL (developer tool)
Most systems ship with cURL already. To check:
curl --versioncurl --versionIf it is missing:
brew install curlsudo apt-get install curl# Windows 10+ includes curl
# Or install Git for Windows, which bundles curl3. Set the API key as an environment variable (cURL users)
Storing the key in an environment variable keeps commands short:
# 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# Current session only
$env:DASHSCOPE_API_KEY="sk-xxxxxxxxxxxxxxxx"
# Persistent (user environment variable)
[Environment]::SetEnvironmentVariable("DASHSCOPE_API_KEY", "sk-xxxxxxxxxxxxxxxx", "User")# Current session only
set DASHSCOPE_API_KEY=sk-xxxxxxxxxxxxxxxx
# Persistent
setx DASHSCOPE_API_KEY "sk-xxxxxxxxxxxxxxxx"Verify it:
echo $DASHSCOPE_API_KEY$env:DASHSCOPE_API_KEYecho %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
- Open Postman
- Click "New" → "HTTP Request"
- Fill in:
| Setting | Value | Notes |
|---|---|---|
| Method | POST | Creating a task uses POST |
| URL | https://api.your-domain.com/api/v1/services/aigc/text2image/image-synthesis | Use 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:
| Key | Value | Notes |
|---|---|---|
X-DashScope-Async | enable | Enables async mode |
Authorization | Bearer sk-xxxxxxxxxxxxxxxx | Your API key |
Content-Type | application/json | JSON format |
Security
- 🔒 The
Authorizationvalue isBearer+ a space + your API key - 🔒 Do not omit the
Bearerprefix - 🔒 Never share your API key
1.3 Configure the body
Switch to the Body tab:
- Select raw
- Choose the JSON format
- Enter:
{
"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
}
}- 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
- Click Send
- Review the response
Successful response:
{
"output": {
"task_id": "abc123-def456-ghi789",
"task_status": "PENDING"
},
"request_id": "req-001",
"code": "200",
"message": "success"
}- 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
- Create a new HTTP request
- Fill in:
| Setting | Value | Notes |
|---|---|---|
| Method | GET | Fetching results uses GET |
| URL | https://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-ghi7892.2 Configure the headers
Switch to the Headers tab and add:
| Key | Value |
|---|---|
Authorization | Bearer sk-xxxxxxxxxxxxxxxx |
2.3 Send the request and read the result
- Click Send
- Review the response
Task in progress:
{
"output": {
"task_id": "abc123-def456-ghi789",
"task_status": "RUNNING",
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 0,
"FAILED": 0
}
}
}Task complete:
{
"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"
}- The image URL:
https://example.com/generated-image.jpg
2.4 Download the image
- Copy the
urlvalue - Open it in your browser
- 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:
- Click Save
- Create a new collection (for example "SeaWhale AI image generation")
- Save both requests into it
2. Use environment variables
So you do not have to edit the API key each time:
- Click Environments in the top right
- Create an environment (for example "SeaWhale AI dev")
- Add variables:
api_key:sk-xxxxxxxxxxxxxxxxbase_url:https://api.your-domain.com
- Reference them in requests as
and
3. Automate with tests
Add a script on the Tests tab:
// 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:
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
}
}'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:
{
"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:
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:
curl -X GET https://api.your-domain.com/api/v1/tasks/abc123-def456-ghi789 \
-H "Authorization: Bearer $DASHSCOPE_API_KEY"curl -X GET https://api-intl.your-domain.com/api/v1/tasks/abc123-def456-ghi789 \
-H "Authorization: Bearer $DASHSCOPE_API_KEY"Task in progress:
{
"output": {
"task_status": "RUNNING"
}
}Task complete:
{
"output": {
"task_id": "abc123-def456-ghi789",
"task_status": "SUCCEEDED",
"results": [
{
"url": "https://example.com/generated-image.jpg"
}
]
}
}Polling
Because generation takes a while:
- Wait 3–5 seconds before the first query
- If you get
RUNNING, wait 2–3 seconds and query again - Repeat until the status is
SUCCEEDEDorFAILED
Automation scripts
Bash example
Create generate_image.sh:
#!/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
doneHow to run it:
chmod +x generate_image.sh
./generate_image.shPython example
Create generate_image.py:
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))
breakHow to run it:
python generate_image.pyFAQ
Q1: Postman returns a 401 authentication error
Error message:
{
"code": "InvalidApiKey",
"message": "Invalid API-key provided"
}Possible causes:
- ❌ The API key is wrong or expired
- ❌ The Authorization format is incorrect
- ❌ The
Bearerprefix is missing
Fix:
✅ Check the Authorization format:
Correct: Bearer sk-xxxxxxxxxxxxxxxx
Incorrect: sk-xxxxxxxxxxxxxxxx
Incorrect: Bearer: sk-xxxxxxxxxxxxxxxx✅ Regenerate the API key:
- Open the SeaWhale AI console
- Delete the old API key
- Generate a new one
- Update your Postman/cURL configuration
Q2: The status stays RUNNING
Why:
- The task is still generating (normal)
- 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:
# From 2 seconds to 5
sleep 5✅ Set an overall timeout:
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
{
"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
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:
- ❌ The URL expired (24-hour lifetime)
- ❌ A network or firewall problem
- ❌ The task actually failed but was read as successful
Fix:
✅ Check the expiry:
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:
curl -o image.jpg "https://example.com/image.jpg"✅ Double-check the task status:
{
"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 fieldParameter tuning
Use a higher-quality model:
| Model | Speed | Quality | Cost |
|---|---|---|---|
wanx2.1-t2i-turbo | ⭐⭐⭐ | ⭐⭐ | Low |
wanx2.1-t2i-plus | ⭐⭐ | ⭐⭐⭐ | Medium |
wanx2.1-t2i-pro | ⭐ | ⭐⭐⭐⭐⭐ | High |
Adjust the size:
{
"parameters": {
"size": "1280*1280", // Larger output
"n": 1
}
}Best practices
1. Error handling
A complete error-handling example:
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 retrying2. Performance
Use a connection pool:
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:
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 results3. Logging
Detailed logging:
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)
raiseRelated resources
Recommended reading
- 📚 Quick start — SeaWhale AI API basics
- 🔧 API reference — the complete API documentation
- 🎯 Model list — every available model
Other developer tools
| Tool | Type | Best for | Documentation |
|---|---|---|---|
| Postman/cURL | API testing | Quick tests, endpoint debugging | This guide |
| Dify | Low-code platform | Visual application building | Read |
| Cline | VSCode extension | Code development | Read |
| Claude Code | CLI | Terminal development | Read |
Support
| Channel | Response time | Contact |
|---|---|---|
| 📖 Documentation | Immediate | Read the docs |
| 💬 Live support | Weekdays 9:00–18:00 | Contact support |
| 📧 Email support | Within 24 hours | support@atalk-ai.com |
| 🐛 Bug reports | Within 48 hours | Submit 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