Main Content

Test Web Request Handlers

You can use the testing interface in the Production Server Compiler app to test web request handlers for deployment to MATLAB® Production Server™. Each web request handler consists of:

  • A MATLAB function that receives a request and returns a response.

  • URL routes to that function, specified in a JSON file that is on the server, a JSON file packaged into the deployable archive containing the function, or files in both locations.

To set up the testing interface for web request handlers, you configure access to the URL routes. To configure access to the routes files, either set environment variables that specify the path to the routes files or place the routes files in the MATLAB preferences directory. When you start the testing interface, it searches for the environment variables for the routes files first. If the environment variables are not set, then the testing interface searches the MATLAB preferences directory for the routes files. After you configure access to the routes files, you can test the MATLAB functions for web request handlers.

For more information about defining web request handlers, see Handle Custom Routes and Payloads in HTTP Requests (MATLAB Production Server).

Set Environment Variable for Routes Files

To specify instance-level routes, which apply across all archives on the server instance, set the environment variable PRODSERVER_ROUTES_FILE to a value that contains the path to the routes file (for example, instance/routes.json). You can set the environment variable at the MATLAB prompt using setenv or at the system command prompt using syntax specific to your operating system.

setenv('PRODSERVER_ROUTES_FILE','instance/routes.json');

To specify archive-level routes, which apply only to a specific archive, set the environment variable PRODSERVER_ROUTES_FILE_LOCAL to a value that contains the path to the routes file (for example, archive/routes_local.json).

setenv('PRODSERVER_ROUTES_FILE_LOCAL','archive/routes_local.json');

If you specify both instance-level and archive-level environment variables, then any instance-level matches take precedence over archive-level matches. If you specify an instance-level or archive-level routes file in both an environment variable and in the MATLAB preferences folder, routes in the environment variable file take precedence.

Before you test, keep these points in mind:

  • If you specify a relative path to the routes files, from the MATLAB prompt, navigate to the folder that contains the routes file before you start the test server in the Production Server Compiler app.

  • If you update the contents or location of a routes file that is already in use, for your changes to take effect, restart the test server in the Production Server Compiler app.

  • To turn off testing for web request handlers, set the environment variables to empty values.

Use MATLAB Preferences Folder for Routes Files

As an alternative to configuring access to the routes file, you can copy the files to the MATLAB preferences folder. This configuration persists across MATLAB restarts. You must name the routes files as follows:

  • Instance-level routes file — prodserver_routes.json.

  • Archive-level routes file — prodserver_routes_local.json.

To locate your preferences folder, type prefdir at the MATLAB prompt.

  • If you specify both instance-level and archive-level environment variables, then any instance-level matches take precedence over archive-level matches.

  • If you specify an instance-level or archive-level routes file in both an environment variable and in the MATLAB preferences folder, routes in the environment variable file take precedence.

  • If you update the contents or location of a routes file that is already in use, for your changes to take effect, restart the test server in the Production Server Compiler app.

  • To turn off testing for web request handlers, rename or move the routes files from the preferences folder and restart the test server.

End-to-End Setup to Test Web Request Handlers

This example shows how to test web request handler functions in the PSC app

Create Routes File

Using a text editor, create a routes JSON file to map client requests to the MATLAB web handler functions. Save the file as routes.json.

This routes file maps client request URLs containing the path segment /greet/ to a hellowh MATLAB function in the deployable archive whdemo. For example, http://localhost:9910/greet/rest/of/path.

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

If you are testing an archive-level routes JSON file, then the component field specifying the archive name is optional. This routes file maps client request URLs containing the deployable archive name and the path segment /greet/ to a hellowh MATLAB function. For example, http://localhost:9910/archive_name/greet/rest/of/path.

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

Configure Access to Routes File

From the MATLAB prompt, set the environment variable PRODSERVER_ROUTES_FILE to specify the path to the routes file.

setenv('PRODSERVER_ROUTES_FILE', 'J:\routes.json');

If you are testing an archive-level routes JSON file, then set the PRODSERVER_ROUTES_FILE_LOCAL environment variable instead.

setenv('PRODSERVER_ROUTES_FILE_LOCAL', 'J:\routes_local.json');

Write MATLAB Function for Web Request Handler

To work as a web request handler, a MATLAB function must accept one scalar structure array as input, and return one scalar structure array as output.

The following code shows a MATLAB function, hellowh.m, that uses the input argument structure request, whose fields provide information about the request headers and body. The function also constructs and returns the 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

Prepare for Testing

  1. Open the Production Server Compiler app by typing the following at the MATLAB command prompt:

    productionServerCompiler

  2. In the Type section of the toolstrip, select Deployable Archive (.ctf).

  3. Specify the MATLAB functions to deploy.

    1. In the Exported Functions section of the toolstrip, click the plus button.

    2. Using the file explorer, locate and select the hellowh.m file.

  4. Set the Archive information to whdemo.

  5. Click Test Client. The app switches to the Test tab.

  6. Click Start to start your test. The Server Log section displays errors, if any.

Call Web Handler MATLAB Function

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/greet/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

The output of the disp commands in the web handler function display in the MATLAB command window.

If you are testing an archive-level route, then after the port number, the request must include the archive name with a slash before and after it.

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

Examine Data

  1. Switch back to the Production Server Compiler app.

  2. In the testing interface, under MATLAB Execution Requests, click the completed message in the app to see the values exchanged between the client and MATLAB.

    Production Server Compiler app testing interface displaying input and output of web request handler function.

  3. Click Input to view data passed into MATLAB.

  4. Click Output to view data returned to the client.

After you are satisfied with your testing, you can package the MATLAB function and deploy it to the server.

Note

The Production Server Compiler app supports testing but not packaging of archive-level routes. If you test routes defined in an archive-level routes JSON file and then build the archive, the routes file is not included in the archive and the routes do not work. To package archive-level routes, use the mcc command.

For more information about creating deployable archives, see Create Deployable Archive for MATLAB Production Server.

Related Topics