Your First API Request
Download the necessary SDK and start making your first API requests within Aidge.
Once you have successfully obtain your AccessKey and AccessKey Secret, now we can proceed to set up your first API call.
To begin, you will need to download our SDK, which is necessary for accessing our API and ensures that your access is authenticated.
It is recommended to invoke the services using the Java SDK. Aidge's SDK offers functionalities for API request encapsulation, digest signature, response parsing, and message listening. By utilizing this SDK, you can effortlessly make API calls, retrieve API results, and monitor real-time messages.
Download SDK
Sign in and navigate to our page below to download the SDK
Select the development language you require and download the corresponding SDK.
Sample Code
Once you have obtained the SDK, below are some code examples for you to write up your first API request.
Here is a sample code to call our API ( using image cut-out api as an example):
IopClient client = new IopClientImpl("https://api.aidc-ai.com", "your key", "your secret");
IopRequest request = new IopRequest();
// Adding this trial tag in header means using the trial resource to test,
// please remove this trial tag after you purchased the API
request.addHeaderParameter("x-iop-trial","true");
request.setApiName("/ai/virtual/tryon-pro");
request.addApiParameter("requestParams", "[{\"clothesList\":[{\"imageUrl\":\"https://ae-pic-a1.aliexpress-media.com/kf/H7588ee37b7674fea814b55f2f516fda1z.jpg\",\"type\":\"tops\"}],\"modelImage\":[\"https://aib-innovation-oss.oss-accelerate.aliyuncs.com/maneken_ai/file/models/12319.png?Expires=4102329600&OSSAccessKeyId=LTAI5tQXkNRSYtVTxN3rKi3z&Signature=k%2FQyZE9zD%2Br%2ByDBYbqD4OaZewjM%3D\"]}]");
IopResponse response = client.execute(request);
System.out.println(response.getBody());
// You can use any other json library to parse result and handle error result
String taskId;
JSONObject result = JSONObject.parseObject(response.getBody());
if (result.getJSONObject("data").getJSONObject("result").containsKey("taskId")) {
taskId = result.getJSONObject("data").getJSONObject("result").getString("taskId");
} else {
return;
}
// Query task status
IopRequest queryResultRequest = new IopRequest();
queryResultRequest.setApiName("/ai/virtual/tryon-results");
queryResultRequest.addApiParameter("task_id", taskId);
int queryCount = 30;
while (queryCount-- > 0) {
IopResponse queryResponse = client.execute(queryResultRequest);
LogUtils.info(queryResponse.getBody());
System.out.println(queryResponse.getBody());
result = JSONObject.parseObject(queryResponse.getBody());
String taskStatus = result.getJSONObject("data").getString("taskStatus");
if ("finished".equals(taskStatus)) {
System.out.println("task finished status=" + taskStatus);
return;
}
Thread.sleep(2000);
}import iop
import json
import time
def api_async_api_call_sdk_vc_test():
client = iop.IopClient("https://api.aidc-ai.com", "your key", "your secret")
request = iop.IopRequest('/ai/virtual/tryon-pro')
request.set_protocol('GOP')
# Adding this trial tag in header means using the trial resource to test,
# please remove this trial tag after you purchased the API
request.add_header("x-iop-trial", "true")
request_params = [{
"clothesList": [{
"imageUrl": "https://ae-pic-a1.aliexpress-media.com/kf/H7588ee37b7674fea814b55f2f516fda1z.jpg",
"type": "tops"
}],
"modelImage": [
"https://aib-innovation-oss.oss-accelerate.aliyuncs.com/maneken_ai/file/models/12319.png?Expires=4102329600&OSSAccessKeyId=LTAI5tQXkNRSYtVTxN3rKi3z&Signature=k%2FQyZE9zD%2Br%2ByDBYbqD4OaZewjM%3D"
]
}]
request.add_api_param('requestParams', json.dumps(request_params))
response = client.execute(request)
print("Initial response body:")
print(response.body)
try:
result = response.body
task_id = result.get("data", {}).get("result", {}).get("taskId")
if not task_id:
print("Failed to get taskId from initial response.")
return
print(f"Task ID: {task_id}")
except Exception as e:
print(f"Error parsing initial response: {e}")
return
query_request = iop.IopRequest('/ai/virtual/tryon-results')
query_request.set_protocol('GOP')
query_request.add_api_param('task_id', task_id)
query_count = 30
while query_count > 0:
query_response = client.execute(query_request)
print("Query response body:")
print(query_response.body)
try:
query_result = query_response.body
task_status = query_result.get("data", {}).get("taskStatus")
print(f"Current task status: {task_status}")
if task_status == "finished":
print(f"Task finished with status={task_status}")
break
except Exception as e:
print(f"Error parsing query response: {e}")
time.sleep(2)
query_count -= 1
if __name__ == "__main__":
api_async_api_call_sdk_vc_test()package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
)
const (
apiDomain = "api.aidc-ai.com"
)
func main() {
// Personal data from environment variables
accessKeyName := os.Getenv("accessKey") // e.g. "512345"
accessKeySecret := os.Getenv("secret")
fmt.Println(accessKeyName)
fmt.Println(accessKeySecret)
// Call api
requestData := `{
"requestParams": [{
"clothesList": [{
"imageUrl": "https://ae-pic-a1.aliexpress-media.com/kf/H7588ee37b7674fea814b55f2f516fda1z.jpg",
"type": "tops"
}],
"modelImage": ["https://aib-innovation-oss.oss-accelerate.aliyuncs.com/maneken_ai/file/models/12319.png?Expires=4102329600&OSSAccessKeyId=LTAI5tQXkNRSYtVTxN3rKi3z&Signature=k%2FQyZE9zD%2Br%2ByDBYbqD4OaZewjM%3D"]
}]
}`
// Create the final URL with real values
apiName := "/ai/virtual/tryon-pro"
url := buildSignedURL(accessKeyName, accessKeySecret, apiName, apiDomain)
// Add "x-iop-trial": "true" for trial
headers := map[string]string{
"Content-Type": "application/json",
//"x-iop-trial": "true",
}
// Do HTTP POST request
respBody, err := makeRequest("POST", url, requestData, headers)
if err != nil {
fmt.Printf("Request failed: %v\n", err)
return
}
// Final result for the virtual try on
fmt.Println("response content:", respBody)
// 解析 taskId
var result map[string]interface{}
if err := parseJSON([]byte(respBody), &result); err != nil {
fmt.Printf("Error parsing response: %v\n", err)
return
}
data, ok := result["data"].(map[string]interface{})
if !ok {
fmt.Println("Unable to find data field")
return
}
resData, ok := data["result"].(map[string]interface{})
if !ok {
fmt.Println("Unable to find result field")
return
}
taskId, ok := resData["taskId"].(string)
if !ok {
fmt.Println("Not returned taskId")
return
}
fmt.Println("obtained taskId:", taskId)
// Regularly query task status
queryTaskResult(accessKeyName, accessKeySecret, taskId)
}
// Build a URL with signature
func buildSignedURL(accessKeyName, accessKeySecret, apiName, domain string) string {
timestamp := fmt.Sprintf("%d", time.Now().UnixNano()/int64(time.Millisecond))
signStr := accessKeySecret + timestamp
h := hmac.New(sha256.New, []byte(accessKeySecret))
h.Write([]byte(signStr))
sign := strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
urlTemplate := "https://%s/rest%s?partner_id=aidge&sign_method=sha256&sign_ver=v2&app_key=%s×tamp=%s&sign=%s"
return fmt.Sprintf(urlTemplate, domain, apiName, accessKeyName, timestamp, sign)
}
// makeRequest handles the HTTP request to the specified URL with the given data and headers
func makeRequest(method, url, data string, headers map[string]string) (string, error) {
client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest(method, url, bytes.NewBufferString(data))
if err != nil {
return "", err
}
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
// Query task results until completion
func queryTaskResult(accessKeyName, accessKeySecret, taskId string) {
apiName := "/ai/virtual/tryon-results"
queryCount := 30
for i := 0; i < queryCount; i++ {
time.Sleep(2 * time.Second)
url := buildSignedURL(accessKeyName, accessKeySecret, apiName, apiDomain)
params := fmt.Sprintf(`{"task_id":"%s"}`, taskId)
headers := map[string]string{
"Content-Type": "application/json",
}
respBody, err := makeRequest("POST", url, params, headers)
if err != nil {
fmt.Printf("Query task failed: %v\n", err)
continue
}
fmt.Println("Query response:", respBody)
var result map[string]interface{}
if err := parseJSON([]byte(respBody), &result); err != nil {
fmt.Printf("Error parsing response: %v\n", err)
continue
}
data, ok := result["data"].(map[string]interface{})
if !ok {
fmt.Println("Unable to find data field")
continue
}
taskStatus, ok := data["taskStatus"].(string)
if !ok {
fmt.Println("Not returned taskStatus")
continue
}
fmt.Printf("Current task status: %s\n", taskStatus)
if taskStatus == "finished" {
fmt.Println("Task completed")
break
}
}
}
// Simple JSON parsing auxiliary function (you can replace it with more powerful libraries such as encoding/json or third-party libraries)
func parseJSON(data []byte, v interface{}) error {
return json.Unmarshal(data, v)
}
curl -X POST 'https://api.aidc-ai.com/rest[api name]?partner_id=aidge&sign_method=sha256&sign_ver=v2&app_key=[you api key name]×tamp=[timestamp]&sign=[sha256 sign]' \
--header 'Content-Type: application/json' \
--data '{
"requestParams": [{
"clothesList": [{
"imageUrl": "https://ae-pic-a1.aliexpress-media.com/kf/H7588ee37b7674fea814b55f2f516fda1z.jpg",
"type": "tops"
}],
"modelImage": ["https://aib-innovation-oss.oss-accelerate.aliyuncs.com/maneken_ai/file/models/12319.png?Expires=4102329600&OSSAccessKeyId=LTAI5tQXkNRSYtVTxN3rKi3z&Signature=k%2FQyZE9zD%2Br%2ByDBYbqD4OaZewjM%3D"]
}]
}' Last updated
Was this helpful?