K2 API - K2 web services
Introduction
Warning: end of support for the original K2 API
The K2 Bora version is the last version that contains the original K2 API described in this chapter. The following K2 versions will no longer contain this interface.
We recommend switching to the new K2 API v2 in good time. It offers similar options and, in addition, also runs on Linux in Docker, supports authentication using JWT tokens, handles error states better and allows passing context information (language, own company, information warehouse, business year). Because the structure of requests and responses has changed and API v2 communicates only in JSON format, existing integrations need to be modified. Start the transition as soon as possible.
You can find more information in the chapter
K2 API is a web application running on the Microsoft Internet Information Services (IIS) web server. Through the K2 application server, it makes the data of the K2 information system available and allows running scripts and reports.
The web services are based on the REST technique, i.e. communication takes place using the HTTP protocol and the standard methods GET (reading data), POST (creating data), PUT (modifying existing data).
Data can be read and sent either in XML or JSON format.
After entering the root URL of the K2 API in a browser, you can browse the basic description of the services and resources/operations using the dynamic help.

Picture: K2 API dynamic help
Note: If this page appears, it means that the initial communication between K2 API and the application server has already taken place. If an IIS error page appears instead, it means that the communication failed and most likely there is an error in the K2 API configuration or the K2 application server is not running.
Installation and basic settings
Prerequisites
- At least one K2 API thread must be available in the K2 license (the Number of shared users item), and a corresponding number of so-called anonymous users must be created in K2, with logins composed of the same prefix followed by a serial number at the end (e.g. "AN1" – "AN5"). These users must have identical rights and an identical password.
- An installed and running application server with "Configure the application server for the web services server" checked during installation. If this option was not checked during installation, the following parameters can be added to the K2.INI configuration file of an existing AS installation (example for 5 threads and users named AN1 – AN5):
AS3USER='AN'
AS3PASSWORD='ANPassword'
AS3USERS=5
AS3IO=2000034152
- The server on which K2 API will be installed must have IIS available with ASP.NET and WCF support installed. When installing IIS, it is necessary to select in particular these components:
- Roles: Default + Application Development (.NET 4.5, ASP.NET 4.5), Management Tools (including IIS 6 compatibility); Do not check: WebDAV Publishing
- Features: Windows Process Activation Service (Process Model), WCF Services (HTTP Activation), .NET 4.5, ASP.NET 4.5
- In the case of an HTTPS installation, a correctly set certificate in IIS
- In the case of publishing K2 API for access via the internet, the used HTTP/HTTPS ports allowed (80/443 by default)
Recommended deployment for accessing K2 API from the internet
The K2 application server should always be installed on a server accessible only in the internal network. It is recommended to install K2 API and any other web applications on a separate server that is accessible from the internet and has restricted access to the internal network, allowing only communication with the K2 AS.
K2 API installation
It is performed using the K2 installer. Before the installation starts, the K2 API installation program checks the availability of the basic required components; if any components are missing, it displays a warning and the installation is stopped.
Several items of data need to be entered during the installation:
- Target directory – any directory can be selected; it does not have to be in the IIS root directory
- IIS server name – enter the name through which the server with K2 API will be accessed. For test installations, "localhost" can also be entered – however, under this name K2 API will be available only on the given server.
- Web site on IIS (Web Site) – select the Web Site into which you want to install K2 API. By default, only the "Default Web Site" is available on IIS
- Application name on IIS – the part of the K2 API URL address after the server name. If the server name is "mujserver.cz" and you specify "restservice" as the application name, the base URL for accessing K2 API will be http://mujserver.cz/restservice
- Name or IP address of the computer where K2 AS is running
- K2 AS instance name – entered during the K2 AS installation
The most common problems when installing and configuring K2 API
- Incorrect name or IP address of the server with the AS, or incorrect AS instance name – check and if necessary adjust manually in the K2 API configuration file – the web.config file in the K2 API installation directory. Check that nothing blocks network communication between the server with K2 API and the server with the AS
- The AS is not configured for K2 API – add the configuration, see the Prerequisites part above
- Anonymous users are missing or disabled - see the Prerequisites part above
- The number of shared users is not specified in the K2 license or this number has been exceeded – update the K2 license
- Missing IIS components – check the IIS components, see the Prerequisites part above
In most cases, logging of K2 API or the AS helps. K2 API logging is enabled in the web.config configuration file, with the parameters LogPath (path to the log file), LogLevel (types of messages to be recorded; at least Info is recommended for debugging), LogRequests (allows tracking the processing of individual requests to K2 API even when multiple requests run concurrently).
URL address structure
Using the URL address, we specify the resource (most often data, a certain record) we want to work with, or the operation we want to run.
Basic URL format:
<server address>/{xml/}<service name>/<resource or operation>{?optional parameters}
- <server address> is the root address of K2 API. For example http://mujserver.cz/restservice
- {xml/} – optional switch. If it is specified in the URL, we request output in XML format; if it is not specified, we request JSON format
- <service name> - specification of the particular K2 API service we want to use
- <resource or operation> - specification of the particular request
- {?optional parameters} – any parameters specific to the given request
Web services
Data - Service used for working with data objects (data modules).
Meta – Service that allows obtaining a description of the structure of data objects.
Formation – Allows running scripts and reports.
FormationDefinition – Allows obtaining definitions of scripts and reports.
Eshop – Groups special resources and operations for the K2 e-shop.
Notification – Support for notifications.
Data service
Used for working with data (data objects) stored in K2.
List of records of a data object
GET /Data/{classname}?<optional parameters>
The request is used to read a list of data objects of the {classname} type. The list is paged; not all records are read at once. Unless specified otherwise by optional parameters, the first 30 records are returned with the values of the implicit columns and all components of the primary key.
Parameters:
- {classname} – name of the data object class (e.g. TD_Part), or an alias (i.e. an alternative name, e.g. Part)
- fields – comma-separated list of names of data fields whose values we want returned. A path to fields via a link, or the name of an item module followed by the name of a field from the item data object, can also be specified (individual field names in the path are separated by a dot).
- orderBy – comma-separated list of names of data fields by which we want to sort the data. For descending order, the - (minus) character must be placed before the field name.
- pageSize – required number of records per page (the maximum number of records returned in one response). If the value -1 is specified, paging is disabled and all records are returned at once.
- page - the variable controls moving to other pages - possible values are last, prev, next, first
- pageState – internal variable identifying the current page. The value of this variable (or the whole URL address) is always returned in the server response.
- orOperator – specifies the logical connective between the individual conditions in conditions
- conditions – used for filtering data (i.e. building selections over a data module).
- The individual conditions have this form:
- field;[!]LT|LE|GT|GE|EQ|NE[@];"value"|value
- field;[!]EMPTY
- field;[!]LIKE[*][^][#];"value"|value
- field;[!]IN;"value1"|value1[;"value2"|value2]...
- field;[!]BETWEEN;"valueFrom"|valueFrom;"valueTo"|valueTo
- field – name of or path to the data field
- ! – negation of the condition
- @ - instead of a constant, the parameter is expected to contain the name of or path to another data field whose value is to be used for the comparison
- value – operand value
- "value" – operand value, if it needs to contain a separator character (comma or semicolon)
- Possible operators:
- LT – less than
- LE – less than or equal to
- GT – greater than
- GE – greater than or equal to
- EQ – equal to
- NE – not equal to
- EMPTY – the field value is empty (not entered)
- IN – in a set
- BETWEEN – between
- LIKE – Comparison of text strings (condition "contains", "starts with", etc.)
- • the * character after the LIKE operator means that wildcards are allowed in the value. Any character(s) can then appear in the value in place of the * character. If LIKE* is not specified, the * character in the value is really treated as part of the value.
- • the ^ character after the LIKE operator turns on case sensitivity.
- • the # character after the LIKE operator switches the condition to "starts with" mode. When the condition is evaluated, a wildcard is automatically added before the entered value.
Note: Both ProgName and AliasName (usually ProgName translated into English) can be used as the field name in all parameters. The K2 API response always returns AliasName.
Response structure:
<PagedList>
<Items> // List of data objects of the {classname} class
</Items>
<FirstPageURL /> // URL address of the first page
<NextPageURL /> // URL address of the next page
<PrevPageURL /> // URL address of the previous page
<LastPageURL /> // URL address of the last page
<RequestedFields /> // names of the returned data fields (e.g. implicit columns)
</PagedList>
Examples:
http://localhost/WS136/xml/Data/Part - returns the first 30 partners with implicit columns, sorted by the primary key.
http://localhost/WS136/xml/Data/Part?fields=Name,ID_NO,Group.Abbr,EAddress.FullEAddress&orderBy=Name&pageSize=10 – returns the first 10 partners sorted by name with these fields: name, Comp. Reg. No., group abbreviation, and for each partner all items of electronic addresses (the value of the FullEAddress field).
http://localhost/WS136/xml/Data/Part?conditions=PartnerId;GT;10,Abbr1;LIKE*;Shell* - returns at most the first 30 partners for which the partner number is greater than 10 and at the same time the abbreviation starts with "Shell".
POST /Data/GetList/{classname}
This is an alternative to the previous call. In the body of the POST request, a DataParameterFields object is expected with the same parameters that can be specified in the URL address of the GET request. This call solves the limitation of the maximum URL address length in the case of complex queries.
Request body structure:
<DataParameterFields xmlns="K2.Data">
<Conditions></Conditions>
<Fields></Fields>
<OrderBy></OrderBy>
<Page></Page>
<PageSize></PageSize>
<PageState></PageState>
<orOperator></orOperator>
</DataParameterFields>
Detail of a specific data object
GET /Data/{classname}/{*PrimaryKeys}/?<optional parameters>
Used to read the detail of one specific record identified by the primary key.
Parameters:
- {classname} – name of the data object class (e.g. TD_Part), or the short name (Part)
- {*PrimaryKeys} – primary key components separated by the / character. For a two-component key, for example /Data/{classname}/first component/second component
- fields - comma-separated list of names of data fields whose values we want returned. A path to fields via a link, or the name of an item module followed by the name of a field from the item data object, can also be specified (individual field names in the path are separated by a dot).
Response structure:
<DataObjectWrapper>
<DOClassName /> // classname of the returned data object
<FieldValues> // collection with the values of data fields
<NameValue> // one data field
<Name></Name> // name of the data field (alias)
<Value></Value> // value of the data field or the referenced data object <NoPermission /> // flag indicating that the user has no right to the field value
</NameValue>
...
</FieldValues>
<ItemURL /> // URL address of the detail of this data object
</DataObjectWrapper>
Note: The NoPermission flag appears set to true only if the field value cannot be obtained due to the evaluation of read rights to the given field. In this case, no field value is sent – the Value property.
Example:
http://localhost/WS136/xml/Data/Part/15 - returns the detail of the partner record with number 15 with data fields according to the implicit columns.
Create new record
POST /Data/{classname}?<optional parameters>
Sending a data object that is to be created and saved to the K2 database. The response returns the detail of the saved record.
Parameters:
- {classname} – name of the data object class (e.g. TD_Part), or the short name (Part)
- fields - comma-separated list of names of data fields whose values we want returned. A path to fields via a link, or the name of an item module followed by the name of a field from the item data object, can also be specified (individual field names in the path are separated by a dot).
Request body structure:
- DataObjectWrapper object with the entered values of data fields
Response structure:
- The same as when reading the detail of a specific record using the GET method
Changing an existing record
PUT /Data/{classname}/{*PrimaryKeys}/?<optional parameters>
Sending a modified data object back to the K2 database. The response returns the detail of the saved record.
An existing record is usually modified by first reading the data object via K2 API, adjusting the values of its fields and sending it back for saving using this request. It is important to always load and send back the value of the "TimeStamp" data field (or of all system fields – more in the description of the detailed data object structure of the Meta service). If the value of the TimeStamp field (or the values of the system fields) is not sent back, the operation ends with an error. The TimeStamp field check is introduced to prevent collisions when a record is changed by several users at the same time (i.e. if someone else modified the data object between the time it was loaded and the save call).
When editing owned items, a specific item can be marked with the "Deleted" flag. After it is sent to K2 API, the item is also removed as part of saving the changes in the header and items. An edited or removed item must have all components of its primary key specified in the request.
Parameters:
- {classname} – name of the data object class (e.g. TD_Part), or the short name (Part)
- {*PrimaryKeys} – primary key components separated by the / character. For a two-component key, for example /Data/{classname}/first component/second component
- fields - comma-separated list of names of data fields whose values we want returned. A path to fields via a link, or the name of an item module followed by the name of a field from the item data object, can also be specified (individual field names in the path are separated by a dot).
Request body structure:
- DataObjectWrapper object with the entered values of data fields
Example with deleting an item:
<DataObjectWrapper xmlns="K2.Data" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<DOClassName>Part</DOClassName>
<FieldValues>
…
<NameValue>
<Name>ListBusinessChild</Name>
<Value i:type="ChildDataObjectWrapper">
<Items>
<Item>
<DOClassName>MBusiness</DOClassName>
<Deleted>true</Deleted>
<FieldValues>
<NameValue>
<Name>RID</Name>
<Value i:type="a:long" xmlns:a="http://www.w3.org/2001/XMLSchema">8495445311489</Value>
</NameValue>
</FieldValues>
</Item>
</Items>
</Value>
</NameValue>
</FieldValues>
</DataObjectWrapper>
Response structure:
- The same as when reading the detail of a specific record using the GET method
META service
Used to obtain the structure of data objects
List of available data objects published for K2 API
GET /Meta
Response structure:
<ArrayOfDataObjectMetaData>
<DataObjectMetaData> // information about one data object class
<Caption /> // displayed name
<ClassName /> // classname – class name used in the URL
<IsHeader /> // flag indicating whether this is a header object type
<V3ClassName /> // internal name of the data object class (DM class)
</DataObjectMetaData>
...
</ArrayOfDataObjectMetaData>
Detailed structure of a specific data module
GET /Meta/{classname}
Response structure:
<DataObjectMetaData>
<Caption /> // displayed name
<ChildList /> // list of item fields of the data object
<ClassName /> // classname – class name used in the URL
<FieldList /> // list of scalar fields of the data object
<IsHeader /> // flag indicating whether this is a header object type
<LinkList /> // list of link fields of the data object
<PrimaryKeyFieldList /> // list of primary key fields
<SystemFields /> // list of fields that must be transferred when changing an existing data object
<V3ClassName /> // internal name of the data object class (DM class)
</DataObjectMetaData>
The elements of the ChildList, FieldList, LinkList, PrimaryKeyFieldList and SystemFields lists are FieldMetaData objects:
<FieldMetaData>
<Caption /> // Field header
<Description /> // Field description
<Name /> // Field naming
<FieldName /> // Field name for the URL and designation in the data
<V3FieldName /> // Corresponding field name in K2 (ProgName)
<ValueType /> // Field value type, can be: Date, Time, DateTime, Bitmap, Numeric
<IsRequired /> // Field required for saving
<IsReadOnly /> // The field is read-only
<LinkClassName /> // Name (classname) of the data object type of the link field
<LinkV3ClassName/> // Corresponding data module name of the link field
<ChildClassName /> // Name (classname) of the data object type of the items
<ChildV3ClassName/> // Corresponding data module name of the items
<KeyIndex /> // Serial number of the field in the primary key
<ItemURL /> // Link to the definition of the corresponding data object type, used for link and item fields
</FieldMetaData>
Note: The SystemFields collection is available only from version K2.point. All fields listed in this collection must be loaded during editing and sent back in the request to save the changes. Without them, K2 API does not allow the record to be saved.
Formation service
Used to obtain a list of available scripts and reports and to run them.
All scripts and reports used via K2 API must be adapted to run on the K2 application server and marked as AS3Compatible. Furthermore, they must be stored in the database (the Scripts, reports module); they cannot be in the file system. They can also be assigned to a specific data module over which it makes sense to run them.
List of available scripts and reports
GET /Formation?<optional parameters>
Parameters:
- ClassName – without this parameter, a list of all scripts and reports is returned. If the parameter is specified, only scripts and reports assigned to the given data object type and scripts without a specified assignment are returned.
Response structure:
<ArrayOfFormationId>
<FormationId> // descriptive object of the script
<DefinitionURL /> // URL address for the detail of the script/report definition
<FormationID /> // File name of the script/report
<ItemURL /> // URL address for running the script/report
<Name / > // Name of the script/report
</FormationId>
...
</ArrayOfFormationId>
Running a script or report without specifying data
With this type of run, AktDM is not passed to the script, so the script cannot work with it. In the case of a script, the output parameters (those whose value was changed while the script was running) are returned by default, or a PDF file in the case of running a report.
GET /Formation/{folder}/{name}/{ext}?<script parameters>
Parameters:
- {folder} – directory name (Special/Standard)
- {name} – file name of the script/report
- {ext} – extension (pas for scripts, am for reports)
- <script parameters> - script parameters can be entered in the URL in the form parameter=value.
- returnOutFileData – optional parameter for running reports and scripts that return a file. If set to "true", the binary data of the file are returned directly in the BulkData response instead of the URL address for downloading the file.
Response structure:
<FormationOutput>
<URL /> // URL address of the output file
<Parameters> // values of the output parameters
<Parameter>
<Name /> // Parameter name
<Value /> // Parameter value
</Parameter>
...
</Parameters>
<BulkData /> // output binary data
</FormationOutput>
Example:
http://localhost/WS136/xml/Formation/Standard/WkfWSProcDef/PAS?DefTypeAbbr=TEST – runs the script ::\\DBNAME\Standard\WkfWSProcDef.PAS and sets its parameter DefTypeAbbr to the value "TEST".
Running a script with data specification
Unlike the previous call, this one allows you to send, before the run, a definition of the data on which the report or script is to be run, as well as parameter values. The rest of the behaviour remains the same.
POST /Formation/{folder}/{name}/{ext}
Request body structure:
<FormationInput>
<Conditions /> // selection conditions (format as in the URL address)
<CurrentPrimaryKey> // definition of the primary key of the record for the run
<Segment>
<Name /> // data field name
<Value /> // data field value
</Segment>
</CurrentPrimaryKey>
<DataObjectName /> // classname of the data object
<ORConditions /> // true – OR between conditions, false - AND
<Parameters> // script parameter values
<Parameter>
<Name /> // Parameter name
<Value /> // Parameter value
</Parameter>
</Parameters>
<PrimaryKeys> // list of primary keys of records for the run
<PrimaryKey>
<Segment>
<Name />
<Value />
</Segment>
</PrimaryKey>
</PrimaryKeys>
<ReturnUrl /> // true – return the URL address of the output file (e.g. a PDF with the report output)
</FormationInput>
Running a script with an HTML result
Allows you to run a script that generates an HTML page and display this page directly in the browser.
GET /Formation/html/{folder}/{name}/pas
A comprehensive example of this web service call is shown in the standard script Example 127 - generating HTML for K2 web services.
Running a script or report and downloading the output file
Allows you to run a report or a script that creates a file and then download this file directly. After entering the URL in the browser, the browser dialog for saving/opening the file is displayed. In the case of a script, the name of the downloaded file can also be set using the script procedure SetOutFileName.
GET/POST /Formation/download/{folder}/{name}/{ext}
Any script parameters can be entered in the URL address (in the case of the GET method) or in the body of the POST request.
Example of the script being run:
program TestDownload;
info
Title = 'TestDownload';
As3Compatible = true;
end;
modules
DM: TD_Job;
var
Exec: TAmExecutorNonVisual;
begin
DM.CreateDm;
DM.SetState(tfNormal, DM.PrimaryKey, False);
Exec := TAmExecutorNonVisual.Create;
try
Exec.AktDm := DM;
Exec.OpenCachedReport('TaskList.AM');
Exec.Execute;
Exec.ToExport('', 0, 9999, extyXLS, exdeToFile, prinPath + '\TasksList.xls');
SetOutFileName(prinPath + '\TasksList.xls');
finally
Exec.Free;
end;
end.
Error handling when working with the K2 API
Errors that occur during deserialization of the request body, before the web service code is called, are handled by .NET, which returns the BadRequest status without any further details of the error being available. This error is returned in HTML format.
An error that occurs in the K2 API code or on the application server is returned as a text response in the format: [ErrorKind]ErrorText.
ErrorKind – Enumeration specifying the error type:
- AS3Message - may occur while processing a report or script
- AS3Warning - may occur while processing a report or script
- AS3Error - an error occurred while the application server was processing the request
- AS3Terminated - this is a critical error of the application server; the session under which the request was being processed was terminated because the application server stopped running or because of a network error between the application server and the database server.
- RequestError – an error while processing the K2 API request. Most often it is an incorrectly specified request (status BadRequest). The status Unauthorized means a user authentication error.
- CommunicationError – a communication error occurred between the K2 API and the application server.
- UnknownError – unidentified error
ErrorText – a more detailed description of the error that occurred.
Example of calling a special script
Script example
program PrikladWS(
ParamText {$DESC 'Input text parameter'}: string = '';
ParamCislo {$DESC 'Input numeric parameter'}: integer = 0;
Vystup {$DESC 'Output parameter'}: string = ''
);
info
Title = 'WS example';
AS3Compatible = true;
end;
modules
TD_Part;
begin
Vystup := 'Values passed: ParamText=' + ParamText + ', ParamCislo=' + IntToStr(ParamCislo) + ', Vystup=' + Vystup;
if (AktDM is TD_Part) then begin
Vystup := Vystup + ', AktDM=' + Trim(TD_Part(AktDM).Zkratka1);
end;
WriteLn(DateTimeToStr(Now) + ': ' + Vystup);
end.
The script must be saved in the database (the Scripts and reports book) as PrikladWS.pas. In the info section, AS3Compatible must be set to true. By setting this parameter, the author of the script confirms that they have verified that the script can be compiled and run on the AS (i.e. they have removed all visual parts from the script and the script can run in the multi-threaded environment of the AS).
This script inserts into the output parameter Vystup a text with the input values of all script parameters and, if the script is run over the partner data module, it also adds the abbreviation of the current partner. It writes the current date and time and the same text to the standard output of the script (a text file K2Export.txt with this text is created in the directory of the current K2 user).
Example of a call using a GET request
Only the script parameter values are passed; AktDm is not set in the script
URL:
http://localhost/WS136/xml/Formation/Special/PrikladWS/pas?ParamText=aaa&ParamCislo=123
Resulting response:
<FormationOutput xmlns="K2.Data" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Parameters>
<Parameter>
<Description/>
<Name>Vystup</Name>
<Value i:type="a:string" xmlns:a="http://www.w3.org/2001/XMLSchema">Values passed: ParamText=aaa, ParamCislo=123, Vystup=</Value>
</Parameter>
</Parameters>
</FormationOutput>
Example of a call using a POST request
Setting AktDm to the partner with number 5 and setting the parameter values.
URL:
http://localhost/WS136/xml/Formation/Special/PrikladWS/pas
HTTP header:
Content-Type: application/xml; charset=utf-8
Content-Length: 472
Request body:
<FormationInput xmlns="K2.Data" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:t="http://www.w3.org/2001/XMLSchema">
<CurrentPrimaryKey>
<Segment>
<Name>CisPart</Name>
<Value i:type="t:integer">5</Value>
</Segment>
</CurrentPrimaryKey>
<DataObjectName>TD_Part</DataObjectName>
<Parameters>
<Parameter>
<Name>ParamText</Name>
<Value i:type="t:string">Entered text</Value>
</Parameter>
<Parameter>
<Name>ParamCislo</Name>
<Value i:type="t:integer">12345</Value>
</Parameter>
</Parameters>
</FormationInput>
Note: Above all, the header must contain "Content-Type", i.e. what kind of data we are sending to the K2 API, and in the body the data type must be specified for the value of all Name-Value pairs so that the K2 API knows during deserialization which data type the text from the XML document is to be converted to.
Resulting response:
<FormationOutput xmlns="K2.Data" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Parameters>
<Parameter>
<Description/>
<Name>Vystup</Name>
<Value i:type="a:string" xmlns:a="http://www.w3.org/2001/XMLSchema">Values passed: ParamText=Entered text, ParamCislo=12345, Vystup=, AktDM=DEMO TRADE</Value>
</Parameter>
</Parameters>
</FormationOutput>
Authentication of K2 API requests
The K2 API can work in the so-called anonymous mode only for debugging service calls. In a production environment, authentication must always be required. After installation, the K2 API is in this mode by default. Switching to the anonymous mode is done in the configuration file web.config in the K2 API installation directory by setting the value of the Anonymous parameter to true.
To pass and verify the identity, every request sent to the K2 API must contain the standard HTTP header Authorization set to the value {UserName}:{HMACHash}, where {UserName} is the user name of the user and {HMACHash} is a text string created using the HMAC MD5 algorithm. The key for the hash is the user's password and the hashed message is the full URL address in unencoded form (i.e. without URL encoding of special characters) converted to upper case. The resulting HMAC hash is then converted to text using base64 encoding.
Alternatively, the hash can also be passed directly in the URL address using the "x-auth" parameter. In this case, the entire request URL is composed, &x-auth= is appended to its end and the whole text is passed to the hash function. The result of the hash function is then again appended to the end of this text.
Examples
Example of the algorithm in Java
public static String calcHMAC(String src, String password)
{
SecretKeySpec sk = new SecretKeySpec(password.getBytes(), "HmacMD5");
Mac mac = Mac.getInstance("HmacMD5");
mac.init(sk);
byte[] result = mac.doFinal(URLDecoder.decode(src, "UTF8").toUpperCase().getBytes());
return Base64.encodeToString(result, Base64.NO_WRAP);
}
Example of the algorithm in C#
public static string CalcHMAC(string src, string password)
{
byte[] secretBytes = Encoding.UTF8.GetBytes(password);
HMACMD5 hmac = new HMACMD5(secretBytes);
byte[] dataBytes = Encoding.UTF8.GetBytes(Uri.UnescapeDataString(src).ToUpper());
byte[] computedHash = hmac.ComputeHash(dataBytes);
return Convert.ToBase64String(computedHash);
}
Example of the algorithm in Go
func getAuthHeader(source_url string, username string, password string) string { // 1. initialize hmac encoder, key is password hmacEncoder := hmac.New(md5.New, []byte(password))
// 2. url decode & convert to uppercase urlDecoded, _ := url.QueryUnescape(source_url) upperFullURL := strings.ToUpper(urlDecoded)
// 3. hmac encode hmac encoder hmacEncoder.Write([]byte(upperFullURL)) hmacHash := base64.StdEncoding.EncodeToString(hmacEncoder.Sum(nil))
return username + ":" + hmacHash
}
Example in a K2 script
function CalcHMAC(ASrc, APassword: string): string;
begin
if not CreateHMacMD5HashBase64(AnsiUpperCase(HTTPDecode(ASrc)), APassword, Result) then
Result:= ' ';
end;
Example of a function in a K2 script for adding the hash directly to the URL
function AppendAuthorizationHeader(aURL: string; aUsername: string; aPassword: string): string;
var
lHash: string;
begin
Result := aUrl;
if (Pos('?', aURL)=0) then
aURL := aURL + '?x-auth='
else
aURL := aURL + '&x-auth=';
if CreateHMacMD5HashBase64(AnsiUpperCase(aURL), aPassword, lHash) then
Result := aURL + HTTPEncode(aUsername + ':' + lHash);
end;
Example of the algorithm in PHP
function getAuthorizationHeader($password, $fullUrl) {
return base64_encode(hash_hmac('md5', mb_strtoupper(rawurldecode($fullUrl), 'UTF-8'), $password, true));
}
Advanced K2 API configuration
The entire configuration of the web services server is done using the usual IIS configuration file – web.config. Besides the specific K2 API settings (e.g. information about the application server, logging settings), it contains other IIS and WCF service settings.
Setting the request size limit or the maximum URL address length
When sending large data using a POST or PUT request to the K2 API, you may run into the maximum request size limit applied by the default IIS settings. This limit manifests itself in that the K2 API starts responding with error messages with a 4xx code, for example 400 Not found or 413 Entity too large. From version move.02, the K2 API contains a default setting of the maximum size of received data of 50MB. This setting can be changed in the configuration file in these places:
- httpRuntime.maxRequestLength in the system.web section – general setting of the maximum size of an HTTP request. The value is given in kB.
- requestLimits.maxAllowedContentLength in the system.webServer/security/requestFiltering section – setting of the IIS "request filtering" module. This parameter can be used to set the maximum size of the request body. The value is given in bytes.
The <requestLimits> element also has other attributes, e.g. maxQueryString or maxUrl, which can be used to affect the maximum length of the parameters in the URL address, or of the entire URL address, respectively. - binding.maxReceivedMessageSize – setting of the size of the received message for a specific service "binding". The value is again given in bytes.
The <binding> element occurs several times in the configuration file (for HTTP and HTTPS communication) and usually needs to be set in all places. - The <readerQuotas> element for a binding – can be used when sending excessively complicated data (e.g. many nested XML/JSON levels, long text values of elements in XML)
Configuration of "bindings"
The standard configuration file contains the following bindings for all K2 API modes:
- UnsecureBinding – binding for the REST API over the unsecured HTTP protocol. If it is not specified, the HTTP protocol will not be supported.
- ssl – binding for the REST API over the secured HTTPS protocol. If it is not specified, the HTTPS protocol will not be supported.
- wsUnsecure, wsssl – for the SOAP v1.2 interface of the Formation service
- basicUnsecure, basicssl – for the SOAP v1.1 interface of the Formation service