Main Content

Call User-Defined Function with MATLAB REST Function Services

A MATLAB® REST function service enables you to evaluate your own MATLAB functions, classes, or scripts, on local or remote servers using JSON representation of MATLAB data types. You can use any HTTPS supported programming language such as Java®, Python®, C++, or .NET to develop client applications.

Create Service to Call mySqrt.m

This example shows how to configure your application to call a MATLAB function that calculates a square root. Do not directly call the MATLAB sqrt function. Instead, create this function, save it to a file named mySqrt.m, and add it to the MATLAB path:

function result = mySqrt(x)
    result = sqrt(x);

Create a service TestService to call mySqrt from your application.

myService = restFunctionService("TestService","mySqrt");

Start Service

Create a ClientRequestInfo object which contains the information your application needs to make RESTful calls.

info = myService.start
info = 
  ClientRequestInfo with properties:

           ClientAccessMode: local
                 RequestUrl: "https://localhost:9920/matlab/feval/v1/TestService"
        CertificateLocation: "C:\Users\myname\AppData\Roaming\MathWorks\restfcnconnector\publickey.pem"
    RESTPersonalAccessToken: "6tHdZuiIB3y8YaQmj7cCX1GNcl/cd+clpuaS7/TIJmE="

Set Up Call from Client Program

In your application, create a request using the POST method. Use the data from your ClientRequestInfo object to complete these arguments in the request:

  • URL — Set the URL value to the RequestUrl property with the function name appended. Do not include the .m file extension. For this example, the value is:

  • Add a mwRESTPersonalAccessToken header field — Set the value to the RESTPersonalAccessToken property.

  • Content-type header field — Set to application/json.

  • Path to certificate — Set to the CertificateLocation property value.

  • Message body — Create a JSON message body with the required arguments for the function:

    {   "rhs": [input-argument(s)],
        "nargout": number-of-output-arguments,
        "outputFormat": {
            "mode": "small",
            "nanType": "string"

    To call res = mySqrt(25) in this example, set the body to:

    {   "rhs": [25.0],
        "nargout": 1,
        "outputFormat": {
            "mode": "small",
            "nanType": "string"

Sample HTTP Request Code

Your request contains the URL, the mwRESTPersonalAccessToken header field, and the message body, and should look like this code:

POST /matlab/feval/v1/TestService/mySqrt HTTP/1.1
Host: localhost:9920
mwRESTPersonalAccessToken: VAAKeo/2MaCzb72rMv1TX0df/HbjSSL47kWy5B694BE=
Content-Type: application/json
Content-Length: 80

{"rhs":[25.0], "nargout":1, "outputFormat":{"mode":"small", "nanType":"string"}}

Set the path to the certificate using the POST method in your application. Refer to your application documentation for details about calling the POST method.

See Also


Related Topics