Call MATLAB Functions from Python Using REST
R2026bA MATLAB® REST function service enables you to evaluate your own MATLAB functions, classes, or scripts on local or remote servers. Using Python®, you can call functions in a service, passing input data and receiving output data in native Python data types. The data passes synchronously between the Python client application and the MATLAB service using the HTTPS request-response model.
This example shows how to create a Python client application that calls MATLAB functions in a REST function service. To run this example, you must have a Python version compatible with your MATLAB release installed in your Python environment. For supported version information, see Versions of Python Compatible with MATLAB Products by Release.
Start MATLAB REST Function Service
In MATLAB, create a RESTFunctionService object containing the
functions you want to call from your Python client application. Then start the service.
To create a sample REST function service in MATLAB, copy the following MATLAB function files to a location on your MATLAB search path:
Create a REST function service named myService and start the
service. The returned ClientRequestInfo object contains information that your Python client application needs to send HTTPS requests to the MATLAB functions.
service = restFunctionService("myService",["mySqrt","myUnique","myMean"]); clientInfo = start(service)
clientInfo =
ClientRequestInfo with properties:
ClientAccessMode: local
RequestUrl: "https://localhost:9920/matlab/feval/v1/myService"
RESTPersonalAccessToken: "AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA="
CertificateLocation: "C:\Users\user\AppData\Roaming\MathWorks\restfcnconnector\publickey.pem"For more details on creating a MATLAB REST function service, see Create MATLAB REST Function Services.
Create Python Client
Install the Python Client for MATLAB REST Function Service from the Python Package Index (PyPI) by running this command from your operating system prompt.
python -m pip install matlab-restfcnservice-clientThen, create a Python client application to call the MATLAB functions. Copy this sample Python client application into a file named
my_client.py.
my_client.py |
|---|
|
The following sections explain the Python client code in detail.
Import Required Software
The following code imports the matlab package and
MWHttpClient class into your application.
import matlab
from matlab.rest_function_service.client import MWHttpClient
Create Client Interface
The following code creates the client interface using the required input
arguments for the MWHttpClient class.
url = "https://localhost:9920/matlab/feval/v1"
token = "AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA="
cert = r"C:\Users\user\AppData\Roaming\MathWorks\restfcnconnector\publickey.pem"
client = MWHttpClient(
base_url=url,
rest_personal_access_token=token,
certificate=cert)
Replace the argument values with the corresponding property values of the
returned ClientRequestInfo object:
url— Base URL of the MATLAB function service. Replace with theRequestUrlproperty value, omitting the service name. For example, ifRequestUrlis"https://localhost:9920/matlab/feval/v1/myService", specifyurlas"https://localhost:9920/matlab/feval/v1".token— Personal access token required to authenticate client requests. Replace with theRESTPersonalAccessTokenproperty value.cert— Path to the PEM certificate required to authenticate client requests. Replace with theCertificateLocationproperty value.
Use Client Interface to Call MATLAB Functions
The following code shows how to call the MATLAB functions using the syntax response =
client.serviceName.functionName(*args, **kwargs).
roots = client.myService.mySqrt(matlab.double([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
print(f"Square roots: {roots}")
uniques = client.myService.myUnique(["A", "B", "A", "C", "C", "A", "D"])
print(f"Unique strings: {uniques}")
user_dict = {"Name": "John Doe", "Billing": matlab.double([127, 180, 77, 65, 108])}
name, mean_bill = client.myService.myMean(user_dict, nargout=2)
print(f"Mean bill for {name}: {mean_bill}")For more details on this syntax, see matlab.rest_function_service.client.MWHttpClient. When making
requests using the Python client, keep these points in mind:
Wrap numeric arrays in the appropriate MATLAB data type, such as
matlab.double. You do not need to wrap string arrays in any data type.To return multiple output arguments, use the
nargoutkeyword argument to specify how many outputs the client expects to receive.The MATLAB REST function service does not support all Python data types. For a list of supported data types, see Data Type Conversions Between MATLAB REST Function Services and Python.
Run Python Client
Run the Python client application using your preferred Python command. For example:
python my_client.pySquare roots: [[1.0,1.4142135623730951,1.7320508075688772,2.0,...]] Unique strings: ['A', 'B', 'C', 'D'] Mean bill for John Doe: 111.4
You can modify your client application without stopping the MATLAB service. For example, add another function call to
mySqrt that specifies a scalar input
value.
rootScalar = client.myService.mySqrt(matlab.double(100))
print(f"Square root: {rootScalar}")python my_client.pySquare root: 10.0
Stop MATLAB REST Function Service
In MATLAB, stop the REST function service when it is no longer needed. The
Status property of the RESTFunctionService
object shows a status of notrunning.
stop(service) service
service = RESTFunctionService with properties: Name: "myService" Functions: ["mySqrt" "myUnique" "myMean"] ClientAccessMode: local FunctionConnector: [1×1 matlab.engine.rest.RESTFunctionConnector] ClientRequestInfo: [0×0 matlab.engine.rest.ClientRequestInfo] Status: notrunning