# API Use Example

Note: All APIs provided by this service require authentication using appKey and appSecret, and requests must be initiated by your backend service. Currently, direct browser initiated requests are not supported

Using Image League of Legends Cartoon-Style as an Example

# Python Language

# Create Task

import base64
file_link = "Downloadable file link"

key = appKey + ":" + appSecret
Authorization = "Basic " + base64.b64encode(key.encode('utf-8')).decode('utf-8') // Note: There is a space after Basic

header = {
    "Content-Type": "application/json",
    "Authorization": Authorization
    }
url = "https://wsai-api.wondershare.com/v3/pic/asc/batch"
file_arr = []
file_arr.append(file_link)
body = {
    "images": file_arr,
    "emotion": "ori",
    "priority": 1
    }
body = json.dumps(body).encode('utf-8')
resp = requests.post(url=url, data=body, headers=header)
resp = json.loads(resp._content)

return resp["data"]["task_id"]

# Poll Results

import base64

key = appKey + ":" + appSecret
Authorization = "Basic " + base64.b64encode(key.encode('utf-8')).decode('utf-8') // Note: There is a space after Basic

header = {
    "Content-Type": "application/json",
    "Authorization": Authorization
}
    
url = "https://wsai-api.wondershare.com/v3/pic/asc/result/" + task_id
while (1):
    resp = requests.get(url=url, headers=header)
    resp = json.loads(resp._content)
    if resp["data"]["status"] == 3:
        log_text = "League of Legends success##" + \
            "url:%s,reponse:%s" % (url, resp)
        mylog.info(log_text)
        break
    elif resp["data"]["status"] == 2:
        log_text = "League of Legends process##" + \
            "url:%s,reponse:%s" % (url, resp)
        mylog.info(log_text)
        time.sleep(2)
        continue
    else:
        log_text = "League of Legends fail##" + \
            "url:%s,reponse:%s" % (url, resp)
        mylog.error(log_text)
        break

return resp["data"]["list"][0]["image_result"]

# Go Language

# Create Task

package main

import (
    "bytes"
	"encoding/base64"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type requestData struct {
    Images   []string `json:"images"`
    Emotion  string   `json:"emotion"`
    Priority int      `json:"priority"`
}

type responseData struct {
    Data struct {
        TaskID string `json:"task_id"`
    } `json:"data"`
}

func main() {
    url := "https://wsai-api.wondershare.com/v3/pic/asc/batch"

    authorization := "Basic " +  base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(`%s:%s`, appKey, appSecret)))// Note: There is a space after Basic

    data := requestData{
        Images:   []string{"file_link"},
        Emotion:  "ori",
        Priority: 1,
    }

    jsonData, err := json.Marshal(data)
    if err != nil {
        log.Fatal("Error marshaling JSON:", err)
    }

    client := &http.Client{}
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", authorization)

    resp, err := client.Do(req)
    if err != nil {
        log.Fatal("Error making request:", err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal("Error reading response body:", err)
    }

    var response responseData
    err = json.Unmarshal(body, &response)
    if err != nil {
        log.Fatal("Error unmarshaling JSON response:", err)
    }

    fmt.Println("Task ID:", response.Data.TaskID)
}

# Poll Results

package main

import (
	"encoding/json"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

type APIResponse struct {
	Data struct {
		Status uint8 `json:"status"`
	} `json:"data"`
}

func pollApi(client *http.Client, url string) (APIResponse, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return APIResponse{}, err
	}
    
    authorization := "Basic " +  base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(`%s:%s`, appKey, appSecret)))// Note: There is a space after Basic`

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", authorization)

	resp, err := client.Do(req)
	if err != nil {
		return APIResponse{}, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return APIResponse{}, err
	}

	var result APIResponse
	err = json.Unmarshal(body, &result)
	if err != nil {
		return APIResponse{}, err
	}

	return result, nil
}

func getResult() (APIResponse, error) {
	taskID := "xxxx"
	url := "https://wsai-api.wondershare.com/v3/pic/asc/result/" + taskID
	client := http.Client{}

	for {
		time.Sleep(5 * time.Second) // Polling Interval 
		res, err := pollApi(&client, url)
		if err != nil {
			log.Println("Error:", err)
			continue
		}

		switch res.Data.Status {
		case 3:
			log.Println("Response Success")
			return res, nil
		case 2:
			log.Println("During task processing, continue polling")
		default:
			log.Println("Task error")
			return res, nil
		}
	}
}

func main() {
	result, err := getResult()
	if err != nil {
		log.Fatal("Error:", err)
	}

	fmt.Println("Task result: ", result)
}

# JavaScript Language

# Create Task

const url = 'https://wsai-api.wondershare.com/v3/pic/asc/batch';
const data = {
    "images": [file_link],
    "emotion": "ori",
    "priority": 1
};

let authorization = "Basic " +  btoa(`${appkey}:${appSecret}`)// Comment: There is a space after Basic 

fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        "Authorization": authorization
    },
    body: JSON.stringify(data)
})
    .then(response => response.json())
    .then(json => console.log(json["data"]["task_id"]))
    .catch(error => console.error('Error:', error));

# Poll Results

let authorization = "Basic " +  btoa(`${appkey}:${appSecret}`) // Comment: There is a space after Basic 
function pollApi(url) {
    return fetch(
        url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                "Authorization": authorization
            },
        }
    )
        .then(response => response.json())
        .catch(error => error);
}


async function getResult () {
    let task_id = "xxxx"
    let url = "https://wsai-api.wondershare.com/v3/pic/asc/result/" + task_id
    let res = null
    while (true) {
        res = await pollApi(url)
        if (res.data.status === 3) {
            console.log("Response Success");
            break
        } else if (res.data.status === 2) {
            console.log("During task processing, continue polling");
            continue
        } else {
            console.log("Task Error")
            break
        }
    }
    return res
}


Last Updated: 2/22/2024, 2:37:41 PM