webwrite - Write data to RESTful web service - MATLAB (original) (raw)

Write data to RESTful web service

Syntax

Description

[response](#buocgv5-response) = webwrite([url](#buocgv5-url),[PostName1,PostValue1,...,PostNameN,PostValueN](#buocgv5-PostName1PostValue1PostNameNPostValueN)) writes content to the web service specified by url and returns the response in response. The input argumentsPostName1,PostValue1,...,PostNameN,PostValueN specify the content to write as one or more pairs of parameter names and values.webwrite form-encodes the content in the body of an HTTP POST request to the web service. The web service definesresponse.

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

example

[response](#buocgv5-response) = webwrite([url](#buocgv5-url),[data](#buocgv5-data)) posts data to the web service specified byurl and sets the media type based ondata.

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

example

[response](#buocgv5-response) = webwrite(___,[options](#buocgv5-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 write content as an internet media type other than a form-encoded character array ("application/x-www-form-urlencoded"), specify theMediaType 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.

example

Examples

collapse all

Write Data to Web Service

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

To run this code, create a ThingSpeak account. Callwebwrite 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 is1.

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)

Write Form-Encoded Character Data

Write form-encoded character 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)

responseData = struct with fields: dataType: 'application/json; charset=UTF-8' dataSize: '40'

Write JSON Object to Database

Write a database 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 Data with Timestamp

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. Callwebwrite using the Write API key and Channel ID from your ThingSpeak account. Specify the date for the feed entry with adatetime value.

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 is1.

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.

Specify Multiple Post Values

Write two pairs of parameter names and values tohttpbin.org. The site returns the POST parameters of the request.

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 — URL to web service

character vector | string scalar

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.

PostName1,PostValue1,...,PostNameN,PostValueN — Web service post parameters

pairs of parameter names and values

Web service post parameters, specified as one or more pairs of parameter names and values. A PostName argument must be a character vector or string scalar that specifies the name of a post parameter. APostValue 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, anddatetime values can be in arrays. The web service defines the parameters that it accepts as part of a request.webwrite encodes the parameters 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 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 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 required 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 seven days that contain the function webwrite. The File Exchange web service defines the term andduration parameters.

data — Data to write to web service

character vector | string scalar | ...

Data to write to a web service, specified as a character vector, a string scalar, or as a numeric scalar, cell, logical scalar, or structure forMediaType value "json", or as a Document Object Model for MediaType value"XML". If data is a character vector or string scalar, then webwrite sends it without conversion. All other types are converted based on theweboptions.MediaType value. For more information, see RFC 6838 Media Type Specifications and Registration Procedures on the RFC Editor website.

options — Additional HTTP request options

weboptions object

Additional HTTP request options, specified as aweboptions object. See weboptions for all request options, which are listed as weboptions properties.

Output Arguments

collapse all

response — Response from web service

scalar | array | structure | table

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

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

Extended Capabilities

Thread-Based Environment

Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.

Version History

Introduced in R2015a

expand all

R2024a: Ctrl+C stops execution of MATLAB command

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 r = webwrite(myURL,data) % User presses Ctrl+C catch ME rethrow(ME); end K>> ME ME = HTTPException with properties: ... r = webwrite(myURL,data) % User presses Ctrl+C Operation terminated by user during matlab.internal.webservices.urlencode>validateURL