webread - Read content from RESTful web service - MATLAB (original) (raw)

Read content from RESTful web service

Syntax

Description

[data](#bue6uid-data) = webread([url](#bue6uid-url)) reads content from the web service specified by url and returns the content in data.

The web service provides a RESTful interface that returns data formatted as an internet media type, such as JSON, XML, image, or text.

example

[data](#bue6uid-data) = webread([url](#bue6uid-url),[QueryName1,QueryValue1,...,QueryNameN,QueryValueN](#bue6uid-QueryName1QueryValue1QueryNameNQueryValueN)) appends query parameters to url, as specified by one or more pairs of parameter names and values. To put a query into the body of the message, use webwrite. The web service defines the query parameters.

example

[data](#bue6uid-data) = webread(___,[options](#bue6uid-options)) adds other HTTP request options, specified by the weboptions object options. You can specify this argument in addition to any of the input argument combinations in the previous syntaxes.

To return data as a specific output type, specify theContentType property ofoptions.

To read content with a function, specify the ContentReader property of options as a handle to the function.webread downloads data from a web service and reads the data with the specified function:

example

[[data](#bue6uid-data),[colormap](#bue6uid-colormap),[alpha](#bue6uid-alpha)] = webread(___) reads an image from the web service specified by url and returns the image in data. You can use the previous syntaxes to return the image only. Use this syntax to return the colormap and alpha channels associated with the image.

webread returns an image when the HTTP response has aContent-Type header field that specifies an image media type and if imread supports the image format. For supported image formats, see Supported File Formats for Import and Export.

[[data](#bue6uid-data),[Fs](#bue6uid-Fs)] = webread(___) reads audio data from the web service specified by url and returns the audio data indata. You can use the previous syntaxes to return the audio data only. Use this syntax to return the sample rate of the audio data in hertz.

webread returns audio data when the HTTP response has aContent-Type header field that specifies an audio media type and if audioread supports the audio format. For supported audio formats, see Supported File Formats for Import and Export.

Examples

collapse all

Read image data from a website.

httpsUrl = "https://requestserver.mathworks.com"; imageUrl = strcat(httpsUrl, "/assets/computerVision.jpg"); rgb = webread(imageUrl); whos rgb

Name Size Bytes Class Attributes

rgb 360x640x3 691200 uint8

Resize and display the image.

rgb = imresize(rgb, 0.6); imshow(rgb)

Figure contains an axes object. The axes object contains an object of type image.

Read temperatures from a CSV data file.

httpsUrl = "https://requestserver.mathworks.com"; dataUrl = strcat(httpsUrl,"/assets/weatherStation.csv"); data = webread(dataUrl); time = [data.Time]; temp = [data.TempF];

Plot the temperature data.

plot(time,temp) xlabel("Time") ylabel("Temperature (Fahrenheit)") title("Temperature Over Time"); axis padded

Figure contains an axes object. The axes object with title Temperature Over Time, xlabel Time, ylabel Temperature (Fahrenheit) contains an object of type line.

You can select a database record using query parameters.

First, view the structure of an employee database by displaying its fields.

httpsUrl = "https://requestserver.mathworks.com"; employeeUrl = strcat(httpsUrl,"/employee"); fieldnames(webread(employeeUrl))

ans = 6×1 cell {'id' } {'firstName' } {'lastName' } {'occupation'} {'age' } {'city' }

Then, select the record of an employee by using the firstName and lastName query parameters.

jSmith = webread(employeeUrl,"firstName","John","lastName","Smith")

jSmith = struct with fields: id: 1 firstName: 'John' lastName: 'Smith' occupation: 'Software Engineer' age: '32' city: 'Boston'

You can return data as a specific type.

Create a weboptions object and set its ContentType to "text". Using the specified options, the webread function converts the JSON data to a character array.

httpUrl = "http://requestserver.mathworks.com"; employeeUrl = strcat(httpUrl,"/employee"); options = weboptions("ContentType","text"); sBrown = webread(employeeUrl,"firstName","Sarah",options)

sBrown = '[{"id":2,"firstName":"Sarah","lastName":"Brown","occupation":"Software Engineer","age":"28","city":"New York"}]'

Input Arguments

collapse all

URL to a web service, specified as a character vector or string scalar. Include the transfer protocol. Only http andhttps are supported. The web service implements a RESTful interface. See RESTful for more information.

Example: webread("https://www.mathworks.com/matlabcentral") reads the webpage and returns its HTML as a character array.

Web service query parameters, specified as one or more pairs of parameter names and values. A QueryName argument must be a character vector or string scalar that specifies the name of a query parameter. A QueryValue argument must be a character vector, a string scalar, or a numeric, logical, ordatetime value that specifies the value of the query parameter. Numeric, logical, and datetime values can be in arrays. The web service defines the parameters that it accepts as part of a request.

When you specify QueryValue as adatetime value, you must specify itsFormat property so that it is consistent with the format required by the web service. If the Format property includes a time zone or offset, and the datetime value is not zoned, then webread specifies"Local" as the time zone.

When QueryValue contains multiple values in an array, you might need to specify the ArrayFormat property of aweboptions object to form-encode the array as required by the web service.

Example: webread("https://www.mathworks.com/matlabcentral/fileexchange/","term","webread") retrieves a list of files uploaded to the File Exchange that contain the function webread. The File Exchange web service defines the term parameter.

Additional HTTP request options, specified as aweboptions object.

If you specify the ContentType property of aweboptions object, and pass the object as an input argument to webread, then webread returns data as that type of output. The table lists the valid content types you can specify in a weboptions object.

ContentType Value Output Type
"auto" (default) Output type is automatically determined based on the content type specified by the web service.
"text" Character vector for content types: text/plaintext/htmltext/xmlapplication/xmlapplication/javascriptapplication/x-javascriptapplication/x-www-form-urlencodedIf a web service returns a MATLAB® file with a .m extension, the function returns its content as a character vector.For text content returned from a server, if no character encoding is specified by the server or by the user, then the function uses UTF-8 by default.
"image" Numeric or logical matrix for image/format content.For supported image formats, see Supported File Formats for Import and Export.
"audio" Numeric matrix for audio/format content.For supported audio formats, see Supported File Formats for Import and Export.
"binary" uint8 column vector for binary content (that is, content not to be treated as type char).
"table" Scalar table object for spreadsheet and CSV (text/csv) content.Alternatively, to read table data from a website, callreadtable with the filename argument specified as a URL. For an example, seeRead HTML Webpage as Table.
"json" char, numeric, logical, structure, or cell array forapplication/json content.
"xmldom" Java® Document Object Model (DOM) node fortext/xml orapplication/xml content. IfContentType is not specified, the function returns XML content as a character vector.
"raw" char column vector for "text","xmldom", and"json" content. The function returns any other content type as auint8 column vector.

See weboptions for all request options which are listed as weboptions properties.

Output Arguments

collapse all

Content from a web service, returned as a scalar, array, structure, or table.

Colormap associated with an indexed image, returned as a numeric array.

Alpha channels associated with an indexed image, returned as a numeric array.

Sample rate of audio data in hertz, returned as a positive numeric scalar.

More About

collapse all

REST stands for representational state transfer, a common architectural style for web services. RESTful interfaces provide standard HTTP methods, such as GET, PUT, POST, or DELETE.

Tips

Extended Capabilities

Version History

Introduced in R2014b

expand all

Pressing Ctrl+C while executing this function stops execution of the MATLAB command. This behavior is consistent with how other MATLAB functionality handles Ctrl+C, as described in Use Keyboard Shortcuts to Navigate MATLAB.

Previously, the function threw a custom exception that users could catch inside atry/catch block. If your code containstry/catch blocks, you can update your code by removing them.

This table shows an example of the different results when you pressCtrl+C before and starting in R2024a.

Before After
try d = webread(myURL) % User presses Ctrl+C catch ME rethrow(ME); end K>> ME ME = HTTPException with properties: ... d = webread(myURL) % User presses Ctrl+C Operation terminated by user during matlab.internal.webservices.urlencode>validateURL

See Also

Functions

Topics