# Javascript Client For Nutanix Networking APIs

The Javascript client for Nutanix Networking APIs is designed for Javascript client application developers offering them simple and flexible access to APIs that manage networking configuration on Nutanix clusters, including AHV and advanced networking.
## Features
- Invoke Nutanix APIs with a simple interface.
- Handle Authentication seamlessly.
- Reduce boilerplate code implementation.
- Use standard methods for installation.
## Version
- API version: v4.1
- Package version: 4.1.1

## Requirements.
Node.JS 14, 15, 16, 17 and 18 are fully supported and tested.

## Installation & Usage

### Installation

This library is distributed on npm. In order to add it as a dependency, run the following command:

```shell
$ npm install @nutanix-api/networking-js-client
```

## Configuration
The javascript client for Nutanix Networking APIs can be configured with the following parameters

| Parameter | Description                                                                     | Required  | Default Value|
|-----------|---------------------------------------------------------------------------------|---------- |--------------|
| scheme    | URI scheme for connecting to the cluster (HTTP or HTTPS using SSL/TLS)          | No        | https        |
| host      | IPv4/IPv6 address or FQDN of the cluster to which the client will connect to    | Yes       | N/A          |
| port      | Port on the cluster to which the client will connect to                         | No        | 9440         |
| username  | Username to connect to a cluster                                                | Yes       | N/A          |
| password  | Password to connect to a cluster                                                | Yes       | N/A          |
| debug     | Runs the client in debug mode if specified                                      | No        | False        |
| verifySsl | Verify SSL certificate of cluster, the client will connect to                   | No        | True         |
| maxRetryAttempts| Maximum number of retry attempts while connecting to the cluster          | No        | 5            |
| retryInterval| Interval in milliseconds at which retry attempts are made                    | No        | 3000         |
| maxRedirects | Maximum number of redirects to follow                                        | No        | 10           |
| loggerFile | File location to which debug logs are written to                               | No        | N/A          |
| connectTimeout | Connection timeout in milliseconds for all operations                      | No        | 30000        |
| readTimeout | Read timeout in milliseconds for all operations                               | No        | 30000        |
| withCredentials | Cross-site Access-Control requests should be made using auth credentials  | No        | False        |

This module can be used in the CommonJS (CJS) , ECMAScript6(ES6) and  Universal Module Definition(UMD) syntax
While using the module in browser frameworks like React or Vue.JS , you can use import/export. Older Node.js versions can continue to use the require ().

For CommonJs:
```javascript
const sdk = require("@nutanix-api/networking-js-client");
let client = new sdk.ApiClient();
```

For ES6 modules:
```javascript
import ApiClient from "@nutanix-api/networking-js-client";
```

### Sample Configuration
```javascript
import ApiClient from "@nutanix-api/networking-js-client";

let client = new ApiClient();
client.host = '10.19.50.27'; // IPv4/IPv6 address or FQDN of the cluster
client.port = 9440; // Port to which to connect to
client.username = 'admin'; // UserName to connect to the cluster
client.password = 'password'; // Password to connect to the cluster
```

### Authentication
Nutanix APIs currently support two type of authentication schemes:

- **HTTP Basic Authentication**
      - The Javascript client can be configured using the username and password parameters to send Basic headers along with every request.
- **API Key Authentication**
      - The Javascript client can be configured to set an API key to send "**X-ntnx-api-key**" header with every request.
  ```javascript
  import ApiClient from "@nutanix-api/networking-js-client";

  let client = new ApiClient();
  client.setApiKey('abcde12345');
  ```



### Retry Mechanism
The client can be configured to retry requests that fail with the following status codes. The numbers of seconds before which the next retry is attempted is determined by the retryInterval:

- [408 - Request Timeout](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408)
- [429 - Too Many Requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429)
- [502 - Bad Gateway](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502)
- [503 - Service Unavailable](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503)

The client will also redirect requests that fail with [302 - Found](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302) to the new location specified in the response header `Location`.
```javascript
import ApiClient from "@nutanix-api/networking-js-client";

let client = new ApiClient();
client.maxRetryAttempts = 5 // Max retry attempts while reconnecting on a loss of connection
client.retryInterval = 5000 // Interval in ms to use during retry attempts
client.maxRedirects = 3  // Max number of redirects to follow
```

## Usage

### Invoking an operation
```javascript
// this sample code is not usable directly for real use-case

import { ApiClient, SampleApi }  from "@nutanix-api/networking-js-client";
// Configure the client
// ...
let client = new ApiClient();
// Initialize the API
let sampleApi = new SampleApi(client);
const extId = '66673023168b486898d76bc27e5ce9c2'
// Get a sample group by UUID.

sampleApi.getSampleByExtId(extId).then(({data, response}) => {
    console.log(`API returned the following status code: ${response.status}`);
}).catch((err) =>  {
    console.log(`Error is: ${err}`);
});
```

### Request Options
The library provides the ability to specify additional options that can be applied directly on the 'ApiClient' object used to make network calls to the API. The library also provides a mechanism to specify operation specific headers.
#### Client headers
The 'ApiClient' can be configured to send additional headers on each request.

```javascript
import ApiClient from "@nutanix-api/networking-js-client";

let client = new ApiClient();
client.addDefaultHeader('Accept-Encoding','gzip, deflate, br');
```
You can also modify the headers sent with each individual operation:

#### Operation specific headers
Nutanix APIs require that concurrent updates are protected using [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) headers. This would mean that the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header received in the response of a fetch (GET) operation should be used as an [If-Match](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match) header for the modification (PUT) operation.
```javascript
// this sample code is not usable directly for real use-case

import { ApiClient, SampleApi } from "@nutanix-api/networking-js-client";
// Configure the client
// ...
let client = new ApiClient();
// Initialize the API
let sampleApi = new SampleApi(client);
const extId = '66673023168b486898d76bc27e5ce9c2'
// Get a sample group by UUID.
sampleApi.getSampleByExtId(extId).then(({data, response}) => {
console.log(`API returned the following status code: ${response.status}`);
// Extract E-Tag Header
let etagValue = ApiClient.getEtag(data)
let body = data.getData();
// initialize/change parameters for update
// Update a given sample by UUID.
sampleApi.updateSampleByExtId(extId, body, {"If-Match" : etagValue}).then(({data, response}) => {
    console.log(`API returned the following status code: ${response.status}`);
}).catch((err) => {
    console.log(`Error is: ${err}`);
});
```

### List Operations
List Operations for Nutanix APIs support pagination, filtering, sorting and projections. The table below details the parameters that can be used to set the options for pagination etc.

| Parameter | Description
|-----------|----------------------------------------------------------------------------------|
| $page     | specifies the page number of the result set. Must be a positive integer between 0 and the maximum number of pages that are available for that resource. Any number out of this range will lead to no results being returned.|
| $limit    | specifies the total number of records returned in the result set. Must be a positive integer between 0 and 100. Any number out of this range will lead to a validation error. If the limit is not provided a default value of 50 records will be returned in the result set|
| $filter   | allows clients to filter a collection of resources. The expression specified with $filter is evaluated for each resource in the collection, and only items where the expression evaluates to true are included in the response. Expression specified with the $filter must conform to the [OData V4.01 URL](https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html#sec_SystemQueryOptionfilter) conventions. |
| $orderby  | allows clients to specify the sort criteria for the returned list of objects. Resources can be sorted in ascending order using asc or descending order using desc. If asc or desc are not specified the resources will be sorted in ascending order by default. For example, 'orderby=templateName desc' would get all templates sorted by templateName in desc order. |
| $select   | allows clients to request a specific set of properties for each entity or complex type. Expression specified with the $select must conform to the OData V4.01 URL conventions. If a $select expression consists of a single select item that is an asterisk (i.e., *), then all properties on the matching resource will be returned. |
| $expand   | allows clients to request related resources when a resource that satisfies a particular request is retrieved. Each expanded item is evaluated relative to the entity containing the property being expanded. Other query options can be applied to an expanded property by appending a semicolon-separated list of query options, enclosed in parentheses, to the property name. Permissible system query options are $filter,$select and $orderby. |

List Options can be passed to list operations in order to perform pagination, filtering etc.
```javascript
import { ApiClient, AwsSubnetsApi }  from "@nutanix-api/networking-js-client";
// Configure the client
// ...
let client = new ApiClient();
// Initialize the API
let awsSubnetsApi = new AwsSubnetsApi(client);

//Construct List Options
var listOptions = new Object();
listOptions.$page = 0;
listOptions.$limit = 50;
listOptions.$filter = "string_sample_data";
listOptions.$orderby = "string_sample_data";
listOptions.$select = "string_sample_data";

awsSubnetsApi.listAwsSubnets(listOptions).then(({data, response}) => {
    console.log(`API returned the following status code: ${response.status}`);
}).catch((err) =>  {
    console.log(`Error is: ${err}`);
});

```

The list of filterable and sortable fields with expansion keys can be found in the documentation [here](https://developers.nutanix.com/).

## API Reference

This library has a full set of [API Reference Documentation](https://developers.nutanix.com/sdk-reference?namespace=networking&version=v4.1&language=javascript). This documentation is auto-generated, and the location may change.

## License
This library is licensed under Apache 2.0 license. Full license text is available in [LICENSE](https://www.apache.org/licenses/LICENSE-2.0.txt).

## Contact us
In case of issues please reach out to us at the [mailing list](mailto:sdk@nutanix.com)