# How to Use Nelson's Web Tools for RESTful API Interactions: A Complete Guide

> Learn to use Nelson's web tools for RESTful API interactions. Explore webread, webwrite, weboptions, and websave to easily handle HTTP requests and JSON responses in MATLAB.

- Repository: [The Nelson Programming Language/nelson](https://github.com/nelson-lang/nelson)
- Tags: how-to-guide
- Published: 2026-03-08

---

**Nelson's webtools module provides MATLAB-compatible functions `webread`, `webwrite`, `weboptions`, and `websave` to execute HTTP requests and automatically convert JSON responses into native data structures.**

The [nelson-lang/nelson](https://github.com/nelson-lang/nelson) repository includes a self-contained **webtools** module that enables RESTful API interactions using a familiar high-level syntax. This implementation leverages a low-level C++ gateway (`webREST`) built on libcurl to handle the actual network I/O, while the M-file functions manage request configuration and response parsing.

## Understanding Nelson's Web Tools Architecture

The webtools stack separates configuration from execution. The M-files located in `modules/webtools/functions/` handle MATLAB-compatible syntax validation and data conversion, while the native gateway performs the HTTP transaction.

### Core Components

- **`weboptions`** (`modules/webtools/functions/@weboptions/weboptions.m`): Constructs an options object that stores `RequestMethod`, `HeaderFields`, `Timeout`, `ContentType`, and SSL certificates. The constructor validates name-value pairs between lines 10-28.

- **`webread`** (`modules/webtools/functions/webread.m`): Executes GET, DELETE, or HEAD requests. The main flow (lines 10-49) builds a temporary filename, invokes the `webREST` gateway, and passes the raw response to `convertContentType` (lines 88-108) for automatic JSON/text/binary decoding.

- **`webwrite`** (`modules/webtools/functions/webwrite.m`): Handles POST, PUT, and PATCH requests. It serializes the data argument (lines 22-27) and forces `RequestMethod` to `'post'` when the user specifies `'auto'` (lines 66-68).

- **`websave`** (`modules/webtools/functions/websave.m`): A thin wrapper around `webread` that writes the response directly to disk rather than returning it to the workspace.

- **`webREST`** ([`modules/webtools/builtin/c/webREST.cpp`](https://github.com/nelson-lang/nelson/blob/main/modules/webtools/builtin/c/webREST.cpp)): The C++ gateway that interfaces with libcurl to perform the actual HTTP I/O, respecting all fields in the `weboptions` structure.

## Configuring API Requests with weboptions

Before executing any request, you define connection parameters using `weboptions`. This function accepts name-value pairs and returns a structured object that `webread` and `webwrite` parse internally.

```matlab
% Create options for a JSON API with custom headers
opts = weboptions( ...
    'RequestMethod', 'get', ...
    'ContentType',   'json', ...
    'Timeout',       30, ...
    'HeaderFields',  {'Accept: application/json'; 'Authorization: Bearer token123'});

```

The constructor in `modules/webtools/functions/@weboptions/weboptions.m` validates each field between lines 10-28, ensuring that `RequestMethod` is one of the supported HTTP verbs and that `HeaderFields` is a cell array of strings.

## Reading Data from REST APIs Using webread

The `webread` function is the primary interface for retrieving data. It supports automatic content conversion based on the `ContentType` option or the server's `Content-Type` header.

### Simple GET Request with JSON

```matlab
opts = weboptions('ContentType', 'json', 'Timeout', 10);
url  = 'https://httpbin.org/json';

% webread returns a struct decoded from JSON
response = webread(url, opts);
disp(response.slideshow.title);

```

According to the source code in `modules/webtools/functions/webread.m` (lines 10-49), the function:
1. Extracts the URL and optional `weboptions` object
2. Generates a temporary filename via `buildTempFilename`
3. Invokes the `webREST` gateway to execute the HTTP transaction
4. Passes the raw response to `convertContentType` (lines 88-108) for decoding

### Custom Content Reader for Binary Data

When the automatic conversion is insufficient, provide a function handle via the `ContentReader` option:

```matlab
% Custom reader that loads an image directly into a matrix
myReader = @(tmp) imread(tmp);

opts = weboptions( ...
    'RequestMethod', 'get', ...
    'ContentReader', myReader, ...
    'Timeout',       10 );

url = 'https://httpbin.org/image/png';
img = webread(url, opts);  % Returns uint8 matrix

imshow(img);

```

The `webread` implementation detects function handles in `options.ContentReader` (lines 49-63) and invokes them with the temporary file path containing the raw response.

## Writing Data to REST APIs Using webwrite

Use `webwrite` to send data to servers via POST, PUT, or PATCH methods. The function automatically serializes structures to JSON when `MediaType` is set to `application/json`.

### POST JSON Payload

```matlab
payload = struct('name', 'Nelson', 'type', 'webtools');

opts = weboptions( ...
    'RequestMethod',  'post', ...
    'MediaType',      'application/json', ...
    'ContentType',    'json', ...
    'Timeout',        15 );

url    = 'https://httpbin.org/post';
result = webwrite(url, payload, opts);  % Server echoes the payload

disp(result.json);

```

In `modules/webtools/functions/webwrite.m`, the implementation:
- Serializes the data argument to JSON if it is a structure or cell array (lines 22-27)
- Forces `RequestMethod` to `'post'` when the user specifies `'auto'` (lines 66-68)
- Reuses the same response conversion logic as `webread`

### Uploading Files with PUT

For binary uploads, read the file into a variable and specify the appropriate `MediaType`:

```matlab
% Read local file as uint8 array
fileData = fileread('myimage.png', 'uint8');

opts = weboptions( ...
    'RequestMethod', 'put', ...
    'MediaType',     'application/octet-stream', ...
    'ContentType',   'binary', ...
    'Timeout',       20 );

url      = 'https://example.com/upload';
response = webwrite(url, fileData, opts);

```

The `webwrite` function passes raw binary data unchanged to the `webREST` gateway when `ContentType` is set to `'binary'`, as handled in the conversion logic within `convertContentType` (lines 100-106).

## Downloading Files with websave

When you need to persist the response to disk rather than loading it into memory, use `websave`. This function is a thin wrapper around `webread` that writes the output to a specified filename.

```matlab
opts    = weboptions('Timeout', 30);
url     = 'https://httpbin.org/image/jpeg';
outfile = fullfile(tempdir, 'downloaded.jpg');

% Download and save to disk
downloaded = websave(outfile, url, opts);

fprintf('Saved to %s (size %d bytes)\n', downloaded, dir(downloaded).bytes);

```

The `websave` implementation invokes `webread` internally and writes the returned payload to the user-specified path, making it ideal for retrieving large binary assets without holding them in the workspace.

## Summary

- **Nelson's webtools module** provides MATLAB-compatible functions `webread`, `webwrite`, `weboptions`, and `websave` for RESTful API interactions.
- **`weboptions`** (`modules/webtools/functions/@weboptions/weboptions.m`) validates request parameters including headers, timeouts, and content types.
- **`webread`** (`modules/webtools/functions/webread.m`) handles GET requests and automatically converts JSON, text, or binary responses using `convertContentType`.
- **`webwrite`** (`modules/webtools/functions/webwrite.m`) sends POST, PUT, or PATCH requests, automatically serializing structures to JSON when appropriate.
- **The C++ gateway** `webREST` ([`modules/webtools/builtin/c/webREST.cpp`](https://github.com/nelson-lang/nelson/blob/main/modules/webtools/builtin/c/webREST.cpp)) performs the actual HTTP I/O using libcurl, respecting all configured options.

## Frequently Asked Questions

### What HTTP methods does Nelson's webtools support?

Nelson supports **GET**, **POST**, **PUT**, **DELETE**, **PATCH**, and **HEAD** requests. You specify the method via the `RequestMethod` parameter in `weboptions`. When using `webwrite`, the method defaults to `POST` if set to `'auto'`, while `webread` defaults to `GET`.

### How does Nelson handle JSON conversion automatically?

When `ContentType` is set to `'json'` (or `'auto'` with a JSON response), Nelson passes the raw HTTP response to the `convertContentType` function located in `modules/webtools/functions/webread.m` (lines 88-108). This function parses the JSON string and converts it into native Nelson data types such as structures and cell arrays.

### Can I use custom headers and authentication with Nelson web tools?

Yes. Pass custom headers as a cell array of strings to the `HeaderFields` option in `weboptions`. For example: `weboptions('HeaderFields', {'Authorization: Bearer token123'; 'Accept: application/json'})`. The constructor in `modules/webtools/functions/@weboptions/weboptions.m` validates these fields between lines 10-28 before passing them to the `webREST` gateway.

### Where is the actual HTTP implementation in Nelson?

The actual network I/O is performed by the **C++ gateway** `webREST`, located in [`modules/webtools/builtin/c/webREST.cpp`](https://github.com/nelson-lang/nelson/blob/main/modules/webtools/builtin/c/webREST.cpp). This gateway uses libcurl to execute HTTP requests and respects all fields defined in the `weboptions` structure, including SSL certificate settings, timeouts, and redirect following.