Examples of tasks creation and modification
  • 17 Jun 2024
  • 9 Minutes to read
  • Contributors
  • Dark
    Light
  • PDF

Examples of tasks creation and modification

  • Dark
    Light
  • PDF

Article summary

postman Use our collection of Corezoid API queries for Postman as an example.

Examine a basic API request-response example and see how to add and modify tasks in a Corezoid process using different languages:

Corezoid API basic request and response example

The example flow is the following:

  1. Сreate three tasks to the Test process (process ID 1234) from the API user (user ID is 13000).
  2. By default, all new tasks go to the starting node called Login (node id is n10221).
  3. Use:
    1. The URL example to make the request: https://api.corezoid.com/api/1/json/13000/{GMT_UNIXTIME}/{SIGNATURE}.
    2. ref as an external (for process) task identifier and optional parameter used in case of reverse interaction with a system that created a request.

Request

 {
    "ops":[
    {
        "ref":"130605ref1",
        "type":"create",
        "obj":"task",
        "conv_id":"1234",
        "data":{
            "phone":"380501234561",
            "card":"4134000011112221"
            }
    },
    {
        "ref":"130605ref2",
        "type":"create",
        "obj":"task",
        "conv_id":"1234",
        "data":{
            "phone":"380661234562",
            "card":"4134000011112222"
            }
    },
    {
        "ref":"130605ref3",
        "type":"create",
        "obj":"task",
        "conv_id":"1234",
        "data":{
            "phone":"380661234563",
            "card":"4134000011112223"
            }
    }
    ]
}

Response (in case of successful operation)

{
    "request_proc":"ok",
    "ops":[
        {
            "ref":"130605ref1",
            "obj":"task",
            "obj_id":"t71001",
            "proc":"ok"
        },
        {
            "ref":"130605ref2",
            "obj":"task",
            "obj_id":"t71012",
            "proc":"ok"
        },
        {
            "ref":"130605ref3",
            "obj":"task",
            "obj_id":"t71013",
            "proc":"ok"
        }
    ]
}

Erlang

-module(test).

-export([send_to_conv/6, test/0]).

test() ->
%Conveyor url
  ConvUrl = "https://api.corezoid.com",

%Conveyor ID
  ConvId = <<"5555">>,

%API user login (Conveyor with given ConvId has to be shared for this API user)
  ApiUser = "555",

%API User Secret Key
  ApiSecret = <<"qjVXiaXFazSCtIvMTjW29cZbPkzeYUzCzGmmrcJtIIj2eqceUm">>,

  % unique task reference, optional
  Reference = integer_to_binary(rand:uniform(100000000)),

% Data for processing
  Data = <<"{\"phone\":\"client_phone\",\"name\":\"client_name\"}">>,

  {ok, Response} = send_to_conv(ConvUrl, ConvId, ApiUser, ApiSecret, Reference, Data),

  Response.


-spec send_to_conv(ConvUrl, ConvId, ApiUser, ApiSecret, Reference, Data) -> {ok, binary()} when
  ConvUrl :: list(),
  ConvId :: binary(),
  ApiUser :: list(),
  ApiSecret :: binary(),
  Reference :: binary(),
  Data :: binary().

send_to_conv(ConvUrl, ConvId, ApiUser, ApiSecret, Reference, Data) ->

% start inets app for httpc client
  application:start(inets),

%Time in unix format
  Time = erlang:integer_to_binary(unixtime()),

%Request with one element (could be many) in ops array for task create
  Request = <<"{\"ops\":[{\"ref\":\"", Reference/binary, "\",\"type\":\"create\",\"obj\":\"task\",\"conv_id\":\"",
  ConvId/binary, "\",\"data\":", Data/binary, "}]}">>,

%Generate Sign
  Sign = create_sign(<<Time/binary, ApiSecret/binary, Request/binary, ApiSecret/binary>>),
  Url = ConvUrl ++ "/api/1/json/" ++ ApiUser ++ "/" ++ binary_to_list(Time) ++ "/" ++ binary_to_list(Sign),

  {ok, {{_, 200, _}, _, Response}} = httpc:request(post, {Url, [], "application/octet-stream", Request}, [{timeout, 10000}], []),

  {ok, Response}.


unixtime()->
  {A,B,_C} = timestamp(),
  A*1000000 + B.

create_sign(Bin) ->
  list_to_binary(list_to_hexstr(binary_to_list(crypto:hash(sha, Bin)))).


list_to_hexstr([]) ->
  [];
list_to_hexstr([H|T]) ->
  to_hex(H) ++ list_to_hexstr(T).


to_hex(N) when N < 256 ->
  [hex(N div 16), hex(N rem 16)].


hex(V) ->
  if
    V < 10 ->
      $0 + V;
    true ->
      $a + (V - 10)
  end.

Java

SDK for the work middleware.biz:
https://github.com/corezoid/sdk-java/releases/tag/v2.1


import com.corezoid.sdk.entity.CorezoidMessage;
import com.corezoid.sdk.entity.RequestOperation;
import com.corezoid.sdk.utils.HttpManager;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import net.sf.json.JSONObject;
import org.apache.http.HttpException;

public class MiddlewareCreate {

    public static void main(String[] args) {
        try {
            // ID process
            String conv_id = "15476";
            // API user settings
            String apiLogin = "5965";
            String apiSecret = "VjKyfIuVAFOGGZwLLFfkHvrTPFUTBBP6E3A8596vIj5jiwqSsK";
            // Create task
            JSONObject data = new JSONObject()
                    .element("phone", "+380989055434")
                    .element("nick", "Test Nick");
            String ref = "test" + System.currentTimeMillis() + new Random(System.currentTimeMillis()).nextInt(1000);
            RequestOperation operation = RequestOperation.create(conv_id, ref, data);
            // Add task to list
            List<RequestOperation> ops = Arrays.asList(operation);
            // Build a Message
            ConveyorMessage message = ConveyorMessage.request(apiSecret, apiLogin, ops);
            // Create HttpManager instance
            HttpManager http = new HttpManager();
            // Send all tasks to Middleware
            String answer = http.send(message);
        } catch (HttpException ex) {
            System.out.println(ex);
        }
    }

}

PHP

SDK for the work Corezoid.com:
https://github.com/corezoid/sdk-php

Example of loading request into the process ID 1635:

include_once('Corezoid.php'); // Corezoid class

// API user settings
$api_login = '1234';
$api_secret = 'Iw5N12MYleOULxdfMH43SK9ZAmjPyFKtdhToiL38xIBz6ecdZxW';

// Init Corezoid class
$CZ = new Corezoid($api_login, $api_secret);

// Add new task
$ref1    = time().'_'.rand();
$task1   = array('phone' => '+380989055434', 'nick' => 'Test Nick');
// ID process
$process_id = 1635;

$CZ->add_task($ref1, $process_id, $task1);

// Send all tasks to Corezoid.com
$res = $CZ->send_tasks();

BASH

Below you can find examples of

Creating new task

Example of creating a new task with the reference ref_32353 to the process with ID 1664 from the user with ID 985:

#!/bin/sh

CONV_ID=1664
CONV_USER_ID='985'
CONV_USER_PASS='***'
API_URL='https://api.corezoid.com/api/1/json/'
TIME=$(echo $(($(date +%s))))

JSON="{
    \"ops\" : [{
    \"ref\" : \"ref_32353\",
   \"type\" : \"create\",
    \"obj\" : \"task\",
\"conv_id\" : ${CONV_ID},
   \"data\" : {\"key1\" : \"val1\", \"key2\" : \"val2\"}
  }]
}"

SIGNATURE=$(echo -n "${TIME}${CONV_USER_PASS}${JSON}${CONV_USER_PASS}" | openssl dgst -sha1 | awk '{print $NF}')

REQ=$(curl --silent -XPOST ${API_URL}${CONV_USER_ID}/${TIME}/${SIGNATURE} --data "${JSON}")
echo "Result: ${REQ}"

Creating new process

#!/bin/sh

# Before you can start using Corezoid API you need to create an API key and get an authorization login and secret key.
# Create file with this script
# Check if file allowed for executing as program
# Allow executing as a program - chmod +x ./../conveyor_api_multipart/download_sh
# https://doc.corezoid.com/docs/protocol-description-v2
# Manage api_keys - https://admin.corezoid.com/users/api_key
# Set your env variables
# {{API_KEY_LOGIN}}, {{API_KEY_SECRET}}, {{API_URL}},

API_KEY_LOGIN="{{API_KEY_LOGIN}}"                                   # authorization login of your API key (for example {{API_KEY_LOGIN}} = 32
API_KEY_SECRET="{{API_KEY_SECRET}}"                                 # a secret key of your API key
API_URL="{{API_URL}}"                                               # URL to download_sh endpoint (for example {{API_URL}} = https://admin.corezoid.com/api/2/json
CONTENT_TYPE="application/json"

TIMESTAMP=$(printf $(($(date +%s))))
BODY="
{
    \"ops\": [
        {
            \"title\": \"Test\",
            \"description\": \"\",
            \"folder_id\": 0,
            \"obj\": \"conv\",
            \"create_mode\": \"without_nodes\",
            \"conv_type\": \"process\",
            \"type\": \"create\",
            \"status\": \"active\"
        }
    ]
}
"
SIGNATURE=$(printf "${TIMESTAMP}${API_KEY_SECRET}${BODY}${API_KEY_SECRET}" | openssl dgst -sha1 | awk '{printf $NF}')
REQ=$(curl --silent --header "Content-Type: ${CONTENT_TYPE}" -XPOST "${API_URL}/${API_KEY_LOGIN}/${TIMESTAMP}/${SIGNATURE}" --data "${BODY}")

printf "Result: ${REQ}"

Getting Corezoid object URL

#!/bin/sh

# Before you can start using Corezoid API you need to create an API key and get an authorization login and secret key.
# Create file with this script
# Check if file allowed for executing as program
# Allow executing as a program - chmod +x ./../conveyor_api_multipart/download_sh
# https://doc.corezoid.com/docs/protocol-description-v2
# Manage api_keys - https://admin.corezoid.com/users/api_key
# Set your env variables
# {{API_KEY_LOGIN}}, {{API_KEY_SECRET}}, {{API_URL}},
# {{OBJ_ID}}, {{OBJ_TYPE}}, {{COMPANY_ID}}, {{ASYNC}}

API_KEY_LOGIN="{{API_KEY_LOGIN}}"                                   # authorization login of your API key (for example {{API_KEY_LOGIN}} = 32
API_KEY_SECRET="{{API_KEY_SECRET}}"                                 # a secret key of your API key
API_URL="{{API_URL}}"                                               # URL to download_sh endpoint (for example {{API_URL}} = https://admin.corezoid.com/api/2/download

OBJ_ID={{OBJ_ID}}                                                   # ID of object (for example {{OBJ_ID}} = 316494)
OBJ_TYPE="{{OBJ_TYPE}}"                                             # Type of object, possible values: conv | folder | dashboard
COMPANY_ID="{{COMPANY_ID}}"                                         # company id (for examole {{COMPANY_ID}} = i814004545)
ASYNC={{ASYNC}}                                                     # possible values: true | false

TIMESTAMP=$(printf $(($(date +%s))))
BODY="
{
    \"ops\": [
        {
            \"obj_type\": \"${OBJ_TYPE}\",
            \"obj\": \"obj_scheme\",
            \"obj_id\": ${OBJ_ID},
            \"company_id\":\"${COMPANY_ID}\",
            \"async\": ${ASYNC}
        }
    ]
}
"
SIGNATURE=$(printf "${TIMESTAMP}${API_KEY_SECRET}${BODY}${API_KEY_SECRET}" | openssl dgst -sha1 | awk '{printf $NF}')
REQ=$(curl --silent -XPOST "${API_URL}/${API_KEY_LOGIN}/${TIMESTAMP}/${SIGNATURE}" --data "${BODY}")

printf "Result: ${REQ}"

Downloading Corezoid object by URL

#!/bin/sh

# Before you can start using Corezoid API you need to create an API key and get an authorization login and secret key.
# Create file with this script
# Check if file allowed for executing as program
# Allow executing as a program - chmod +x ./../conveyor_api_multipart/download_sh
# https://doc.corezoid.com/docs/protocol-description-v2
# Manage api_keys - https://admin.corezoid.com/users/api_key
# Set your env variables
# {{API_KEY_LOGIN}}, {{API_KEY_SECRET}}, {{DOWNLOAD_URL}},

API_KEY_LOGIN="{{API_KEY_LOGIN}}"       # authorization login of your API key (for example {{API_KEY_LOGIN}} = 32
API_KEY_SECRET="{{API_KEY_SECRET}}"     # a secret key of your API key
DOWNLOAD_URL="{{DOWNLOAD_URL}}"         # You can get from "get -> obj_scheme" request (for example {{DOWNLOAD_URL}} = # https://admin.corezoid.com/user_downloads/folder_1_1580304112.json

TIMESTAMP=$(printf $(($(date +%s))))
BODY=""
SIGNATURE=$(printf "${TIMESTAMP}${API_KEY_SECRET}${BODY}${API_KEY_SECRET}" | openssl dgst -sha1 | awk '{printf $NF}')

REQ=$(curl --silent -XGET "${DOWNLOAD_URL}/${API_KEY_LOGIN}/${TIMESTAMP}/${SIGNATURE}" -O -J)

printf "Result: ${REQ}"

Uploading Corezoid object

#!/bin/sh

# Before you can start using Corezoid API you need to create an API key and get an authorization login and secret key.
# Create file with this script
# Check if file allowed for executing as program
# Allow executing as a program - chmod +x ./../conveyor_api_multipart/download_sh
# Set your env variables
# {{API_KEY_LOGIN}}, {{API_KEY_SECRET}}, {{API_URL}},
# {{COMPANY_ID}}, {{FOLDER_ID}}, {{ASYNC}},
# {{FILE_DIR_PATH}}, {{FILE_NAME}}, {{CONTENT_TYPE}},
# {{TMP_FILE_PATH}}
# https://doc.corezoid.com/docs/protocol-description-v2
# Manage api_keys - https://admin.corezoid.com/users/api_key

API_KEY_LOGIN="{{API_KEY_LOGIN}}"               # authorization login of your API key (for example {{API_KEY_LOGIN}} = 32
API_KEY_SECRET="{{API_KEY_SECRET}}"             # a secret key of your API key
API_URL="{{API_URL}}"                           # URL to download_sh endpoint (for example {{API_URL}} = https://admin.corezoid.com/api/2/upload

COMPANY_ID="{{COMPANY_ID}}"                     # company id (for examole {{COMPANY_ID}} = i814004545)
FOLDER_ID="{{FOLDER_ID}}"                       # foder id for upload objects (for example {{FOLDER_ID}} = 0)
ASYNC="{{ASYNC}}"                               # possible values: true | false
FILE_DIR_PATH="{{FILE_DIR_PATH}}"               # Path to local file dir (for example {{FILE_DIR_PATH}} = /home)
FILE_NAME="{{FILE_NAME}}"                       # File name (for example {{FILE_NAME}} = test.json)
CONTENT_TYPE="{{CONTENT_TYPE}}"                 # possible values: application/json | application/zip
TMP_FILE_PATH="./gen_signature"                 # path to tmp file

TIMESTAMP=$(printf $(($(date +%s))))
FILE_PATH=${FILE_DIR_PATH}/${FILE_NAME}
BODY="Content-Disposition: form-data; name=\"type\"\r\ncreateContent-Disposition: form-data; name=\"obj\"\r\nobj_schemeContent-Disposition: form-data; name=\"folder_id\"\r\n${FOLDER_ID}Content-Disposition: form-data; name=\"async\"\r\n${ASYNC}Content-Disposition: form-data; name=\"company_id\"\r\n${COMPANY_ID}Content-Disposition: form-data; name=\"scheme\"; filename=\"${FILE_NAME}\"\r\nContent-Type: ${CONTENT_TYPE}\r\n"

printf "${TIMESTAMP}${API_KEY_SECRET}${BODY}" >> $TMP_FILE_PATH
cat $FILE_PATH >> $TMP_FILE_PATH
printf "$API_KEY_SECRET" >> $TMP_FILE_PATH
SIGNATURE=$(openssl dgst -sha1 $TMP_FILE_PATH | awk '{printf $NF}')
rm $TMP_FILE_PATH

REQ=$(
  curl  --silent -XPOST "${API_URL}/${API_KEY_LOGIN}/${TIMESTAMP}/${SIGNATURE}" \
        --header "Content-Type: multipart/form-data" \
        --form "type=create" \
        --form "obj=obj_scheme" \
        --form "folder_id=${FOLDER_ID}" \
        --form "async=${ASYNC}" \
        --form "company_id=${COMPANY_ID}" \
        --form "scheme=@${FILE_PATH};type=${CONTENT_TYPE}"
)

printf "Result: ${REQ}"

PYTHON

SDK for the work Corezoid.com:
https://github.com/MaxBondar/Corezoid

This module helps you send and modify tasks to Corezoid processes.

from Corezoid import Corezoid

# Insert Corezoid Process credentials
# Learn more about credentials: https://doc.corezoid.com/en/interface/access_management.html
API_KEY    = '<INSERT API KEY>' 
API_SECRET = '<INSERT API SECRET>'
PROCESS_ID = '<INSERT PROCESS ID>'

# Initialize Corezoid SDK
c = Corezoid(API_KEY, API_SECRET, PROCESS_ID)

# There are 2 methods available: send and modify tasks.
# Learn more about Corezoid API: https://doc.corezoid.com/en/api/upload_data/

# Send a new task to Corezoid process
def send_task(ref, data):
    # ref: string. Can be a custom value. By default it's a timestamp. 
    # data: JSON. Must be a JSON object.

    c.create_task(ref, data)

# Modify an existing task by ref at Corezoid process
def modify_task(ref, data):
    # ref: string. Can be a custom value. By default it's a timestamp. 
    # data: JSON. Must be a JSON object.

    c.modify_task(ref, data)

Below you can find examples of:

Modifying task by reference

Example flow:

  1. Send the request with the reference 130605ref1 for processing to http://my.api.com/getData via the API method.
  2. Process the request on api.my.com resource asynchronously.
  3. Receive a callback with the results.

Example of URL to which requests will be sent: https://api.corezoid.com/api/1/json/13000/{GMT_UNIXTIME}/{SIGNATURE}

{
    "ops":[
        {
            "type":"modify",
            "obj":"task",
            "ref":"130605ref1",
            "conv_id":"1234",
            "data":{
                "checkedClient":"true"
            }
        }
    ]
}

Response of a process after callback successfully accepted:

{
    "request_proc":"ok",
    "ops":[
        {
            "ref":"130605ref4",
            "proc":"ok"
        }
    ]
}

The "checkedClient":"true" parameter and its value will be added to the request with the 130605ref1 reference. After that request leaves standby mode in api_callback and proceeds to perform the corresponding logic.

Modifying task with Java SDK

SDK for the work middleware.biz:
https://github.com/corezoid/sdk-java/releases/tag/v2.1


import com.corezoid.sdk.entity.CorezoidMessage;
import com.corezoid.sdk.entity.RequestOperation;
import com.corezoid.sdk.utils.HttpManager;
import java.util.Arrays;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.http.HttpException;

public class MiddleWareModify {

    public static void main(String[] args) {
        try {
            // ID process
            String conv_id = "15476";
            // API user settings
            String apiLogin = "5965";
            String apiSecret = "VjKyfIuVAFOGGZwLLFfkHvrTPFUTBBP6E3A8596vIj5jiwqSsK";
            // ModifÏy task
            String ref = "test141874099180849";
            JSONObject data = new JSONObject()
                    .element("phone", "+380989055434")
                    .element("ref", "test141874099180849");
            RequestOperation operation = RequestOperation.modifyRef(conv_id, ref, data);
            // Add task to list
            List<RequestOperation> ops = Arrays.asList(operation);
            // Build a Message
            ConveyorMessage message = ConveyorMessage.request(apiSecret, apiLogin, ops);
            // Create HttpManager instance
            HttpManager http = new HttpManager();
            // Send all tasks to Middleware
            String answer = http.send(message);
        } catch (HttpException ex) {
            System.out.println(ex);
        }
    }

}

For more information on asynchronous API methods, go to Corezoid API reference.


Was this article helpful?

What's Next