# Create New Datasource

Endpoint Name: `insertdatasource`

Request type : `POST`

Authorization: Bearer token as header

Endpoint Details: The `insertdatasource` endpoint will be used to create new datasource.

<table data-header-hidden><thead><tr><th width="116"></th><th></th></tr></thead><tbody><tr><td>Method</td><td>URL</td></tr><tr><td>POST</td><td><code>URL/access/klearstack/insertdatasource</code></td></tr></tbody></table>

### Request Body

<table data-header-hidden><thead><tr><th width="185"></th><th width="144"></th><th></th></tr></thead><tbody><tr><td>Params</td><td>Values</td><td>Description</td></tr><tr><td>datasource_name</td><td>string</td><td>Name of the datasource</td></tr><tr><td>company_name</td><td>string</td><td>Name of the company for which the user is logging in</td></tr><tr><td>data</td><td>string(JSON)</td><td><p>A valid JSON string containing info about Datasource to be created. It contains info about which columns to create and datatype of those columns</p><p>Example:</p><p>{</p><p>"DataSourceName": "test ",</p><p>"DataSourceType": "excel_or_csv",</p><p>"DataSourceStatus": true,</p><p>"fields": [{</p><p>"name": "USER_FIRST_NAME",</p><p>"datatype": "string"</p><p>}, {</p><p>"name": "email",</p><p>"datatype": "string"</p><p>}]</p><p>}</p></td></tr><tr><td>dataset</td><td>Binary</td><td>Excel or CSV file containing data for datasource.</td></tr></tbody></table>

### Shell (cURL)

* Request Body

```bash
curl --location POST "URL/access/klearstack/insertdatasource" \
  --header "Authorization: Bearer your_token_here" \
  --form "datasource_name=Replace_Datasource_Name_Here" \
  --form "company_name=Replace_Company_Name_Here" \
  --form 'data={
    "DataSourceName": "test",
    "DataSourceType": "excel_or_csv",
    "DataSourceStatus": true,
    "fields": [
      {"name": "USER_FIRST_NAME", "datatype": "string"},
      {"name": "email", "datatype": "string"}
    ]
  }' \
  --form "dataset=@/path/to/your/file.csv"
```

### Python

* Request Body

```python
import requests

# API URL
url = "URL/access/klearstack/insertdatasource"

# Request payload (JSON data)
data_payload = {
    "DataSourceName": "test",
    "DataSourceType": "excel_or_csv",
    "DataSourceStatus": True,
    "fields": [
        {"name": "USER_FIRST_NAME", "datatype": "string"},
        {"name": "email", "datatype": "string"}
    ]
}

# Files to upload
files = {
    "dataset": ("file.csv", open("path/to/your/file.csv", "rb"), "text/csv")
}

# Form data
form_data = {
    "datasource_name": "Replace_Datasource_Name_Here",
    "company_name": "Replace_Company_Name_Here",
    "data": str(data_payload)  # JSON needs to be converted to string
}

# Headers
headers = {
    "Authorization": "Bearer your_token_here"
}

# Make the POST request
response = requests.post(url, data=form_data, files=files, headers=headers)

# Print the response
if response.status_code == 200:
    print(response.json())
else:
    print("Error:", response.text)
```

### Java

* Request Body

```java
import okhttp3.*;
import java.io.File;
import java.io.IOException;

public class InsertDatasourceAPI {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        // JSON payload
        String jsonPayload = "{ \"DataSourceName\": \"test\", " +
                "\"DataSourceType\": \"excel_or_csv\", " +
                "\"DataSourceStatus\": true, " +
                "\"fields\": [" +
                "{ \"name\": \"USER_FIRST_NAME\", \"datatype\": \"string\" }," +
                "{ \"name\": \"email\", \"datatype\": \"string\" }]" +
                "}";

        // File to upload
        File file = new File("path/to/your/file.csv");

        RequestBody fileBody = RequestBody.create(file, MediaType.parse("text/csv"));
        RequestBody formBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("datasource_name", "Replace_Datasource_Name_Here")
                .addFormDataPart("company_name", "Replace_Company_Name_Here")
                .addFormDataPart("data", jsonPayload)
                .addFormDataPart("dataset", file.getName(), fileBody)
                .build();

        Request request = new Request.Builder()
                .url("URL/access/klearstack/insertdatasource")
                .post(formBody)
                .addHeader("Authorization", "Bearer your_token_here")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                System.out.println("Response: " + response.body().string());
            } else {
                System.out.println("Error: " + response.body().string());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```

### Node.js

* Request Body

```javascript
var request = require('request');
var fs = require('fs');

const form_data = {
  'datasource_name': 'Replace_Datasource_Name_Here',
  'company_name': 'Replace_Company_Name_Here',
  'data': JSON.stringify({
    "DataSourceName": "test",
    "DataSourceType": "excel_or_csv",
    "DataSourceStatus": true,
    "fields": [
      { "name": "USER_FIRST_NAME", "datatype": "string" },
      { "name": "email", "datatype": "string" }
    ]
  }),
  'dataset': fs.createReadStream('path/to/your/file.csv')
};

const options = {
  url: 'URL/access/klearstack/insertdatasource',
  formData: form_data,
  headers: {
    'Authorization': 'Bearer your_token_here'
  }
};

request.post(options, function(err, httpResponse, body) {
  if (err) {
    console.error('Request failed:', err);
    return;
  }

  console.log('Response:', body);
});
```

### JavaScript (XMLHttpRequest)

* Request Body

```javascript
var formData = new FormData();
formData.append("datasource_name", "Replace_Datasource_Name_Here");
formData.append("company_name", "Replace_Company_Name_Here");
formData.append("data", JSON.stringify({
    "DataSourceName": "test",
    "DataSourceType": "excel_or_csv",
    "DataSourceStatus": true,
    "fields": [
        { "name": "USER_FIRST_NAME", "datatype": "string" },
        { "name": "email", "datatype": "string" }
    ]
}));

var fileInput = document.createElement("input");
fileInput.type = "file";
fileInput.accept = ".csv, .xlsx";
fileInput.addEventListener("change", function () {
    var file = fileInput.files[0];
    formData.append("dataset", file);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "URL/access/klearstack/insertdatasource", true);
    xhr.setRequestHeader("Authorization", "Bearer your_token_here");

    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                console.log("Response:", xhr.responseText);
            } else {
                console.error("Error:", xhr.responseText);
            }
        }
    };

    xhr.send(formData);
});

document.body.appendChild(fileInput);
```

### API Response

<table data-header-hidden><thead><tr><th width="147"></th><th></th></tr></thead><tbody><tr><td>Status code</td><td>Example Response</td></tr><tr><td>200</td><td><p><code>{</code></p><p>    <code>"success": true,</code></p><p>    <code>“release_version”:”7.8.9”</code></p><p><code>}</code></p></td></tr><tr><td>400</td><td><p><code>{</code></p><p>    <code>"error": "Datasource Name already exists"</code></p><p><code>}</code></p></td></tr></tbody></table>
