> You are reading the Docusign Developer Documentation. For clean Markdown of any page, append .md to the page URL.
>
> Documentation indexes by section:
> - APIs and SDKs: https://docusign.docs.buildwithfern.com/docs/llms.txt
> - Platform 101: https://docusign.docs.buildwithfern.com/platform/llms.txt
> - Extension Apps: https://docusign.docs.buildwithfern.com/extension-apps/llms.txt
> - Docusign CLI: https://docusign.docs.buildwithfern.com/docusign-cli/llms.txt
>
> Authentication (OAuth, JWT Grant, M2M): https://docusign.docs.buildwithfern.com/platform/auth
> Webhooks and Connect: https://docusign.docs.buildwithfern.com/platform/webhooks
>
> OpenAPI specifications: https://docusign.docs.buildwithfern.com/openapi.json
> MCP server: https://docusign.docs.buildwithfern.com/_mcp/server

# How to get monitoring data

> Learn how to get and display all of your organization’s monitoring data.

This topic demonstrates how to get and display all of your organization’s monitoring data.

> **Note**
>
> Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects: [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).

## Prerequisites

Running the code in this how-to requires this data:

| Prerequisite                                           | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Admin access                                           | To call the Docusign Monitor endpoint, you must impersonate a user with administrator access to your organization. This means that you must have obtained your access token using [JWT Grant](/platform/auth/jwt-get-token) and have requested the impersonation [scope](/platform/auth/reference/scopes). **Note:** The impersonated administrator may not be an admin of more than one organization. Admins of two or more organizations who call the Monitor API endpoint will receive responses with the 403 Forbidden [error code](/docs/esign-rest-api/esign101/error-codes). |
| Your organization must have access to Docusign Monitor | Your organization must have access to Docusign Monitor to call the endpoint. The Monitor API is available for developer (demo) accounts for testing and development, but for apps in the production environment, it is a separate SKU that requires Enterprise Pro. For more information about how to enable the Monitor API for your account, contact Docusign Support.                                                                                                                                                                                                            |

## Step 1. Obtain your OAuth token

To make the API calls shown in this how-to, you need a valid OAuth access token.

Because Docusign Monitor requires that you impersonate a user with admin access to your organization, you must have obtained your access token using  [JWT Grant](/platform/auth/jwt-get-token) and have requested the impersonation [scope](/platform/auth/reference/scopes). For details, see [Docusign Monitor Authentication](/docs/monitor-api/monitor101/auth).

![](/_fern-files/_img/8fa9d5571f1873e1b0889d7c53a9d86ac5b7918878793372360ab134c431b95d.webp)

## Step 2. Construct your API headers

After you have a valid OAuth access token, you are ready to construct the API headers that you will pass to the API call. Construct your headers like this, but make sure to substitute your valid OAuth access token for \{ACCESS_TOKEN}.

**`Bash`**

```bash title="Bash"
declare -a Headers=('--header' "Authorization: Bearer ${ACCESS_TOKEN}"
    '--header' "Accept: application/json"
    '--header' "Content-Type: application/json")
```

**`C#`**

```csharp title="C#"
apiClient.SetBasePath(DocuSignClient.Demo_REST_BasePath);
apiClient.Configuration.DefaultHeader.Add("Authorization", string.Format("Bearer {0}", accessToken));
apiClient.Configuration.DefaultHeader.Add("Content-Type", "application/json");
```

**`Java`**

```java title="Java"
ApiClient apiClient = new ApiClient(config.getMonitorBasePath());
apiClient.addDefaultHeader(HttpHeaders.AUTHORIZATION, BEARER_AUTHENTICATION + accessToken);
apiClient.setBasePath(config.getMonitorBasePath());
```

**`Node.js`**

```javascript title="Node.js"
let dsApiClient = new docusign.ApiClient();
dsApiClient.setBasePath(args.basePath);
dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + args.accessToken);
```

**`PHP`**

```php title="PHP"
$config = new Configuration();
$accessToken = $_SESSION['ds_access_token'];

$config->setAccessToken($accessToken);
$config->setHost('https://lens-d.docusign.net');
$config->addDefaultHeader('Authorization', 'Bearer ' . $accessToken);
$config->addDefaultHeader("Content-Type", "application/json");
$this->apiClient = new ApiClient($config);
```

**`PowerShell`**

```text title="PowerShell"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.add("Authorization", "Bearer $accessToken")
$headers.add("Accept", "application/json")
$headers.add("Content-Type", "application/json")
```

**`Python`**

```python title="Python"
api_client = create_monitor_api_client(
    access_token=args["access_token"]
)
```

**`Ruby`**

```ruby title="Ruby"
configuration = DocuSign_Monitor::Configuration.new
configuration.host = Rails.configuration.monitor_host
configuration.debugging = true
api_client = DocuSign_Monitor::ApiClient.new configuration
api_client.set_default_header('Authorization', "Bearer #{args[:access_token]}")
```

## Step 3. Get monitoring data

Make a GET request to the [DataSet:getStream](/docs/monitor-api/reference/monitor/dataset/stream) endpoint to get your monitoring data. Because your organization may have large amounts of data, you can use the `limit` query parameter to specify the maximum number of records each call will return (2,000 in the example shown here) and a `cursor` value to continue the query from where the previous one left off.

In this example, we return and display chunks of monitoring data, record the returned cursor value, and use that value to begin the next query until all data has been returned.

> **Note**
>
> View the source code for this how-to on GitHub: [Bash](https://github.com/docusign/code-examples-bash/blob/master/examples/Monitor/eg001GetMonitoringData.sh), [C#](https://github.com/docusign/code-examples-csharp/blob/master/launcher-csharp/Monitor/Examples/GetMonitoringDataFunc.cs), [Java](https://github.com/docusign/code-examples-java/blob/master/src/main/java/com/docusign/controller/monitor/services/GetMonitoringDataService.java), [Node.js](https://github.com/docusign/code-examples-node/blob/master/lib/monitor/examples/getMonitoringData.js), [PHP](https://github.com/docusign/code-examples-php/blob/master/src/Services/Examples/Monitor/GetMonitoringDataService.php), [PowerShell](https://github.com/docusign/code-examples-powershell/blob/master/examples/Monitor/eg001GetMonitoringData.ps1), [Python](https://github.com/docusign/code-examples-python/blob/master/app/monitor/examples/eg001_get_monitoring_data.py), or [Ruby](https://github.com/docusign/code-examples-ruby/blob/master/app/services/monitor_api/eg001_get_monitoring_dataset_service.rb).

**`Bash`**

```bash title="Bash"
if date -v -10d &>/dev/null; then
    # Mac
    cursorDate=$(date -v -1y '+%Y-%m-%d')
else
    # Not a Mac
    cursorDate=$(date --date='-1 year' '+%Y-%m-%d')
fi

complete=false
cursorValue="${cursorDate}T00:00:00Z"
iterations=0

while [ $complete == false ]; do
((iterations=iterations+1))
# Create a temporary file to store the response
response=$(mktemp /tmp/response-bs.XXXXXX)
Status=$(curl -w '%{http_code}' -i --request GET "https://api-d.docusign.com/v1/organizations/${ORGANIZATION_ID}/stream?cursor=${cursorValue}&limit=2000" \
     "${Headers[@]}" \
     --output ${response})
# If the Status code returned is greater than 201 (OK / Accepted), display an error message
# along with the API response
if [[ "$Status" -gt "201" ]] ; then
    echo ""
	echo "You do not have Monitor enabled for your account, follow https://developers.docusign.com/docs/monitor-api/how-to/enable-monitor/ to get it enabled."
	echo ""
	cat $response
	exit 1
fi
# Display the data
echo ""
echo "Increment:"
echo $iterations
echo "Response:"
cat $response
echo ""
# Get the endCursor value from the response. This lets you resume
# getting records from the spot where this call left off
endCursorValue=$(sed -n 's/.*"endCursor":"\([^"]*\)".*/\1/p' $response)
echo "endCursorValue is:"
echo $endCursorValue
echo "cursorValue is:"
echo $cursorValue
echo ""
# If the endCursor from the response is the same as the one that you already have,
# it means that you have reached the end of the records
if [ "$endCursorValue" == "$cursorValue" ] ; then
    echo 'After getting records, the cursor values are the same. This indicates that you have reached the end of your available records.'
	complete=$((true))
	else
	echo 'Updating the cursor value of ' ${cursorValue} ' to the new value of ' ${endCursorValue}
	cursorValue="${endCursorValue}"
sleep 5
fi
```

**`C#`**

```csharp title="C#"
DateTime cursorDate = DateTime.UtcNow.AddDays(-1);
bool complete = false;
string cursorValue = cursorDate.ToString("yyyy-MM-dd") + "T00:00:00Z";
int limit = 2000; // Amount of records you want to read in one request
List<object> functionResult = new List<object>();

DataSetApi dataSetApi = new DataSetApi(apiClient);
GetStreamOptions options = new GetStreamOptions();

options.limit = limit;

// Get monitoring data
do
{
    if (!string.IsNullOrEmpty(cursorValue))
    {
        options.cursor = cursorValue;
    }

    var cursoredResult = dataSetApi.GetStreamWithHttpInfo("2.0", "monitor", options);

    cursoredResult.Headers.TryGetValue("X-RateLimit-Remaining", out string remaining);
    cursoredResult.Headers.TryGetValue("X-RateLimit-Reset", out string reset);

    if (reset != null && remaining != null)
    {
        DateTime resetDate = DateTimeOffset.FromUnixTimeSeconds(long.Parse(reset)).UtcDateTime;
        Console.WriteLine("API calls remaining: " + remaining);
        Console.WriteLine("Next Reset: " + resetDate);
    }

    string endCursor = cursoredResult.Data.EndCursor;

    // If the endCursor from the response is the same as the one that you already have,
    // it means that you have reached the end of the records
    if (endCursor == cursorValue)
    {
        complete = true;
    }
    else
    {
        cursorValue = endCursor;
        functionResult.Add(cursoredResult.Data);
    }
}
while (!complete);
```

**`Java`**

```java title="Java"
do {
    if (!cursorValue.isEmpty()) {
        options.setCursor(cursorValue);
    }

    LOGGER.info("options set: " + options);
    ApiResponse<CursoredResult> cursoredResult = datasetApi.getStreamWithHttpInfo("2.0", "monitor",
            options);

    Map<String, List<String>> headers = cursoredResult.getHeaders();
    List<String> remaining = headers.get("X-RateLimit-Remaining");
    List<String> reset = headers.get("X-RateLimit-Reset");

    if (remaining != null & reset != null) {
        Instant resetInstant = Instant.ofEpochSecond(Long.parseLong(reset.get(0)));
        System.out.println("API calls remaining: " + remaining);
        System.out.println("Next Reset: " + resetInstant);
    }

    LOGGER.info("cursor results " + cursoredResult.getData());
    String endCursor = cursoredResult.getData().getEndCursor();

    // If the endCursor from the response is the same as the one that you already
    // have,
    // it means that you have reached the end of the records
    if (endCursor.equals(cursorValue)) {
        complete = true;
    } else {
        cursorValue = endCursor;
        monitoringData.put(new JSONObject(cursoredResult));
    }
} while (!complete);
```

**`Node.js`**

```javascript title="Node.js"
const cursorDate = new Date();
cursorDate.setDate(cursorDate.getDate() - 1);
const limit = 2000; // Amount of records you want to read in one request
let functionResult = [];

let complete = false;
let cursorValue = cursorDate.toISOString().split('T')[0] + 'T00:00:00Z';
let cursoredResult;
const datasetApi = new docusign.DataSetApi(dsApiClient);

let options = {
  limit: limit,
};

// Get monitoring data
do {
  if (cursorValue != null) {
    options.cursor = cursorValue;
  }
  cursoredResult = await new Promise((resolve, reject) => {
    datasetApi.getStream('2.0', 'monitor', options, (err, data, response) => {
      if (err) return reject(err);
      resolve({ data, response });
    });
  });

  let headers = cursoredResult.response.headers;
  let remaining = headers['x-ratelimit-remaining'];
  let reset = headers['x-ratelimit-reset'];

  if (remaining && reset) {
    const resetInstant = new Date(Number(reset) * 1000);
    console.log(`API calls remaining: ${remaining}`);
    console.log(`Next Reset: ${resetInstant.toISOString()}`);
  }

  let endCursor = cursoredResult.data.endCursor;

  // If the endCursor from the response is the same as the one that you already have,
  // it means that you have reached the end of the records
  if (endCursor === cursorValue) {
    complete = true;
  } else {
    cursorValue = endCursor;
    if (cursoredResult.data.data.length !== 0) {
      functionResult.push(cursoredResult.data.data);
    }
  }
} while (!complete);
```

**`PHP`**

```php title="PHP"
try {
    // Get monitoring data
    $datasetApi = new DataSetApi($apiClient);
    $cursorDate = new \DateTime();
    $cursorDate->modify('-1 year');
    $cursor = $cursorDate->format('Y-m-d') . "T00:00:00Z";
    $complete = false;
    $options = new GetStreamOptions();
    $options->setLimit(2000);
    $monitoringLogs = array();

    // First call the endpoint with no cursor to get the first records.
    // After each call, save the cursor and use it to make the next
    // call from the point where the previous one left off when iterating through
    // the monitoring records
    do {
        $options->setCursor($cursor);
        $cursoredResult = $datasetApi->getStreamWithHttpInfo('monitor', '2.0', $options);

        $remaining = $cursoredResult[2]['X-RateLimit-Remaining'] ?? null;
        $reset = $cursoredResult[2]['X-RateLimit-Reset'] ?? null;

        if ($remaining !== null && $reset !== null) {
            $resetInstant = (new DateTime())->setTimestamp((int)$reset);
            error_log("API calls remaining: $remaining");
            error_log("Next Reset: " . $resetInstant->format(\DateTime::ATOM));
        }

        $key = "end_cursor";
        $endCursor = $cursoredResult[0]->$key;

        // If the endCursor from the response is the same as the one that you already have,
        // it means that you have reached the
        // end of the records
        if ($endCursor === $cursor) {
            $complete = true;
        } else {
            $cursor = $endCursor;
            array_push($monitoringLogs, json_decode($cursoredResult[0]));
        }
    } while (!$complete);
} catch (ApiException $e) {
    $clientService->showErrorTemplate($e);
    exit;
}
```

**`PowerShell`**

```text title="PowerShell"
# Set this to your organization ID (a GUID)
$organizationId = "YOUR_ORGANIZATION_ID"

DO {
   $iterations++
   Write-Output ""
   try {
      Invoke-RestMethod `
      -Uri "https://api-d.docusign.com/v1/organizations/${organizationId}/stream?cursor=${cursorValue}&limit=2000" `
      -Method 'GET' `
      -Headers @{
         'Authorization' = "Bearer $accessToken";
         'Content-Type'  = "application/json";
      } `
      -OutFile $response
      # Display the data
      Write-Output "Iteration:"
      Write-Output $iterations
      Write-Output "Results:"
      Get-Content $response
      # Get the endCursor value from the response. This lets you resume
      # getting records from the spot where this call left off
      $endCursorValue = (Get-Content $response | ConvertFrom-Json).endCursor
      Write-Output "endCursorValue is:"
      Write-Output $endCursorValue
      Write-Output "cursorValue is:"
      Write-Output $cursorValue

      # If the endCursor from the response is the same as the one that you already have,
      # it means that you have reached the
      # end of the records
      if ($endCursorValue -eq $cursorValue) {
        Write-Output 'After getting records, the cursor values are the same. This indicates that you have reached the end of your available records.'
        $complete=$true
      }
      else {
        Write-Output "Updating the cursor value of $cursorValue to the new value of $endCursorValue"
        $cursorValue=$endCursorValue
        Start-Sleep -Second 5
      }
   }
   catch {
      $int = 0
      foreach($header in $_.Exception.Response.Headers) {
        if ($header -eq "X-DocuSign-TraceToken") {
          Write-Output "TraceToken : " $_.Exception.Response.Headers[$int]
	}
        $int++
      }
      Write-Output "You do not have Monitor enabled for your account, follow https://developers.docusign.com/docs/monitor-api/how-to/enable-monitor/ to get it enabled."
      Write-Output "Command : "$_.InvocationInfo.Line
      $complete = $true
   }

} While ($complete -eq $false )
```

**`Python`**

```python title="Python"
cursor_date = dt.now(timezone.utc).replace(year=dt.now(timezone.utc).year - 1)
dataset_api = DataSetApi(api_client=api_client)

cursor_value = cursor_date.strftime('%Y-%m-%dT00:00:00Z')
limit = 2000
function_results = []
complete = False

while not complete:
    (cursored_results, status, headers) = dataset_api.get_stream_with_http_info(
        data_set_name="monitor",
        version="2.0",
        limit=limit,
        cursor=cursor_value
    )

    remaining = headers.get("X-RateLimit-Remaining")
    reset = headers.get("X-RateLimit-Reset")

    if remaining is not None and reset is not None:
        reset_date = dt.fromtimestamp(int(reset), tz=timezone.utc)
        print(f"API calls remaining: {remaining}")
        print(f"Next Reset: {reset_date}")

    end_cursor = cursored_results.end_cursor

    if end_cursor == cursor_value:
        complete = True
    else:
        cursor_value = end_cursor
        function_results.append(cursored_results.data)
```

**`Ruby`**

```ruby title="Ruby"
monitor_api = DocuSign_Monitor::DataSetApi.new(api_client)
begin
  cursor_date = Date.today.prev_day
  cursor_value = cursor_date.strftime('%Y-%m-%dT00:00:00Z')
  limit = 2000
  function_results = []
  options = DocuSign_Monitor::GetStreamOptions.new
  options.limit = limit

  loop do
    options.cursor = cursor_value unless cursor_value.empty?

    cursored_results, _status, headers = monitor_api.get_stream_with_http_info(args[:data_set_name], args[:version], options)

    remaining = headers['X-RateLimit-Remaining']
    reset = headers['X-RateLimit-Reset']

    if remaining && reset
      reset_date = Time.at(reset.to_i).utc
      puts "API calls remaining: #{remaining}"
      puts "Next Reset: #{reset_date}"
    end

    end_cursor = cursored_results.end_cursor

    break if cursor_value == end_cursor

    cursor_value = end_cursor
    function_results.push(cursored_results.data)
  end
  @response = function_results
```

## Expected response

If your API call is successful, you should see a JSON response similar to this.

The sample response shows only the results of the final three query loops; the first loops (and the body of the data returned) are omitted due to lack of space. You can see the structure of the returned JSON in [Tracking data and handling alerts](/docs/monitor-api/monitor101/tracking-data-handling-alerts).

**`Sample response`**

```json title="Sample response"
<Responses for the first 3 loops are displayed here. Only the final loops are
displayed in this example response>
Increment:
3
Response:
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
Strict-Transport-Security: max-age=5184000; includeSubDomains; preload
api-supported-versions: 2.0
X-DocuSign-TraceToken: a778d0c4-xxxx-xxxx-xxxx-c676ed038c22
X-DocuSign-Node: SE4DFE181
Date: Thu, 29 Oct 2020 20:29:13 GMT
Strict-Transport-Security: max-age=15768000
{"resultData":[{EVENT/ALERT DATA HERE}],"endCursor":"aa_637395998467230467_637395997844343970_195"}
endCursorValue is:
aa_637395998467230467_637395997844343970_195
cursorValue is:
aa_637395449927163968_637395449443454544_380
Updating the cursor value of  aa_637395449927163968_637395449443454544_380  to the new value of  aa_637395998467230467_637395997844343970_195
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    68    0    68    0     0    111      0 --:--:-- --:--:-- --:--:--   111
Increment:
4
Response:
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
Strict-Transport-Security: max-age=5184000; includeSubDomains; preload
api-supported-versions: 2.0
X-DocuSign-TraceToken: 081e2182-xxxx-xxxx-xxxx-2da9af39aaea
X-DocuSign-Node: DA3DFE177
Date: Thu, 29 Oct 2020 20:29:20 GMT
Strict-Transport-Security: max-age=15768000
{"resultData":[],"endCursor":"aa_637395998467230467_637395997844343970_0"}
endCursorValue is:
aa_637395998467230467_637395997844343970_0
cursorValue is:
aa_637395998467230467_637395997844343970_195
Updating the cursor value of  aa_637395998467230467_637395997844343970_195  to the new value of  aa_637395998467230467_637395997844343970_0
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    68    0    68    0     0    129      0 --:--:-- --:--:-- --:--:--   129
Increment:
5
Response:
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
Strict-Transport-Security: max-age=5184000; includeSubDomains; preload
api-supported-versions: 2.0
X-DocuSign-TraceToken: 90a45fef-xxxx-xxxx-xxxx-d24725ecf21b
X-DocuSign-Node: DA3DFE177
Date: Thu, 29 Oct 2020 20:29:26 GMT
Strict-Transport-Security: max-age=15768000
{"resultData":[],"endCursor":"aa_637395998467230467_637395997844343970_0"}
endCursorValue is:
aa_637395998467230467_637395997844343970_0
cursorValue is:
aa_637395998467230467_637395997844343970_0
After getting records, the cursor values are the same. This indicates that you have reached the end of your available records.
Done.
```

## Next steps

* Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects:    [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).
* Learn the context of getting [tracking data](/docs/monitor-api/monitor101/tracking-data-handling-alerts).
* Find out more about [Docusign Monitor Authentication](/docs/monitor-api/monitor101/auth).
* See [Best practices for handling alerts](/docs/monitor-api/monitor101/best-practices-handling-alerts).
* See [Go-Live](/docs/monitor-api/go-live) to see the Monitor API endpoint base path for the production environment.