11/12/2024
How-to | Engineering | PLC | IO | API Client

Generate API client libraries from Engineering API

ctrlX PLC & IO Engineering API: An Overview (v5.2+)

From Engineering version 5.2 onwards, the OpenAPI specification includes improved schema definitions for polymorphic models (discriminator mappings, JobBase, and refined union types).

These changes make the spec more precise and significantly improve the quality of auto-generated API clients — especially regarding type-safety, polymorphic deserialization, and class hierarchies.

The recommended tool for generating API clients is openapi-generator, which supports more than 50 target languages and frameworks.


Step 1 — Download openapi-generator-cli

The generator is distributed as a single executable JAR file (requires Java 11 or later).

1. Go to the official Maven Central release page:

https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/

2. Navigate to the latest stable version folder (e.g. 7.x.x/).

3. Download the file named: openapi-generator-cli-<version>.jar

4. Rename it to openapi-generator-cli.jar for convenience.

> Tip: You can also use the npm wrapper if you have Node.js installed:

> npm install @openapitools/openapi-generator-cli -g


Step 2 — Locate the API-CodeGenerator folder in the installation

Inside your ctrlX PLC Engineering or ctrlX IO Engineering installation directory, navigate to: <InstallationPath>\Studio\Help\API-CodeGenerator\

This folder already contains:

- Ready-to-use batch files for client generation:

- Generate_Rexroth_PlcEng_APIClient.bat — generates a C# client for PLC Engineering

- Generate_Rexroth_IoEng_APIClient.bat — generates a C# client for IO Engineering

- The bundled OpenAPI specification file (`.json`) are available under <InstallationPath>\Studio\Help\OpenAPI

Step 3 — Copy the JAR into the API-CodeGenerator folder

Copy the downloaded openapi-generator-cli.jar into:<InstallationPath>\Studio\Help\API-CodeGenerator\

The batch files expect the JAR to be present in the same directory.

Step 4 — Generate the C# client

Open a command prompt, navigate to the API-CodeGenerator folder, and run the appropriate batch file:

For PLC Engineering: Generate_Rexroth_PlcEng_APIClient.bat

For IO Engineering: Generate_Rexroth_IoEng_APIClient.bat

The batch file executes a command equivalent to:

java -jar openapi-generator-cli.jar generate ^
  -g csharp ^
  -i "plc-engineering-api-v2.json" ^
  -o "<OutputFolder>" ^
  --additional-properties packageName=Rexroth.Api.PlcEngineering,targetFramework=net8.0 ^
  --model-name-mappings Path=LibraryFilePath,Task=ProjectTask

Note on model name mappings: The --model-name-mappings option renames certain generated classes to avoid conflicts with reserved names in the target language (e.g. PathLibraryFilePath, TaskProjectTask in C#).

After the script completes, the generated client source code will be available in the configured output folder.

Step 5 — Generate a client for other languages

openapi-generator supports many target languages. To generate a client for a different language or framework, run the generator manually from the API-CodeGenerator folder.

List all supported generators: java -jar openapi-generator-cli.jar list

Example: Generate a Java client:

java -jar openapi-generator-cli.jar generate ^
  -g java^
  -i "plc-engineering-api-v2.json" ^
  -o ".\output\java-client" ^
  --additional-properties packageName=rexroth_plcengineering

Example: Generate a TypeScript (angular) client:

java -jar openapi-generator-cli.jar generate ^
  -g typescript-angular^
  -i "plc-engineering-api-v2.json" ^
  -o ".\output\typescript-client"

Replace -g with the desired generator name from the list output.

What changed in v5.2 — relevant for client generation

Starting with version 5.2 both OpenAPI specifications were updated to improve client generation compatibility.

The changes follow the same patterns in both products but differ in scope because the two APIs serve different use cases.

ctrlX PLC Engineering

1. Job schema
   Change:  Refactored to a pure discriminator + oneOf union wrapper around JobBase (29 job types).
   Effect:  Clean polymorphic class hierarchy. Resolves NPE crash in some C# generators caused
            by mixed allOf / properties / discriminator composition.

2. JobBase
   Change:  Introduced as explicit shared base type for all job variants.
   Effect:  Common job properties (id, state, progress, jobResultInfo) now appear in a proper
            base class instead of being repeated per job type.

3. DevicePatchElements / DevicePatchResponseElements
   Change:  Changed from untagged anyOf to anyOf + discriminator + mapping.
            Request variants: LibraryParameter, DisableDevice, Device.
            Response variants: Library, Device.
   Effect:  Generator can resolve concrete types correctly; no ambiguous union models.

4. DevicesElements, DevicesRootElements, PousElements, PousRootElements
   Change:  Aligned to anyOf + discriminator pattern.
   Effect:  Consistent polymorphic handling across all element union types.

5. Enum corrections
   Change:  BuildJob action value corrected: "GenerateCodeJob" -> "GenerateCode".
            busType casing normalized to "Ethercat".
   Effect:  Enum constants in generated code now match the values the server actually accepts.

ctrlX IO Engineering

1. Job schema
   Change:  Refactored to a pure discriminator + anyOf union wrapper around JobBase (21 job types).
   Effect:  Clean polymorphic class hierarchy for all IO Engineering job variants.

2. JobBase
   Change:  Introduced as explicit shared base type for all job variants.
   Effect:  Common job properties (id, state, progress, jobResultInfo) appear in a single
            base class instead of being repeated per job type.

3. New IO-specific jobs
   Change:  Added ExportEthercatConfigJob, ScanAndMergeDevicesJob, TransferFieldbusConfigJob
            to the Job discriminator mapping.
   Effect:  New concrete job classes generated; existing job models unaffected.

4. DevicesPatchElements
   Change:  New schema with anyOf + discriminator + mapping.
            Variants: DevicePlug, DeviceUnplug, DisableDevice.
   Effect:  Generator produces properly typed PATCH request models for
            plug / unplug / disable operations.

5. DevicesElements, DevicesRootElements
   Change:  Aligned to anyOf + discriminator pattern (currently maps Device).
   Effect:  Consistent polymorphic handling; extensible for future device types.

Compatibility note

REST wire compatibility: The JSON request/response payloads on the wire are backward compatible for both APIs. Existing clients built against older versions continue to work at runtime. However, regenerating your client against the new spec may produce different type names or class hierarchies, which may require minor code adjustments in consumer code.


==============================================================================

ctrlX PLC & IO Engineering API: An Overview (v4.6 and Earlier)

This blog will show you how to generate API client libraries. API client libraries is a code or an app that can access the provided REST services. Client code generators are used to create such API Client Libraries. Few well known client code generators are Swagger Codegen CLIAutoRestNSwag, and OpenAPI Generator. These tools  require NPM or the Java Runtime Environment to be installed on the developers machine. Alternative Java SDK implementations such as the OpenJDK works fine with this extension. 

The Swagger Codegen CLI and OpenAPI Generator are distributed as JAR files and are downloaded on demand but requires the Java SDK to be installed on the machine. AutoRest is installed on-demand via NPM as a global tool and uses the latest available version.

NSwagStudio is stand alone UI tool for editing a .nswag specification file for generating code. This tool is optional to install and official installation instructions are available on the NSwag Wiki on Github. If NSwagStudio is not installed on the machine then the Visual Studio Extension will install the NSwag CLI via NPM as a global tool using the latest available version.

For CSharp Environment

Prerequisites

  • Latest ctrlX WORKS with PLC and IO Engineering is installed

  • Visual Studio is installed. (As an alternative Visual Studio Code can be used with extension C# for Visual Studio Code)

  • Swagger Codegen CLI is downloaded. For Windows users, you can use Invoke-WebRequest in PowerShell (3.0+) to download swagger-codegen-cli v3.0.33, e.g.

    Invoke-WebRequest -OutFile swagger-codegen-cli.jar https://repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/3.0.33/swagger-codegen-cli-3.0.33.jar
  • If you're looking for the latest stable Swagger Codegen CLI version, you can grab it directly from Maven.org (search for swagger-codegen-cli)

  • Swagger Codegen is a Java app, so you must have Java Runtime Environment installed. Additionally JAVA_HOME environment variable, should point to java.exe path

Generate API client libraries using Swagger Codegen CLI

CSharp client library for PLC Engineering

  • Open installed ctrlX WORKS directory and navigate to → Studio\Help\API-CodeGenerator. (For ctrlX WORKS WRK-V-0112.4 version and below,  folder 'API-CodeGenerator' is not available, you can download the files from attachment)

  • Copy the contents of API-CodeGenerator and downloaded swagger-codegen-cli.jar to a folder inside your work directory (e.g. D:\CodeGen) as shown below:

  • To generate PLC Engineering API client library, run 'Generate_Rexroth_PlcEng_APIClient_CSharp.bat'

  • After successful generation, you will see a folder named 'Rexroth_PlcEng_APIClient_CSharp' as shown below:

  • Navigate to 'Rexroth_PlcEng_APIClient_CSharp' directory and run 'build.bat'. This downloads required packages and DLLs are available under bin folder as shown below. (The Codegen also creates a README file with all the information for running and building the API)

 

 

 

 

 

 

 

 

 

  • Open 'Rexroth.Api.PlcEngineering.sln', project will be opened in Visual Studio

  • In Visual Studio, navigate and open Edit → Find and Replace → Replace in Files

  • In the editor, enter base(elementType, name, id, children) in find textbox  and enter base(elementType, name) in replace textbox and click on Replace All as shown below. (This step is required to correct few errors caused by Swagger Codegen CLI for CSharp language. Same errors might not occur in different language(s) or with different code generator(s))

  • Again enter base(jobType, id, state, progress, jobResultInfo) in find textbox  and enter base(jobType, jobResultInfo) in replace textbox and click on Replace All as shown below. (This step is required to correct few errors caused by Swagger Codegen CLI for CSharp language. Same errors might not occur in different language(s) or with different code generator(s))

  • Only for ctrlX WORKS WRK-V-0112.4 version and below, additional changes are required to the generated file (Rexroth_PlcEng_APIClient_CSharp\src\Rexroth.Api.PlcEngineering\Model\RecipeManager.cs). Changes should match to below shown images (see line number in the below image as reference):

    Add missing Assignment
    Select Assignment from the enum
    Select Assignment from the enum
  • In Visual Studio, navigate and click on Build → Rebuild Solution. (Rebuild Solution should be successful, If you still have build error, ask for help in the comment section)

  • After successful build,  DLL's are available (under the `bin` folder) in the C# project as shown below:

  • For more information/examples on available API functions, navigate to menu Help → API-reference in ctrlX PLC Engineering

CSharp client library for IO Engineering

  • Run 'Generate_Rexroth_IoEng_APIClient_CSharp.bat' and follow steps similar to client library generation for PLC Engineering

  • For more information/examples on available API functions, navigate to menu Help → API-reference in ctrlX IO Engineering

Java client library for PLC and IO Engineering

  • Run 'Generate_Rexroth_PlcEng_APIClient_Java.bat' and 'Generate_Rexroth_IoEng_APIClient_Java.bat'

  • To build and install the generated API client, follow the README file inside the created 'Rexroth_PlcEng_APIClient_Java' and 'Rexroth_IoEng_APIClient_Java' folder

Client library for other languages

  • Swagger Codegen CLI also supports many other languages/frameworks. For more information visit there GitHub

Generate API client libraries using openapi-generator-cli

  • Alternatively, client libraries can also be generated using openapi-generator-cli. Client libraries can be generated in a similar way as described for swagger-codegen-cli.

  • Openapi generator references latest version of 'RestSharp', which is already 'Strong-Named'. This helps the generated client libraries to be used in strong named environment.

  • If you're looking for the latest stable version, you can grab it directly from Maven.org (JAR location) (Java 11 runtime at a minimum).

  • For Windows users, you will need to install wget or you can use Invoke-WebRequest in PowerShell (3.0+), e.g.

    Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.9.0/openapi-generator-cli-7.9.0.jar
  • See online for more CLI Installation options

  • After successful download, copy the 'openapi-generator-cli.jar' to the same folder where PLC & IO api json files are available.

  • Create a batch file and add below code and run the created batch file.

    call java -jar openapi-generator-cli.jar generate -g csharp -i plc-engineering-api-client-v2.json -o Rexroth_PlcEng_APIClient_CSharp --additional-properties packageName=Rexroth.Api.PlcEngineering,targetFramework=net8.0
  • In generated code, 'base' class needs to be replaced using VisualStudio, follow the same process as shown for swagger-codegen-cli.

  • Additionally for error CS0104: 'Task' is an ambiguous reference between 'Rexroth.Api.PlcEngineering.Model.Task' and 'System.Threading.Tasks.Task', use the reference of 'System.Threading.Tasks.Task'

  • Additionally for error CS0104: 'Path' is an ambiguous reference between 'Rexroth.Api.PlcEngineering.Model.Path' and 'System.IO.Path', use the reference of 'System.IO.Path'

  • In Visual Studio, navigate and click on Build → Rebuild Solution. (Rebuild Solution should be successful, If you still have build error, ask for help in the comment section)

CSharp console application for PLC Engineering

  • In Visual Studio, navigate and click on File → New → Project. Follow the instructions in the dialog and Create an Console App (.NET Framework)

  • Add generated 'Rexroth.Api.PlcEngineering.dll' reference to the created console application as shown below:

  • Open Program.cs file and replace existing code with below code:

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Threading;
    using Rexroth.Api.PlcEngineering.Api;
    using Rexroth.Api.PlcEngineering.Client;
    using Rexroth.Api.PlcEngineering.Model;
     
    namespace ConsoleApp
    {
      public class Program
      {
        static void Main(string[] args)
        {
          try
          {
            Console.WriteLine("Start PLC Engineering and create a new project");
            //Latest installed or latest used ctrlX WORKS instance will be used to start engineering
            //For ctrlX WORKS version WRK-V-0112.4 and below, protocol 'rexrothstudio://plc/?' to start engineering is not supported, use
            //Process.Start(@"path to engineering exe") and open existing project using 'ProjectJob' in API
            Process.Start("rexrothstudio://plc/?hostname=localhost&newproject=d:\\ctrlX\\Projects");
     
            //Wait till Engineering is ready for input
            Thread.Sleep(20000);
     
            //Set base path to the actual URL with port
            Configuration config = new Configuration {BasePath = "http://localhost:9002/plc/engineering/api/v2"};
     
            //Create new device api instance with the actual URL
            DevicesApi devicesApi = new DevicesApi(config);
     
            //Create a device with mandatory parameters
            Device ctrlXCoreDevice = new Device(name: "ctrlXCoreDevice", elementType: "Device");
            DeviceInfo deviceInfo = new DeviceInfo(deviceType: 4096, id: "1001 0080");
            ctrlXCoreDevice.DeviceInfo = deviceInfo;
     
            BaseElement addedDevice = devicesApi.AddDevices(ctrlXCoreDevice);
            Console.WriteLine($"Device added: {addedDevice.Name}");
     
            //Create and add task configuration
            TaskConfig taskConfigObj = new TaskConfig(elementType: "TaskConfig", name: "Task Configuration");
            devicesApi.AddDevicesByPath(taskConfigObj, "/ctrlXCoreDevice/PLC Logic/Application");
            Console.WriteLine("Task Configuration added");
     
            //Create and add a task
            Task taskObj = new Task(elementType: "Task", name: "MyTask")
            {
              Priority = "30",
              TaskGroup = "IEC-Tasks",
              Type = new TaskType("cyclic", "t#20ms"),
              Watchdog = new TaskWatchdog(false, "", "1"),
              PouCalls = new List<TaskPouCall>()
            {
              new TaskPouCall("Prg1", ""),
              new TaskPouCall("Prg2", "")
            }
            };
            devicesApi.AddDevicesByPath(taskObj, "/ctrlXCoreDevice/PLC Logic/Application/task-config");
            Console.WriteLine("Task added");
     
            Console.ReadLine();
          }
          catch (Exception e)
          {
            Console.WriteLine(e);
            throw;
          }
        }
      }
    }
  • After successful Build, Start the console app. This will start the ctrlX PLC Engineering with a new project and a Device, Task Configuration, Task will be added to the project

3
API-CodeGenerator(WRK-V-0112).zip
30.25KB
Types
How-to
Products
Controls
IO
PLC