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 interface 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 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 = webread(___,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 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

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 and https 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, or datetime 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 a datetime value, 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 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 a weboptions 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 a weboptions object.

If you 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 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/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.

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.

"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 ContentType 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 a uint8 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

RESTful

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

  • For functionality not supported by the RESTful web services functions, see 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 web 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 intended CharacterEncoding option in weboptions.

  • For information on how to specify proxy server settings, see Proxy Server Authentication.

Extended Capabilities

Version History

Introduced in R2014b

expand all