The Modelit Webserver Toolbox for Matlab makes it possible to deploy algorithms written in Matlab code as a webservice. Central to the toolbox is a servlet that runs in Apache Tomcat and which redirects incoming web-requests to Matlab callback functions. Using Apache Tomcat has advantage that it is a proven technology with a lot of features. However it introduces an extra component which causes extra complexity and makes the use of Matlab algorithms in Docker containers overly complicated. As a solution Modelit has extended the Webserver toolbox with an embedded server, based on the Java Sun HTTP server. This server runs inside Matlab and makes it possible for Matlab to directly send and receive HTTP messages.

In this example we make a simple application in Matlab that can receive HTTP requests by using the Embedded Matlab server from the Modelit webserver toolbox. This application can be used as a standalone server or as part of a Docker container.

Let's start with a simple function that we want to run as a service.

function output = algorithm(input)

This algorithm can be converted to a Matlab webservice by executing the following nine steps:

  1. Create a modelit.web.server.Server that can receive HTTP requests on a specific port.
  2. Define a callback that is executed when an HTTP request arrives.
  3. Start the server and make sure that the services stays active by running an eternal loop.
  4. Get the data from the (modelit.web.server.HttpExchange) event.
  5. Convert the data (e.g. JSON of XML) to a format that can be used by Matlab.
  6. Create the response by executing the algorithm.
  7. Convert the response to the required output format (e.g. JSON of XML).
  8. Set de HTTP headers (e.g. Content-Type).
  9. Send the response and HTTP statuscode to the client.

By following these nine step the following code is created:

% Create a server that listen to HTTP requests on port 8081
% Set the callback that has to be executed when an HTTP request arrives.
server = modelit.web.server.Server(8081, @callback);

% Start the webservice.
server.start();

% Start an eternal loop. In this way the application is not automatically closed when running in compiled form.
while true
  pause(5);
end

%______________________________________________________________________________________
function callback(event)
% The first argument contains the data the was sent via the HTTP request
input = event.getBody();

% Convert these data to a for Matlab readable format
input = jsondecode(input);

% Call the existing algorithm with these adjusted input arguments
output = algorithm(input);

% Convert the output to JSON
output = jsonencode(output);

% Set the MIME type
event.addResponseHeader('Content-Type', 'application/json');

% Return the output with Statuscode 200: OK
event.send(200, response);