Server Request and Response Classes
This section of the documentation documents the Request
and Response
classes in more detail.
- class Request
The
Request
class basically only has properties which you can simply read from directly. You do not need to interact with any of its methods.Properties
- Raw
The original raw request in its Custom Routes and Payloads low-level structure format. Generally you should not have to interact with this directly, and instead use the higher-level properties listed below, but it is available here if necessary.
- Params
A structure representing all the path parameters which were parsed from the path. If there are no path parameters defined for the operation, this will be an empty struct. If path parameters have been defined it will be a structure in which the names of the fields match the names of the path parameters. The fields should always exist, but their values may be empty depending on how the operation was called exactly.
Note that all values will always be strings. If you are expecting a numerical value convert it as appropriate.
Caution
Do not use
str2num
to convert path parameter values to numerical values. Its usage ofeval
can lead to security vulnerabilities.For example if a route was defined as:
app.get('/some/path/{foo}/{bar}',@myHandler);
Then inside
@myHandler
you should be able to write:function myHandler(req,res,~) % Get the value of Path parameter foo foo = req.Params.foo; % And bar bar = req.Params.bar
And the following table then shows what values
foo
andbar
could for example get, depending on the request path:Request Path
foo
bar
/some/path/abc
"abc"
""
/some/path/abc/123
"abc"
"123"
Note that if you make a request to
/some/path
, this will not be handled by@myHandler
at all, only the last path parameter may be empty.
- Query
A dictionary with all query parameters. The query parameters are also available as part of the
Path
property, but this provides a more convenient way to access them. Note that all values will always be strings. If you are expecting a numerical value convert it as appropriate.Caution
Do not use
str2num
to convert query parameter values to numerical values. Its usage ofeval
can lead to security vulnerabilities.For example if a route was defined as:
app.get('/some/path',@myHandler);
Then when a request was made to
/some/path?foo=hello&bar=123
You should be able to access parameters
foo
andbar
as follows:function myHandler(req,res,~) % Get the value of foo foo = req.Query("foo"); % Note that the line above would fail if parameter "foo" % had not been set in the request, so it is better to % use `lookup` with a `FallbackValue` bar = req.Query.lookup("bar",FallbackValue=""); % And for example then also verify the input if bar == "" res.Status(400).SendText("Value bar must be provided and cannot be empty."); return end
- Path
The path of the request, parsed into a
matlab.net.URI
instance.
- Body
The raw request body as
uint8
bytes. It is not automatically parsed into anything else, regardless of whatContent-Type
headers may have been set. If you for example want to parse the data into a string you will need to manually do this usingnative2unicode
. Or if you have a model class for the request body in question you can for example use:myData = MyServer.models.MyData().fromJSON(req.Body);
- Headers
The headers of the request, parsed into an array of
matlab.net.http.HeaderField
.
- class Response
The
Response
class has both properties and methods. While it is possible to directly modify the properties to influence the response, it is generally recommended to use the methods to construct the response.Note
None of the methods immediately send a response to the client when that method is called (despite some of them even being called
Send...
). They rather set up the response to be sent later once the method fully completes. Explicitly includereturn
statements in your code where appropriate to end the function and allow the response to be send. Note that when the function ends and the response has been send, this also really end the entire interaction with the client and you can no longer send additional data/responses/etc.The
Response
class aims to offer a fluent API, which means that most methods below will return theResponse
instance itself as output. Which allows you to “chain” calls of methods together. E.g. you can writeres.Status(200).SendText("Hello World")
to set the status code, response body, and content type in a single line.Methods
- SendStatus(res, code)
Sets the HTTP response code to the specified response code, the response body to the default text message corresponding to the code and
Content-Type
header totext/plain
.- Parameters:
code – the numeric HTTP response code.
- Returns:
res
the response instance itself.
- Status(res, code)
Sets the HTTP response code to the specified response code.
- Parameters:
code – the numeric HTTP response code.
- Returns:
res
the response instance itself.
- Json(res, data)
Sets the
Body
to a JSON representation of the input data and setsContent-Type
header toapplication/json
.The data is first converted into a string JSON representation internally by calling
jsonencode(data)
. In that sensedata
must be compatible with built-injsonencode
or ifdata
is a class it may implement its ownjsonencode
method. Generated Model classes, do implement such a method and are fully compatible with this.The string JSON data is then UTF-8 encoded using
unicode2native
to form the raw binary response body.- Parameters:
data – input data.
- Returns:
res
the response instance itself.
- JsonArray(res, data)
Sets the
Body
to a JSON Array representation of the input data and setsContent-Type
header toapplication/json
. The difference with theJson
method is that this really forces the output to always be a JSON array even if the input was just a scalar, whereasJson
will output a scalar JSON object or primitive if the input was a scalar.This method can be helpful because in MATLAB in general there is no real difference between “an array containing a scalar” and “just a scalar”. This method abstracts away some of the logic which you would need to add to force your scalar to become a JSON array (like having to wrap your scalar in a cell-array).
- Parameters:
data – input data.
- Returns:
res
the response instance itself.
- Send(res, data)
Sets the
Body
to the input data. If the input is of typechar
orstring
, it is automatically encoded as UTF-8 bytes usingnative2unicode
. If the input is of any other type, it is passed through as-is meaning it should already by of typeuint8
or MATLAB must be able to automatically convert it touint8
.Note this method never sets the
Content-Type
header, even if it did automatically encodechar
orstring
. UseSendText
if you also automatically set it totext/plain
. Or useSet
to set your own headers.- Parameters:
data – input data.
- Returns:
res
the response instance itself.
- SendText(res, text)
Sets the
Body
to the input text andContent-Type
header totext/plain
. The input text is automatically encoded as UTF-8 usingunicode2native
.- Parameters:
data – input text.
- Returns:
res
the response instance itself.
- Set(res, name, value)
Sets a header field to the specified value. If a header with the same name had already been set, it will be overwritten with the new value. If a header with the specified name did not yet exist it will be added.
- Parameters:
name – name of the header field.
data – value of the header field.
- Returns:
res
the response instance itself.
- GetStruct(res)
Returns the response in Custom Routes and Payloads response structure format. You generally do not have to call this method ever, the higher level framework will call it where necessary.
- Returns:
a Custom Routes and Payloads response structure.
Properties
- ApiVersion
The internal API version of the Custom Routes and Payloads feature. At the time of writing there is only one version:
[1 0 0]
.
- Body
The response body. This is in
uint8
binary format.Instead of interacting with this property directly it is recommended to use methods like
Send
,SendText
,Json
orJsonArray
to set theBody
instead.
- HttpCode
The HTTP status code to set on the response.
Instead of interacting with this property directly it is recommended to use
Status
orSendStatus
to set theHttpCode
instead.Its default value is
200
but for clarity it is recommended to always explicitly set the response code in your code even if should be200
. For example:name = req.Query.lookup("name",FallbackValue="") if name == "" % For an error response you will really want to set an error response code res.Status(400).SendText("name parameter is required and cannot be empty"); else % Strictly speaking not absolutely necessary to set the Status to 200 - OK % as it is the default, but recommended to make a clear distinction from % the condition above res.Status(200).SendText("Hello " + name); end