Main Content

webwrite

Write data to RESTful web service

Description

example

response = webwrite(url,PostName1,PostValue1,...,PostNameN,PostValueN) writes content to the web service specified by url and returns response. The input arguments PostName1,PostValue1,...,PostNameN,PostValueN specify the content as name-value pairs. webwrite form-encodes the name-value pairs in the body of an HTTP POST request to the web service. The web service defines response.

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

example

response = webwrite(url,data) posts data to the web service specified by url and sets the media type based on the data.

The input argument data specifies the content as a form-encoded character array. webwrite puts data in the body of an HTTP POST request to the web service. The web service defines response.

example

response = webwrite(___,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 write content as an internet media type other than a form-encoded character array ('application/x-www-form-urlencoded'), specify the MediaType property of options.

To request data with an HTTP POST request and read the response with a function, specify the ContentReader property of options as a handle to the function. If you specify a handle to a function that returns multiple output arguments, webwrite returns all output arguments.

Examples

collapse all

Write a number to a channel feed on the ThingSpeak™ server and read it back.

To run this code, create a ThingSpeak account. Call webwrite using the Write API key and Channel ID from your ThingSpeak account. The default field name is 'field1'.

thingSpeakURL = 'http://api.thingspeak.com/';
thingSpeakWriteURL = [thingSpeakURL 'update'];
writeApiKey = 'Your Write API Key';
fieldName = 'field1';
fieldValue = 42;
response = webwrite(thingSpeakWriteURL,'api_key',writeApiKey,fieldName,fieldValue)

If this call to webwrite is the first update to your ThingSpeak channel, response is 1.

Read back the number you wrote to your channel. ThingSpeak provides a different URL to get the last entry to your channel. Your Channel ID is part of the URL.

channelID = num2str(Your Channel ID);
thingSpeakReadURL = [thingSpeakURL 'channels/' channelID '/fields/' fieldName '/last'];
data = webread(thingSpeakReadURL,'api_key',writeApiKey)
data =

42

This example shows how to write data to a Web server.

httpUrl  = 'http://requestserver.mathworks.com';
delim = '&';
pairDelim = '=';
data = 42;
data = num2str(data);
data = ['key', pairDelim, 'value', delim, 'field', pairDelim, data];
responseData = webwrite(httpUrl, data);
disp(responseData);
    dataType: 'application/x-www-form-urlencoded'
    dataSize: '18'

This example shows how to write a record as a JSON object.

httpsUrl = 'https://requestserver.mathworks.com';
employee(1).Name = 'Jon';
employee(1).Occupation = 'Doctor';
employee(2).Name = 'Sarah';
employee(2).Occupation = 'Engineer';
options = weboptions('MediaType', 'application/json');
responseEmployee = webwrite(httpsUrl, employee, options)
responseEmployee = struct with fields:
    dataType: 'application/json; charset=UTF-8'
    dataSize: '79'

Write a number and a specific date to a channel feed on the ThingSpeak server. Read the number and date back.

To run this code, create a ThingSpeak account. Call webwrite using the Write API key and Channel ID from your ThingSpeak account. Specify the date for the feed entry with a datetime object.

thingSpeakURL = 'http://api.thingspeak.com/';
thingSpeakWriteURL = [thingSpeakURL 'update'];
writeApiKey = 'Your Write API Key';
fieldName = 'field1';
fieldValue = 42;
D = datetime(2015,3,22,8,15,30,'Format','yyyy-MM-dd HH:mm:ss');
response = webwrite(thingSpeakWriteURL,'api_key',writeApiKey,...
    fieldName,fieldValue,'created_at',D)

If this call to webwrite is the first update to your ThingSpeak channel, response is 1.

Read back the last entry to your channel. ThingSpeak provides a different URL to get the last entry to your channel. Append last.json to the URL to get the data as a JSON object. Your Channel ID is part of the URL.

channelID = num2str(Your Channel ID);
thingSpeakReadURL = [thingSpeakURL 'channels/' channelID '/fields/' ...
    fieldName '/last.json'];
data = webread(thingSpeakReadURL,'api_key',writeApiKey)
data = 

    created_at: '2015-03-22T08:15:30Z'
      entry_id: 1
        field1: '42'

The date in the created_at field matches the date specified in D.

Write two name-value pair arguments to httpbin.org. The site returns the request's POST parameters.

uri = matlab.net.URI('http://httpbin.org/post');
res = webwrite(uri,'field1','hello','field2','world');
res.form
ans = 

  struct with fields:

    field1: 'hello '
    field2: 'world'

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.

Web service post parameters, specified as one or more pairs of name-value arguments. A PostName argument must specify the name of a post parameter. A PostValue argument must be a character vector, a string scalar, or a numeric, logical, or datetime value that specifies the value of the post 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. webwrite encodes the name-value pairs as a form-encoded character array in the body of an HTTP POST request and sets the content type to application/x-www-form-urlencoded by default.

When you specify PostValue 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 webwrite specifies 'Local' as the time zone.

When a PostValue argument contains multiple values in an array, specify the ArrayFormat property of a weboptions object to form-encode the array as specified by the web service.

Example: webwrite('https://www.mathworks.com/matlabcentral/fileexchange/','term','webwrite','duration',7) retrieves a list of files uploaded to the File Exchange within the past 7 days that contain the word webwrite. The File Exchange web service defines the term and duration parameters.

Data to post to a web service, specified as a character vector, a string scalar, or as numeric, cell, logical, or structure for MediaType value 'json', or as Document Object Model for MediaType value 'XML'. If data is a character string or character vector, then webwrite sends it without conversion. All other types are converted based on the weboptions.MediaType value. For more information, see RFC 6838 Media Type Specifications and Registration Procedures on the Internet Engineering Task Force (IETF®) website.

Example: webwrite('https://www.mathworks.com/matlabcentral/fileexchange/','term=webwrite&duration=7') retrieves a list of files uploaded to the File Exchange within the past 7 days that contain the word webwrite. The File Exchange web service defines the term and duration parameters.

Additional HTTP request options, specified as a weboptions object. See weboptions for all request options that are weboptions properties.

Output Arguments

collapse all

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

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

  • The webwrite function writes PostName,PostValue input arguments as form-encoded character arrays. If you also specify the options input argument, then its MediaType property must be 'application/x-www-form-urlencoded'.

  • webwrite cannot convert datetime objects to JSON, because JSON does not define a standard date format.

  • webwrite always puts PostName,PostValue query parameters into the body of the message regardless of the value of the RequestMethod property of options.

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

Extended Capabilities

Version History

Introduced in R2015a