Main Content

Handle Custom Routes and Payloads in HTTP Requests

Web request handlers for MATLAB® Production Server™ provide flexible client-server communication.

  • Client programmers can send custom HTTP headers and payloads in RESTful requests to the server.

  • Server administrators can provide flexible mapping of the request URLs to deployed MATLAB functions.

  • Server administrators can provide static file serving.

  • MATLAB programmers can return custom HTTP headers, HTTP status codes, HTTP status messages, and payloads in functions deployed to MATLAB Production Server.

To use web request handlers, you write the MATLAB function that you deploy to the server in a specific way and specify custom URL routes in a JSON file on the server.

Write MATLAB Function for Web Request Handler

To work as a web request handler, the MATLAB function that you deploy to the server must accept one input argument that is a scalar structure array, and return one output argument that is a scalar structure array.

The structure in the function input argument provides information about the client request. Clients can send custom HTTP headers and custom payloads. There are no data format restrictions on the payload that the deployed function can accept. For example, the function can accept raw data in binary or ASCII formats, CSV data, or JSON data that is not in the schema specified by the MATLAB Production Server RESTful API. Clients can also use the Transfer-Encoding: chunked header to send data in chunks. In chunked transfer encoding, though the server receives payload in chunks, the input structure receives payload data in entirety.

The structure in the function input argument contains the following fields:

Field NameData TypeDimensionsDescription
ApiVersiondouble1 x 3Version of the input structure schema in the format <major> <minor> <fix>
Bodyuint81 x NRequest payload
HeaderscellN x 2

HTTP request headers

Each element in the cell array represents a header. Each element is a key-value pair, where the key is of type char and the value can be of type char or double.

HttpVersiondouble1 x 2HTTP version in the format <major> <minor>
Methodchar1 x NHTTP request method
Pathchar1 x NPath of request URL

Since the deployed MATLAB function can accept custom headers and payloads in RESTful requests, you can vary the behavior of the MATLAB function depending on the request header data. You can use the structure in the function output argument to return a response with custom HTTP headers and payload. Server processing errors, if any, override any custom HTTP headers that you might set. If a MATLAB error occurs, the server returns an HTTP 500 Internal Server Error response. All fields in the structure are optional.

The structure in the output argument can contain the following fields:

Field NameData TypeDimensionsDescription
ApiVersiondouble1 x 3Version of the output structure schema in the format <major> <minor> <fix>
Bodyuint81 x NResponse payload
HeaderscellN x 2

HTTP response headers

Each element in the cell array represents a header. Each element is a key-value pair, where the key is of type char and the value can be of type char or double.

HttpCodedouble1 x 1HTTP status code
HttpMessagechar1 x NHTTP status message

Configure Server for URL Routes

Custom URL routes allow the server to map the path in request URLs to any deployable archive and MATLAB function deployed on the server.

To specify the mapping of a request URL to a deployed MATLAB function, you use a JSON file present on the server. The default name of the file is routes.json and its default location is in the $MPS_INSTALL/config directory. You can change the file name and its location by changing the value of the --routes-file property in the main_config server configuration file. You must restart the server after making any updates to routes.json.

When the server starts, it tries to read the routes.json file. If the file does not exist or contains errors, the server does not start, and writes an error message to the main.log file present in the directory that the log-root property specifies.

The default routes.json contains a version field with a value of 1.0.0, and an empty pathmap field. version specifies the schema version of the file. You do not need to change its value. To allow custom routes, edit the file to specify mapping rules in the pathmap array. In the pathmap array, you can specify multiple objects, where each object corresponds to a URL route.

Following is the schema of routes.json.

{
  "version": "1.0.0",
   "pathmap": [
       {
           "match": "<regular_expression>",
           "webhandler": {
               "component": "<name_of_deployable_archive>",
               "function": "<name_of_deployed_function>"
           }
       },
	{
           "match": "<regular_expression>",
           "webhandler": {
               "component": "<name_of_deployable_archive>",
               "function": "<name_of_deployed_function>"
           }
       }
    ]
}

To specify a URL mapping rule, use the match and webhandler fields from the pathmap array.

  • In the match field, specify a regular expression that uses ECMAScript grammar to match the path in a request URL.

    • If the request URL matches multiple regular expressions in the match field, the first match starting from the beginning of the file is selected.

    • The regular expression patterns are considered a match if any substring of the request URL is a match. For example, the pattern a/b matches a/b, /a/b, and /x/a/b/y. However, you can use the regular expression anchors, ^ and $, to match positions before or after specific characters. For example, the pattern ^a/b$ only matches a/b.

    • You can specify regular expressions that match query parameters in the request URL. However, asynchronous request execution using the MATLAB Production Server RESTful API is not supported. Request execution is synchronous. For more information about the MATLAB Production Server RESTful API, see RESTful API for MATLAB Function Execution.

  • In the webhandler field, use the component field to specify the name of the deployable archive and the function field to specify the name of the deployed function for the request URL to execute.

End-to-End Setup for Web Request Handler

This example assumes you have a server instance running at the default host and port, localhost:9910. For information on starting a server, see Start Server Instance Using Command Line.

  1. Write a MATLAB function for the web request handler.

    The following code shows a MATLAB function that uses an input argument structure request, whose fields provide information about the request headers and body. The function also constructs and returns a structure response, whose fields contain a success HTTP code and status message, custom headers, and a message body.

    function response = hellowh(request)
        disp(request);
        disp('request.Headers:');
        disp(request.Headers);
        bodyText = char(request.Body);
        disp('request.Body:');
        if length(bodyText) > 100
            disp(bodyText(1:100));
            disp('...');
        else
            disp(bodyText);
        end
    
        response = struct('ApiVersion', [1 0 0], ...
                          'HttpCode', 200, ...
                          'HttpMessage', 'OK', ...
                          'Headers', {{ ...
                            'Server' 'WebFunctionTest/1'; ...
                            'X-MyHeader' 'foobar'; ...
                            'X-Request-Body-Len' sprintf('%d', length(request.Body)); ...
                            'Content-Type' 'text/plain'; ...
                          }},...
                          'Body', uint8('hello, world'));
       
        disp(response);
        disp('response.Headers:');
        disp(response.Headers);
    end
    
  2. Package the function into a deployable archive.

    The following command compiles the hellowh.m function into a deployable archive, whdemo.ctf. For other ways to create deployable archives, see Create Deployable Archive for MATLAB Production Server.

    mcc -v -U -W 'CTF:whdemo' hellowh.m

  3. Deploy the archive, whdemo, to the server. For more information, see Deploy Archive to MATLAB Production Server.

  4. Edit the routes.json file on the server to map a client request to the deployed function. Restart the server instance for the changes to take effect. See mps-restart.

    The following file maps any client request that contains MyDemo in the request URL to the hellowh function in the whdemo archive deployed to the server.

    {
      "version": "1.0.0",
        "pathmap": [
            {
                "match": "^/MyDemo/.*",
                "webhandler": {
                    "component": "whdemo",
                    "function": "hellowh"
                }
            }     
        ]
    }
    

  5. Use a client of your choice to invoke the deployed function.

    The following command uses cURL to invoke the deployed function from the system command line.

    curl -v http://localhost:9910/MyDemo/this/could/be/any/path?param=YES

You see the following output at the system command line:

*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 9910 (#0)
> GET /MyDemo/this/could/be/any/path?param=YES HTTP/1.1
> Host: localhost:9910
> User-Agent: curl/7.55.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Server: WebFunctionTest/1
< X-MyHeader: foobar
< X-Request-Body-Len: 0
< Content-Type: text/plain
< Content-Length: 12
< Connection: Keep-Alive
<
hello, world* Connection #0 to host localhost left intact

See Also

Related Topics