Main Content

webread

Read content from RESTful web service

Description

example

data = webread(url) reads content from the web service specified by url and returns the content in data.

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

example

data = webread(url,QueryName1,QueryValue1,...,QueryNameN,QueryValueN) appends query parameters to url, as specified by one or more pairs of name-value arguments. To put a query into the body of the message, use webwrite. The web service defines the query parameters.

example

data = webread(___,options) adds other HTTP request options, specified by the weboptions object options. You can use this syntax with any of the input arguments of the previous syntaxes.

To return data as a specific output type, specify the ContentType property of options.

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:

  • If you specify a handle to a function that returns multiple output arguments, webread returns all output arguments.

  • If you specify a handle to a function that returns no output argument (such as Image Processing Toolbox™ function @implay for video files), webread returns no output argument.

[data,colormap,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 a Content-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,Fs] = webread(___) reads audio data from the web service specified by url and returns the audio data in data. 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 a Content-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

This example shows how to read an image from a website and display it.

Read Image Data

httpsUrl = 'https://requestserver.bat365';
imageUrl = strcat(httpsUrl, '/assets/computerVision.jpg');
rgb = webread(imageUrl);
whos rgb
  Name        Size                Bytes  Class    Attributes

  rgb       360x640x3            691200  uint8              

Resize and Display Image

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

This example shows how to read temperatures from a csv data file.

Read Data from CSV File

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

Display Temperature Plot

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

This example shows how to select a record using query parameters.

View Employee Database Structure

Display the fields of database employee.

httpsUrl = "https://requestserver.bat365";
employeeUrl = strcat(httpsUrl, "/employee");
fieldnames(webread(employeeUrl))
ans = 6×1 cell
    {'id'        }
    {'firstName' }
    {'lastName'  }
    {'occupation'}
    {'age'       }
    {'city'      }

Select Employee by firstName and lastName

jSmith = webread(employeeUrl, "firstName", "John", "lastName", "Smith");
disp(jSmith);
            id: 1
     firstName: 'John'
      lastName: 'Smith'
    occupation: 'Software Engineer'
           age: '32'
          city: 'Boston'

This example shows how to return data as a specific type.

Read Data

httpUrl  = "http://requestserver.bat365";
employeeUrl = strcat(httpUrl, "/employee");

Return Record as Character Array

Create a weboptions object and set its ContentType to 'text'. The webread function converts the JSON object to a character array.

options = weboptions("ContentType", "text");
sBrown = webread(employeeUrl, "firstName", "Sarah", options);
disp(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 and https are supported. The web service implements a RESTful interface. See RESTful for more information.

Example: webread('/matlabcentral') reads the web page and returns its HTML as a character array.

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

When you specify QueryValue as a datetime object, you must specify its Format 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 object 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 a weboptions object to form-encode the array as specified by the web service.

Example: webread('/matlabcentral/fileexchange/','term','webread') retrieves a list of files uploaded to the File Exchange that contain the word webread.

Additional HTTP request options, specified as a weboptions object.

You can specify the ContentType property of a weboptions 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 Specifier

Output Type

'auto' (default)

Output type automatically determined based on content type specified by the server.

'text'

Character vector for content types:

text/plain
text/html
text/xml
application/xml
application/javascript
application/x-javascript
application/x-www-form-urlencoded

If a web service returns a MATLAB® file with a .m extension, the function returns its content as a character vector.

'image'

Numeric or logical matrix for image/format content. If the first output argument is an indexed image, the second output argument is the colormap, and the third output argument is the alpha channel.

For supported image formats, see Supported File Formats for Import and Export.

'audio'

Numeric matrix for audio/format content with numeric scalar sampling rate as a second output argument.

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.

'json'

char, numeric, logical, structure, or cell array, for application/json content.

'xmldom'

Java® Document Object Model (DOM) node for text/xml or application/xml content. If 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 a uint8 column vector.

See weboptions for all request options that are weboptions properties.

Output Arguments

collapse all

Content read 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

RESTful

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

Tips

  • For functionality not supported by the RESTful web services functions, see the Call Web Services from MATLAB Using HTTP.

  • webread supports HTTP GET and POST methods. Many web services provide both GET and POST methods to request data. To send an HTTP POST request, specify the RequestMethod property of options as 'post'. However, webread puts query options into the url, not in the body of the request message. To put a query into the body, use webwrite.

  • For HTTP POST requests, the webread function supports only the application/x-www-form-urlencoded media type. To send a POST request with content of any other internet media type, use webwrite.

  • This function does not examine the document contents to determine how to process it. For example, HTML and XML documents often contain a <meta> tag that specifies the document character encoding. If the encoding is different from the default webread encoding, then specify the correct CharacterEncoding option in weboptions.

  • To specify proxy server settings, see Proxy Server Authentication.

Extended Capabilities

Version History

Introduced in R2014b