Introduction
K2 API v2 is a web application that makes the data and functions of the K2 information system available to other applications. It communicates with the K2 application server (AS) and through it allows reading, creating and changing data, obtaining a description of their structure, running scripts and reports, and using other specialized interfaces – for example, for connecting an e-shop.
Thanks to the K2 API, K2 can be connected to the outside world without the external application having to know the internal structure of the database or run as a K2 client. All requests pass through the same application logic as work in K2 – user rights, checks on saving and business rules are applied.
The web services are based on the REST architecture. Communication takes place over the HTTP (HTTPS) protocol using standard methods (GET for reading, POST for creating and running operations, PUT for changing data). The JSON format is used exclusively for data exchange.
K2 API v2 is the successor to the original K2 API. It corresponds to it functionally and extends it in many areas, but it is built on a new technology that brings the option of running outside Windows, a modern method of authentication and better error handling.
What the K2 API is used for
Typical usage scenarios:
- E-shops and B2B portals – reading the catalogue of articles, prices and availability, creating orders and partners. Specialized operations (text pages, localized texts) are also available for K2 web solutions.
- Mobile and web applications – e.g. applications for sales representatives, warehouse workers or service technicians.
- Integration with other systems – data exchange with external CRM, WMS, attendance, production or logistics systems, connection to a marketplace (e.g. Alza) or a telephone exchange.
- Automation – running K2 scripts and reports from external processes, generating documents (e.g. PDF), working with documents attached to records.
Documentation of a specific instance
After entering the root address of the K2 API into a browser, a home page is displayed with information about the version and a link to the interactive documentation. The documentation is generated from the OpenAPI (Swagger) specification and corresponds to the installed version of the K2 API. In it, you can browse the available services and operations, request and response structures and sample examples, and try individual calls directly from the browser.

Picture:
Example for the demo instance:
- root address: https://demo.k2.cz/k2apiv2/
- interactive documentation: https://demo.k2.cz/k2apiv2/swagger
- OpenAPI specification (JSON): https://demo.k2.cz/k2apiv2/swagger/internal/v1/openapi-k2.json
The OpenAPI specification can be used to automatically generate a client in any programming language, or it can be imported into API testing tools (Postman, Insomnia, etc.).
Tip: If the home page is displayed, the K2 API is running. You can verify whether the K2 application server is also available by calling GET /system/ping – it returns status 200 if at least one application server is available.
What is new compared to the original K2 API
The options of the new API remain similar to those of the original K2 API. The main differences are summarized in the table:
Area |
|
|
K2 API v2 |
|
Operating environment |
Windows only, IIS (ASP.NET, WCF) |
Windows in IIS or Linux in a Docker container |
||
Data format |
XML or JSON |
JSON only |
||
Authentication |
HMAC request signature |
HMAC request signature or JWT token (access + refresh token) |
||
Responses and errors |
Data without a uniform envelope; errors as text [ErrorKind]ErrorText, deserialization errors as an HTML page |
Every response in a uniform JSON envelope with a status code, error message and list of errors; standard HTTP status codes |
||
Context information |
Only language, e-shop RID |
HTTP headers for language, own company, information warehouse, period, currency and more |
||
Loading lists |
Sequential paging using the URL of the next/previous page |
Sequential paging and now also direct access to any page, including the total number of records |
||
Filtering |
Conditions in the conditions parameter, saved filter in K2 |
Conditions in the conditions parameter, saved filter in K2, structured conditions (AND/OR, conditions on items) |
||
Documentation |
Dynamic WCF help |
OpenAPI (Swagger) with examples and the option to try out calls |
||
API - AS communication protocol |
Named pipes |
TCP connection |
Other new features:
- optional flattening of links in the response (flattenLinks parameter) – values from linked objects are returned as fields with a path, e.g. ArticleTypeId.Description,
- running a script with direct access to the HTTP request and response (/formation/raw/…) – the script itself processes the request body and creates any response, which makes it possible to implement custom interfaces (e.g. third-party webhooks).
- More advanced load balancer when running the API against multiple application server instances
- Tracing and tracking down API requests using the RequestDebugId response header
Warning for migration from the original API: The structure of requests and responses has changed (uniform envelope, naming of JSON properties, service addresses) and XML support has been dropped. Existing integrations therefore cannot simply be redirected to K2 API v2 – they must be modified according to the OpenAPI specification.
Architecture and deployment
K2 API v2 is a standalone web application that stands between client applications and the K2 application server. The client sends requests to the K2 API, which passes them to the application server for processing and returns the result to the client in JSON format. The client thus never communicates directly with the application server or the database.
Operating variants
- Windows / IIS – a classic installation on the Microsoft IIS web server, suitable for environments where K2 is operated on Windows servers.
- Linux / Docker – the K2 API runs as a container. This variant makes it easier to deploy in an environment with container orchestration, to update to a new version and to run multiple instances.
The installation and configuration procedure of the individual variants is described in the K2 API v2 chapter
Recommended deployment for access from the internet
The K2 application server should always be installed on a server accessible only from the internal network. It is recommended to run the K2 API (like other web applications) on a separate server or in a container that is accessible from the internet and has only communication with the K2 application server allowed into the internal network. The K2 API is therefore typically located in the DMZ. Always use the secure HTTPS protocol for access from the internet.
Licence and users
K2 API requests are processed by the K2 application server. Operation therefore requires a corresponding number of K2 API threads in the K2 licence and a correctly configured application server.
- a corresponding number of so-called anonymous users is created in K2, with a login composed of the same prefix followed by a sequence number at the end (e.g. "AN1" – "AN5"). These users must have identical rights and an identical password.
- During installation, the K2 application server was configured for the web services server, i.e. the K2.INI configuration file contains these parameters:
AS3USER='AN'
AS3PASSWORD='ANPassword'
AS3USERS=5
AS3IO=2000034152
Network communication requirements
K2 API v2 communicates with the application server using the TCP protocol. The application server must therefore be configured to operate on the TCP protocol, and the selected TCP port must be allowed on all firewalls between the server with the K2 API and the server with the K2 AS.
Example of the content of the K2.INI configuration file of the AS:
AS3SERVERPROTOCOLS=3 ; the AS listens on both named pipes and TCP
AS3SERVERPORT=10010 ; number of the TCP port on which the AS listens
Configuration file parameters
K2 API v2 has all its configuration parameters stated in the appsettings.json configuration file.
{
"AutomaticHttpsRedirect": true,
"Authentication": "UrlHash", // Type of authentication: UrlHash, JWT, RequestChoice, Disabled
"AuthenticationSessionLifetime": 10, // Lifetime of logged user session
"AuthenticationJwt": { // JWT configuration
"SecretKey": "{112AXXXX-XXXX-XXXX-XXXX-F98BC9BXXXX}",
"ValidateIssuerSigningKey": true,
"ValidateTokenLifetime": true,
"ValidateIssuer": true,
"ValidateAudience": true,
"ValidIssuer": "K2API",
"ValidAudience": "public"
},
"ASClient": { // AS server configuration
"ForwardASGeneralExceptions": false, // Forward general AS exceptions to API client
"BalancerConfig": {
"PeriodicCheckTimer": 1,
"Multipliers": {
"SystemCPUAvg": 1,
"SystemFreeMemory": -1,
"AppPoolSpandAvg": 1,
"AppNCLSessions": 1,
"AppAnonymousSessions": 1,
"AppSchedulerSessions": 1
}
},
"Servers": [
{
"ServerName": "127.0.0.1",
"Port": 55000
}
]
}
}
Selected important parameters:
Parameter |
Default value |
Meaning |
AutomaticHttpsRedirect |
true |
true – redirect traffic from HTTP to secure HTTPS |
Authentication |
RequestChoice |
Allowed authentication mode of API requests. Possible values: UrlHash – only the original HMAC hash JWT – only using a JWT token RequestChoice – both HMAC hash and JWT are allowed. They are distinguished by the form of the Authorization HTTP header (Bearer prefix – JWT token, without prefix – HMAC hash) Disabled – authentication is not required, for debugging purposes only! |
AuthenticationSessionLifetime |
10 |
Validity period of the user session after authorization of the first request, in minutes |
AuthenticationJwt |
|
Detailed configuration of JWT authentication |
ASClient. |
false |
true – all exceptions during request processing on the K2 AS side will be passed to the API client. False – only a general error without details is returned to the client. The details are stored in the log |
ASClient.BalancerConfig. |
1 |
Number of minutes for the interval of obtaining the status and load counters for the load balancer |
ASClient.BalancerConfig. Multipliers |
|
Weights (coefficients) of the individual performance counters for load balancer decisions. |
ASClient.Servers |
|
Array with a list of all application server instances (server + port) against which the API can run in load balancer mode. Without a load balancer, only one record is entered. |
API logging
The K2 API allows several modes and scopes of logging, from basic logging of exceptions only up to a log of the complete data of the incoming request and the complete response, which is useful mainly when debugging communication and troubleshooting integration with other systems.
File logs are created in the logs subdirectory of the API installation/working directory.
The required logging level is set in the appsettings.json configuration file in the NLog section.
Global logging level – the NLog.globalThreshold parameter allows you to set the maximum level of detail of the output to all logs. Possible values are:
Trace – detailed trace output with details of the complete request processing procedure
Debug – detailed debugging output about request processing
Info – basic information about the start and end of processing of each request
Warn – only warnings during request processing
Error – all errors during request processing
Fatal – only critical errors during request processing
Off – logging is completely disabled
The NLog.rules section contains rules for the individual logging collections. By default, the API works with 3 logging collections.
CommonLogger – for general logging output
RequestLogger – for recording complete requests and responses
stdOutMessages – for writing output to the standard output of the application
For each collection, you can specify whether it is enabled/disabled, what level of output detail it should write (the same possible values as the global level) and to which target (storage) it should write.
The NLog.targets section then defines the individual log storages and their rules. Typically, for file output, it specifies the file name and path, the format of an individual log line and, for example, rules for archiving/rotating logs
Basic principles of communication
Data format
Request and response bodies are in JSON format with UTF-8 encoding. Requests with a body (POST, PUT) must contain the Content-Type: application/json header. The exception are operations that return a file (e.g. report output in PDF or a document attached to a record) – these return the file content directly.
URL address structure
The URL specifies the service and the resource we want to work with, or the operation we want to run:
<server address>/<service>/<resource or operation>{?optional parameters}
- <server address> – the root address of the K2 API, e.g. https://demo.k2.cz/k2apiv2
- <service> – a specific K2 API service, e.g. data, meta, formation
- <resource or operation> – specification of the particular request, e.g. the class name of the data object and the primary key of the record
- {?optional parameters} – parameters specific to the given request, e.g. fields, orderBy, conditions, pageSize
Unlike the original API, the xml/ switch is no longer stated in the URL – the output is always JSON. Data objects are identified by the class name of the data module, e.g. TArticleDM for articles.
Response structure
All responses in JSON format have a uniform envelope. In addition to the data itself, it contains the processing status of the request, so the client always knows whether the request was successful and, if not, why it failed:
Property |
Meaning |
statusCode |
Processing status of the request, e.g. OK or ResourceNotFound. |
errorMessage |
Text description of the error; empty on success. |
errors |
List of individual errors; each has a text (message) and a reference to the place it relates to (reference). |
dbgMessages |
Debug messages in the same structure as errors. |
data |
The actual response data – a data object, a list of objects, a script result, etc. |
Data object in JSON
A K2 record (data object) is transferred as an object with a class name (className) and a list of field values (fieldValues), where each field has a name (name) and a value (value). The value of a link field is a nested data object; the value of an item field (e.g. units of measure of an article) is an array of data objects.
{
"className": "TArticleDM",
"fieldValues": [
{ "name": "Id", "value": 35 },
{ "name": "Abbr", "value": "TESTARTICLE" },
{ "name": "Name", "value": "Test Article" },
{ "name": "ArticleTypeId", "value": {
"className": "TTextDM",
"fieldValues": [
{ "name": "Id", "value": 1 },
{ "name": "Description", "value": "Article" }
] } }
]
}
When changing an existing record, the value of the Timestamp field loaded together with the record must also be sent back. As with the original API, K2 thus prevents overwriting changes made in the meantime by another user.
Overview of services
Service |
Address |
Purpose |
Data |
/data/… |
Reading lists and details of records (sequentially and by pages), filtering including saved filters, creating and changing records, running commands, uploading and downloading documents. |
Meta |
/meta/… |
Version information, list of data objects published for the K2 API, description of their fields, primary keys, commands and saved filters. |
Formation |
/formation/… |
Running scripts and reports – with output parameters returned, with an output file returned, or with direct processing of the HTTP request by the script. |
FormationDefinition |
/formationmeta/… |
Description of a script or report, including parameters and their default values. |
Authorization |
/token/…, /currentUser/… |
Obtaining and refreshing a JWT token, data about the logged-in contact person. |
System |
/system/… |
Checking the availability of the application server (ping) and other system operations. |
Web |
/web/… |
Operations for K2 web solutions and e-shops – web configuration, text pages, localized texts. |
Marketplace |
/marketplace/… |
Connection to a marketplace (Alza) – receiving, confirming, extending and cancelling orders. |
CRM |
/crm/… |
Support for CRM applications (synchronization of emails, calendar, etc.) |
Pbx |
/pbx/… |
Receiving events from the telephone exchange into the call history. |
A detailed description of the individual operations is given in the following chapters and in the OpenAPI documentation of the instance.
Request example
- Loading a list of articles with selected fields, sorted by name, 10 records at a time, with texts in Czech:
- GET https://demo.k2.cz/k2apiv2/data/TArticleDM?fields=Id,Abbr,Name,ArticleTypeId.Name&orderBy=Name&pageSize=10
- Authorization: Bearer <access token>
- X-LangId: 5
- Accept: application/json
Sample response (shortened):
{
"statusCode": "OK",
"errorMessage": "",
"data": {
"items": [
{ "className": "TArticleDM",
"fieldValues": [
{ "name": "Id", "value": 35 },
{ "name": "Abbr", "value": "TESTARTICLE" },
{ "name": "Name", "value": "Test Article" },
…
] }
],
"itemsPerPage": 10,
"firstPageUrl": "…",
"nextPageUrl": "…",
"previousPageUrl": "…",
"lastPageUrl": "…"
}
}
You get the next page of the result by calling the address from the nextPageUrl property. If you need to go directly to a specific page or know the total number of records, use the GET /data/paged/{classname} operation with the pageNumber and includeTotalRecordsCount parameters. In this case, filtering and sorting is possible only by physical (not calculated) fields.
Authentication
Each request to the K2 API must carry information about the K2 user under whose identity it is to be processed. This user determines which data and functions the request has access to – the same access rights apply as when working in K2.
Data about the logged-in contact person is returned by the GET /currentUser/ContactPerson operation.
K2 API v2 supports two authentication methods. Which of them are allowed is set in the configuration of each K2 API instance. If both are allowed, the K2 API distinguishes them by the value of the Authorization header – if it starts with the word Bearer, it is a JWT token; otherwise, it is an HMAC signature.
JWT token
The new, recommended method. The client first logs in with a user name and password and obtains a pair of tokens:
- access token – sent in every request, has limited validity,
- refresh token – used to obtain a new access token after its validity expires, without entering the password again.
Login:
POST /token/login
Content-Type: application/json
{ "username": "user1", "password": "pass" }
Response:
{
"accessToken": "xxxxx.yyyyy.zzzzz",
"accessTokenValidity": "2000-01-01T00:30:00.000",
"refreshToken": "a50d4492f751c28b2",
"refreshTokenValidity": "2000-02-01T00:30:00.000"
}
The access token is then sent in every request in the header:
Authorization: Bearer <access token>
After the access token expires, the client calls POST /token/refresh, sending the refresh token (as a JSON string) in its body, and obtains a new pair of tokens. The accessTokenValidity and refreshTokenValidity properties state until when the tokens are valid, so the client can schedule the refresh in advance.
For web solutions, the web identification (shopRID) can also be passed at login.
The advantage of JWT is that the client does not have to sign each request separately. This method is supported by most libraries and development tools, including the OpenAPI documentation itself, in which you can enter the token and try out calls right away.
HMAC request signature
The method known from the original K2 API, which makes it possible to keep the existing authentication mechanism for existing integrations. In each request, the client states the Authorization header in the form {UserName}:{HMACHash}. The hash is calculated using the HMAC MD5 algorithm: the key is the user's password and the hashed message is the entire URL of the request in unencoded form (without URL encoding of special characters) converted to upper case. The result is converted to text using Base64 encoding. The password is thus not transmitted over the network.
Example of the calculation 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 calculation in a K2 script:
function CalcHMAC(ASrc, APassword: string): string;
begin
if not CreateHMacMD5HashBase64(AnsiUpperCase(HTTPDecode(ASrc)), APassword, Result) then
Result:= ' ';
end;
Examples in other languages (Java, PHP) are given in the OpenAPI documentation.
Alternatively, the hash can also be passed directly in the URL 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 again appended to the end of this text.
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;
Security: Always transmit tokens and the HMAC signature only over HTTPS. Tokens must be protected in the same way as a password – anyone who obtains them can act as the given user until they expire.
Request context information
In K2 API v2, context information can be attached to each request, which modifies the user's settings for the duration of the request processing – similarly to when a user switches the company, language or warehouse in K2. Context information is passed as HTTP headers:
Header |
Meaning |
Example |
X-LangId |
Language ID. It affects the values of translated fields, etc. |
5 |
X-CompanyId |
ID of the own company within which the request is processed. |
3 |
X-InfoWarehouseId |
ID of the information warehouse. It affects the values of calculated fields, e.g. the available quantity of an article. |
257 |
X-BusinessYear |
Business year (period) in which new records are created. |
2022 |
X-CurrencyCode |
ISO code of the currency in which prices are to be returned. |
EUR |
X-PartnerId |
ID of the current partner. Required by some e-shop operations. |
66 |
X-ShopRid |
RID of the current e-shop / web. Required by operations of the Web service. |
4569845202946 |
Example – loading articles in English with availability in the warehouse with ID 257:
GET https://demo.k2.cz/k2apiv2/data/TArticleDM?fields=Abbr,Name
Authorization: Bearer <access token>
X-LangId: 1
X-InfoWarehouseId: 257
If a context header is not stated in the request, the settings of the given K2 user are used.
Error handling
In the event of an error, K2 API v2 returns the corresponding HTTP status code and, in the response body, the same JSON envelope as on success, only with the error information filled in. The client application can thus reliably recognize and process errors automatically: it distinguishes the basic error type by the HTTP status code and the specific reason by the statusCode property, and it can display the text from errorMessage and errors to the user or write it to a log.
Example – the requested record does not exist (HTTP 404):
{
"statusCode": "ResourceNotFound",
"errorMessage": "The object with specified key was not found"
}
Compared to the original API, errors that previously ended with a general HTML page without further details (e.g. an incorrectly composed request body) are also returned in JSON format. In addition, the errors list makes it possible to return multiple errors at once – for example, all missing or incorrectly filled-in values when saving a record.
The most common HTTP status codes:
Code |
Meaning |
200 |
The request was processed successfully. |
201 |
The record was created (for some operations, e.g. Marketplace). |
400 |
Incorrectly composed request – e.g. invalid JSON, unknown field, incorrect condition. |
401 |
Authentication is missing or invalid (e.g. the access token has expired). |
403 |
The user does not have permission for the requested operation. |
404 |
The requested resource does not exist – e.g. an unknown data object, record, script or saved filter. |
500 |
Error during processing on the side of the K2 API or the application server. |
Possible statusCode values:
Code |
Meaning |
OK |
The request was processed successfully. |
BadRequest |
Incorrectly composed request – e.g. invalid JSON, unknown field, incorrect condition. |
NotAuthorized |
Authentication is missing or invalid (e.g. the access token has expired). |
ResourceNotFound |
The requested resource does not exist – e.g. an unknown data object, record, script or saved filter. |
GeneralError |
Error during processing on the side of the K2 API or the application server. |
ServiceUnavailable |
Temporary service error – for example, no running application server is available |
First steps
- Open the root address of the K2 API in a browser and verify that the home page with version information is displayed.
- Call GET /system/ping and verify that the K2 application server is available.
- Go to the documentation link (Swagger) and get familiar with the available services.
- Obtain a JWT token by calling POST /token/login and enter it in the documentation (Authorize button).
- Try simple data reading, e.g. the list of data objects published for the K2 API (GET /meta/objects) and the list of articles (GET /data/TArticleDM).
- Implement the calls in your application according to the OpenAPI specification, or generate the client automatically.