webread — Read and decode content from a web service.
webread issues an HTTP or HTTPS GET request and decodes the response according to its content type and options.
Syntax
data = webread(url)
data = webread(url, optionsStruct)
data = webread(url, queryParameters)
data = webread(url, name, value, ...)
data = webread(url, optionsStruct, name, value, ...)
data = webread(url, queryParameters, name, value, ...)Inputs
url- Type
StringScalar- Required
- Yes
- Description
- HTTP/HTTPS URL to fetch.
optionsStruct- Type
Any- Required
- Yes
- Description
- weboptions struct or option struct literal.
queryParameters- Type
Any- Required
- Yes
- Description
- Two-column cell array of query parameter names and values.
name- Type
StringScalar- Required
- Variadic
- Description
- Option or query parameter name.
value- Type
Any- Required
- Variadic
- Description
- Option or query parameter value.
Returns
data- Type
Any- Description
- Downloaded payload decoded as JSON, text, or binary tensor.
Errors
RunMat:webread:InvalidArgument- When
- Argument type/shape does not match webread call contract.
- Message
webread: invalid argument
RunMat:webread:InvalidUrl- When
- URL input is empty or invalid.
- Message
webread: invalid URL
RunMat:webread:MissingOptionValue- When
- A name-value key has no corresponding value.
- Message
webread: missing option value
Behavior
Accepts URLs supplied as character vectors or string scalars; the URL must be absolute.
Query names are text. Query values may be text, numeric, or logical scalars or vectors; native integer values are formatted from exact storage without conversion to double. Vector values use comma-separated formatting in the current implementation.
An options structure immediately after the URL controls response decoding (ContentType), timeout (Timeout), headers (HeaderFields), and authentication (Username and Password). The default timeout is 5 seconds, and an integer timeout is read exactly.
A leading options structure also pairs KeyName with KeyValue as an HTTP header. Native integer key values retain exact decimal text; the empty default pair adds no header or query parameter. Direct name-value query pairs keep their query meaning.
RunMat also accepts a leading structure or cell array of query parameters and recognizes option-like direct name-value pairs. These conveniences do not replace the portable query-pair plus final-options form.
ContentType 'auto' (default) inspects the Content-Type response header to choose between JSON, text, or binary decoding. Explicit ContentType 'json', 'text', or 'binary' override the detection logic.
JSON responses are parsed with the same rules as jsondecode, producing doubles, logicals, strings, structs, and cell arrays that match MATLAB semantics.
Text responses use the response character encoding when supported. Binary payloads return an exact 1×N uint8 row vector.
Image, audio, table, XML DOM, raw-response, and custom ContentReader result forms are not yet implemented.
HTTP errors (non-2xx status codes), timeouts, TLS failures, and parsing problems raise descriptive MATLAB-style errors.
Placement and support
HTTP and TLS execute on the host and results are host-resident. Automatically resident values gather transparently; explicit gpuArray input requires RunMat mode.
The request path terminates fusion and gathers automatically resident values through their owning provider. Explicit gpuArray input crosses the webread-explicit-gpu-input extension gate before any gather.
HTTP is an effectful host boundary, not a GPU kernel or fusion operation. Browser custom User-Agent headers are restricted by the browser platform; the browser service does not promise to set them.
No optional feature is required; the active host must install HTTP service capability.
Further examples
The external API addresses below are illustrative and depend on third-party responses. Runnable loopback examples on this page exercise the same JSON, text, binary, query, and credential/header call forms with fixed response data.
Reading JSON data from a REST API
opts = weboptions("ContentType", "json", "Timeout", 15);
weather = webread("https://api.example.com/weather", opts, "city", "Reykjavik");
disp(weather.temperatureC)
Expected display: 2.3
Downloading plain text as a character vector
html = webread("https://example.com/index.txt", "Timeout", 5);
extract = html(1:200)
Retrieving binary payloads such as images
bytes = webread("https://example.com/logo.png", "ContentType", "binary");
filewrite("logo.png", uint8(bytes))
Supplying custom headers and credentials
headers = struct("Accept", "application/json", "X-Client", "RunMat");
data = webread("https://api.example.com/me", ...
"Username", "ada", "Password", "secret", ...
"HeaderFields", headers, ...
"ContentType", "json")
Passing query parameters as a struct
query = struct("limit", 25, "sort", "name");
response = webread("https://api.example.com/resources", query, "ContentType", "json")
Examples
Read an HTTP text response
data = webread('__RUNMAT_HTTP_BASE_URL__/message', 'ContentType', 'text');
disp(data);Expected output:
RunMat HTTP fixtureRead JSON with an options structure and query value
opts = weboptions('ContentType', 'json', 'Timeout', 15);
weather = webread('__RUNMAT_HTTP_BASE_URL__/weather', opts, 'city', 'Reykjavik');
disp(weather.temperatureC);Expected output:
2.3Extract text from a downloaded character vector
html = webread('__RUNMAT_HTTP_BASE_URL__/index.txt', 'Timeout', 5);
extract = html(1:6);
disp(extract);Expected output:
RunMatRetrieve exact binary response bytes
bytes = webread('__RUNMAT_HTTP_BASE_URL__/logo.png', 'ContentType', 'binary');
assert(isa(bytes, 'uint8'));Supply headers and HTTP basic credentials
headers = struct('Accept', 'application/json', 'X-Client', 'RunMat');
data = webread('__RUNMAT_HTTP_BASE_URL__/me', 'Username', 'ada', 'Password', 'secret', 'HeaderFields', headers, 'ContentType', 'json');
disp(data.name);Expected output:
AdaPass query values through a structure
query = struct('limit', 25, 'sort', 'name');
response = webread('__RUNMAT_HTTP_BASE_URL__/resources', query, 'ContentType', 'json');
disp(response.count);Expected output:
1Using webread with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how webread changes the result.
Run a small webread example, explain the result, then change one input and compare the output.
FAQ
Can webread decode JSON automatically?⌄
Yes. When the server reports a JSON Content-Type header (for example application/json or application/vnd.api+json) the builtin decodes it using the same rules as jsondecode. Override the behaviour with "ContentType","text" or "ContentType","binary" when needed.
How do I control request timeouts?⌄
Set Timeout in an options structure immediately after the URL or in a supported direct name-value pair. The default is 5 seconds; a positive scalar up to 2147.483647 seconds or Inf is accepted.
What headers can I set?⌄
Use "HeaderFields", struct(...) or a cell array of name/value pairs. Header names must be valid HTTP tokens. Native requests use a RunMat-specific User-Agent unless overridden; browsers restrict setting that header.
Does webread follow redirects?⌄
Yes. The underlying HTTP client follows redirects up to the platform default limit while preserving headers and authentication.
How do I provide credentials?⌄
Use "Username", "user", "Password", "pass" for HTTP basic authentication. Supplying a password without a username raises an error.
Can I send POST or PUT requests?⌄
webread supports GET. Use webwrite for requests with bodies or mutation methods.
How are binary responses represented?⌄
Binary payloads return an exact 1×N uint8 row vector.
What happens when the server returns an error status?⌄
Non-success HTTP status codes raise webread: request to … failed with HTTP status XYZ. Inspect the remote server logs or response headers for additional diagnostics.
Does webread support compressed responses?⌄
Yes. The builtin enables gzip / deflate content decoding through the HTTP client automatically.
Can I pass query parameters as GPU arrays?⌄
Automatically resident query values gather transparently. Explicit gpuArray query values are supported only in RunMat mode and are rejected before provider access in MATLAB-compatible mode.
Related Io functions
Repl Fs
addpath · cd · copyfile · delete · dir · exist · fileattrib · fileparts · filesep · fullfile · genpath · getenv · getpref · isenv · isfile · isfolder · ispref · ls · matlabroot · memmapfile · memmapfile.subsasgn · memmapfile.subsref · mkdir · movefile · open · opentoline · path · pathsep · pcode · pwd · readstruct · rehash · restoredefaultpath · rmdir · rmpath · run · savepath · setenv · setpref · system · tempdir · tempname · uigetdir · uigetfile · uiputfile · unsetenv · userpath · what · winqueryreg · xmlread · xmlwrite
Tabular
arrayDatastore · csvread · csvwrite · detectImportOptions · dlmread · dlmwrite · fileDatastore · getvaropts · parquetDatastore · parquetinfo · parquetread · readcell · readmatrix · readtable · readtimetable · setvaropts · setvartype · spreadsheetImportOptions · writecell · writematrix · writetable · writetimetable · xlsread · xlswrite
Data
commit · data.copy · data.create · data.delete · data.exists · data.export · data.import · data.inspect · data.list · data.move · data.open · DataArray.chunk_shape · DataArray.codec · DataArray.dtype · DataArray.fill · DataArray.name · DataArray.rank · DataArray.read · DataArray.resize · DataArray.shape · DataArray.write · Dataset.array · Dataset.arrays · Dataset.attrs · Dataset.begin · Dataset.get_attr · Dataset.has_array · Dataset.id · Dataset.path · Dataset.refresh · Dataset.set_attr · Dataset.set_attrs · Dataset.snapshot · Dataset.version · DataTransaction.abort · DataTransaction.commit · DataTransaction.create_array · DataTransaction.delete_array · DataTransaction.fill · DataTransaction.id · DataTransaction.resize · DataTransaction.set_attr · DataTransaction.set_attrs · DataTransaction.status · DataTransaction.write
Filetext
fclose · feof · fgetl · fgets · fileread · filewrite · fopen · fprintf · fread · frewind · fwrite · readlines · writelines
Import
Json
Source you can read
Every RunMat function's source is public. Read exactly how webread is executed, line by line, in Rust.
- View the source for webread in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.