> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usedatabrain.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Delete Datasource

> Delete a datasource from your organization. This action cannot be undone and will remove all associated configurations.

Permanently delete a datasource from your organization. This will remove the datasource and all its associated configurations, including cached schemas.

<Danger>
  This action is irreversible. Once a datasource is deleted, all its configurations and cached schemas will be permanently removed. Ensure no datamarts or other resources depend on this datasource before deletion.
</Danger>

## Endpoint

```
DELETE https://api.usedatabrain.com/api/v2/datasource?datasourceName={name}
```

## Self-hosted Databrain Endpoint

```
DELETE <SELF_HOSTED_URL>/api/v2/datasource?datasourceName={name}
```

## Authentication

This endpoint requires a service token in the Authorization header. Service tokens differ from data app API keys and provide organization-level permissions.

To access your service token:

1. In **Settings** page, navigate to the **Service Tokens** section.
2. Click the **"Generate Token"** button to create a new service token if you don't have one already.

<Panel>
  <RequestExample>
    ```bash Authentication theme={"dark"}
    curl --request DELETE \
      --url 'https://api.usedatabrain.com/api/v2/datasource?datasourceName=production-postgres' \
      --header 'Authorization: Bearer dbn_live_...'
    ```
  </RequestExample>
</Panel>

## Headers

<ParamField header="Authorization" type="string" required>
  Bearer token for API authentication. Use your service token.

  ```
  Authorization: Bearer dbn_live_abc123...
  ```
</ParamField>

## Query Parameters

<ParamField query="datasourceName" type="string" required>
  The name of the datasource to delete. Must match exactly as it was created.

  <Expandable title="Finding datasource names">
    * Use the [List Datasources API](/developer-docs/helpers/api-reference/list-datasources) to get all datasource names
    * Check the response from datasource creation
    * Available in the DataBrain dashboard when viewing datasources
  </Expandable>
</ParamField>

## Response

<ResponseField name="id" type="string">
  The ID of the deleted datasource for confirmation.
</ResponseField>

<ResponseField name="message" type="string">
  Success message confirming the deletion: "Datasource deleted successfully".
</ResponseField>

<ResponseField name="error" type="null">
  Error field, null when successful. Not included in successful responses.
</ResponseField>

## Examples

<Panel>
  <RequestExample>
    ```bash cURL theme={"dark"}
    curl --request DELETE \
      --url 'https://api.usedatabrain.com/api/v2/datasource?datasourceName=production-postgres' \
      --header 'Authorization: Bearer dbn_live_abc123...'
    ```

    ```javascript Node.js theme={"dark"}
    const datasourceName = 'production-postgres';
    const response = await fetch(
      `https://api.usedatabrain.com/api/v2/datasource?datasourceName=${encodeURIComponent(datasourceName)}`,
      {
        method: 'DELETE',
        headers: {
          'Authorization': 'Bearer dbn_live_abc123...'
        }
      }
    );

    const data = await response.json();
    if (data.error) {
      console.error('Error:', data.error);
    } else {
      console.log('Deleted datasource:', data.id);
      console.log('Message:', data.message);
    }
    ```

    ```python Python theme={"dark"}
    import requests

    url = "https://api.usedatabrain.com/api/v2/datasource"
    headers = {
        "Authorization": "Bearer dbn_live_abc123..."
    }
    params = {
        "datasourceName": "production-postgres"
    }

    response = requests.delete(url, headers=headers, params=params)
    data = response.json()

    if data.get('error'):
        print('Error:', data['error'])
    else:
        print(f"Deleted datasource: {data['id']}")
        print(f"Message: {data['message']}")
    ```

    ```ruby Ruby theme={"dark"}
    require 'net/http'
    require 'json'
    require 'uri'

    uri = URI('https://api.usedatabrain.com/api/v2/datasource')
    params = { datasourceName: 'production-postgres' }
    uri.query = URI.encode_www_form(params)

    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true

    request = Net::HTTP::Delete.new(uri)
    request['Authorization'] = 'Bearer dbn_live_abc123...'

    response = http.request(request)
    data = JSON.parse(response.body)

    if data['error']
      puts "Error: #{data['error']}"
    else
      puts "Deleted datasource: #{data['id']}"
      puts "Message: #{data['message']}"
    end
    ```

    ```java Java theme={"dark"}
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    import java.net.URI;
    import java.net.URLEncoder;
    import java.nio.charset.StandardCharsets;

    public class DataBrainDeleteDatasourceAPI {
        public static void main(String[] args) throws Exception {
            HttpClient client = HttpClient.newHttpClient();
            
            String datasourceName = URLEncoder.encode("production-postgres", StandardCharsets.UTF_8);
            String url = String.format(
                "https://api.usedatabrain.com/api/v2/datasource?datasourceName=%s",
                datasourceName
            );
            
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer dbn_live_abc123...")
                .DELETE()
                .build();
                
            HttpResponse<String> response = client.send(request, 
                HttpResponse.BodyHandlers.ofString());
                
            System.out.println("Response: " + response.body());
        }
    }
    ```

    ```go Go theme={"dark"}
    package main

    import (
        "encoding/json"
        "fmt"
        "net/http"
        "net/url"
    )

    type DeleteDatasourceResponse struct {
        Id      string      `json:"id"`
        Message string      `json:"message"`
        Error   interface{} `json:"error"`
    }

    func main() {
        baseURL := "https://api.usedatabrain.com/api/v2/datasource"
        params := url.Values{}
        params.Add("datasourceName", "production-postgres")
        
        fullURL := fmt.Sprintf("%s?%s", baseURL, params.Encode())
        
        req, _ := http.NewRequest("DELETE", fullURL, nil)
        req.Header.Set("Authorization", "Bearer dbn_live_abc123...")
        
        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            panic(err)
        }
        defer resp.Body.Close()
        
        var datasourceResp DeleteDatasourceResponse
        json.NewDecoder(resp.Body).Decode(&datasourceResp)
        
        if datasourceResp.Error != nil {
            fmt.Printf("Error: %v\n", datasourceResp.Error)
        } else {
            fmt.Printf("Deleted datasource: %s\n", datasourceResp.Id)
            fmt.Printf("Message: %s\n", datasourceResp.Message)
        }
    }
    ```

    ```php PHP theme={"dark"}
    <?php
    $params = http_build_query([
        'datasourceName' => 'production-postgres'
    ]);

    $url = 'https://api.usedatabrain.com/api/v2/datasource?' . $params;

    $options = [
        'http' => [
            'header' => 'Authorization: Bearer dbn_live_abc123...',
            'method' => 'DELETE'
        ]
    ];

    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    $response = json_decode($result, true);

    if (isset($response['error'])) {
        echo "Error: " . json_encode($response['error']);
    } else {
        echo "Deleted datasource: " . $response['id'] . "\n";
        echo "Message: " . $response['message'];
    }
    ?>
    ```
  </RequestExample>

  <ResponseExample>
    ```json Success Response theme={"dark"}
    {
      "id": "uuid-of-deleted-datasource",
      "message": "Datasource deleted successfully"
    }
    ```

    ```json Error Response (400) theme={"dark"}
    {
      "error": {
        "code": "INVALID_REQUEST_BODY",
        "message": "Invalid datasource name",
        "status": 400
      }
    }
    ```

    ```json Error Response (400) - Datasource Not Found theme={"dark"}
    {
      "error": {
        "code": "DATASOURCE_NAME_ERROR",
        "message": "Invalid datasource name",
        "status": 400
      }
    }
    ```

    ```json Error Response (400) - Datasource In Use theme={"dark"}
    {
      "error": {
        "code": "DATASOURCE_IN_USE",
        "message": "Cannot delete datasource as it is being used by other resources",
        "status": 400
      }
    }
    ```

    ```json Error Response (401) theme={"dark"}
    {
      "error": {
        "code": "AUTHENTICATION_ERROR",
        "message": "AUTHENTICATION_ERROR",
        "status": 401
      }
    }
    ```
  </ResponseExample>
</Panel>

## Error Codes

| Error Code              | HTTP Status | Description                                 |
| ----------------------- | ----------- | ------------------------------------------- |
| `INVALID_REQUEST_BODY`  | 400         | Missing or invalid datasourceName parameter |
| `DATASOURCE_NAME_ERROR` | 400         | Datasource not found                        |
| `DATASOURCE_IN_USE`     | 400         | Datasource is being used by other resources |
| `AUTHENTICATION_ERROR`  | 401         | Invalid or missing service token            |
| `INTERNAL_SERVER_ERROR` | 500         | Server error occurred                       |

## Next Steps

<CardGroup cols={2}>
  <Card title="Create Datasource" icon="plus" href="/developer-docs/helpers/api-reference/create-datasource">
    Create a new datasource to replace the deleted one
  </Card>

  <Card title="List Datasources" icon="list" href="/developer-docs/helpers/api-reference/list-datasources">
    View all remaining datasources in your organization
  </Card>

  <Card title="Update Datasource" icon="edit" href="/developer-docs/helpers/api-reference/update-datasource">
    Update datasource credentials instead of deleting
  </Card>

  <Card title="Create Datamart" icon="database" href="/developer-docs/helpers/api-reference/create-datamart">
    Create datamarts using your remaining datasources
  </Card>
</CardGroup>
