# Create a new connection

`POST /api/2/connections`

Creates the connection defined in the JSON body.
The ID of the connection will be **generated** by the backend. Any `ID` specified in the request body is therefore
prohibited.
Supported connection types are `amqp-091`, `amqp-10`, `mqtt`, `mqtt-5`, `kafka`, `hono` and `http-push`.

Authentication (security requirement alternatives):

```json
[
  {
    "DevOpsBasic": []
  },
  {
    "DevOpsBearer": []
  }
]
```

- DevOpsBasic: http (basic). Eclipse Ditto devops user (devops) + password (foobar)
- DevOpsBearer: http (bearer). A JSON Web Token issued by a supported OAuth 2.0 Identity Provider for the Eclipse Ditto devops user.

Parameters:

- `dry-run` (query, boolean, optional) - When set to true, the request will not try to create the connection, but only try to connect it.
You can use this parameter to verify that the given connection is able to communicate with your external
system.
  Type: boolean

Request body: application/json (required)

The example below shows a connection to Eclipse Hono.

Type: NewConnection

Schema: [NewConnection](https://sourcey-ditto.pages.dev/http-api-doc/models/newconnection.md)

- `name` (optional)
  Type: string
  
  The name of the connection

- `connectionType` (required)
  Reference: [ConnectionType](https://sourcey-ditto.pages.dev/http-api-doc/models/connectiontype.md); Type: ConnectionType
  
  The type of a connection
  
  enum: ["amqp-091","amqp-10","http-push","mqtt","mqtt-5","kafka,","hono"]

- `connectionStatus` (required)
  Reference: [ConnectivityStatus](https://sourcey-ditto.pages.dev/http-api-doc/models/connectivitystatus.md); Type: ConnectivityStatus
  
  The status of a connection or resource
  
  enum: ["open","closed","failed","misconfigured","unknown"]

- `uri` (required)
  Type: string
  
  The URI of the connection

- `sources` (required)
  Reference: [Sources](https://sourcey-ditto.pages.dev/http-api-doc/models/sources.md); Type: Array<Source>
  
  The subscription sources of this connection
  
  uniqueItems: true

- `targets` (required)
  Reference: [Targets](https://sourcey-ditto.pages.dev/http-api-doc/models/targets.md); Type: Array<Target>
  
  The publish targets of this connection
  
  uniqueItems: true

- `specificConfig` (optional)
  Type: object
  
  Configuration which is only applicable for a specific connection type

- `clientCount` (optional)
  Type: number
  
  How many clients on different cluster nodes should establish the connection

- `failoverEnabled` (optional)
  Type: boolean
  
  Whether or not failover is enabled for this connection

- `validateCertificates` (optional)
  Type: boolean
  
  Whether or not to validate server certificates on connection establishment

- `mappingDefinitions` (optional)
  Reference: [PayloadMappingDefinitions](https://sourcey-ditto.pages.dev/http-api-doc/models/payloadmappingdefinitions.md); Type: PayloadMappingDefinitions
  
  List of mapping definitions where the key represents the ID of each mapping that can be used in sources and
  targets to reference a mapping.

- `mappingContext` (optional)
  Reference: [MappingContext](https://sourcey-ditto.pages.dev/http-api-doc/models/mappingcontext.md); Type: MappingContext
  
  MappingContext to apply in this connection containing JavaScript scripts mapping from external messages to
  internal Ditto Protocol messages. Usage of MappingContext is deprecated, use PayloadMappingDefinitions instead.
  
  deprecated: true

- `sshTunnel` (optional)
  Type: object
  
  The configuration of a local SSH port forwarding used to tunnel the connection to the actual endpoint.
  
  - `enabled` (required)
    Type: boolean
    
    Whether the tunnel is enabled
    
    Example:
    
    ```json
    true
    ```
  
  - `uri` (required)
    Type: string
    
    The URI of the SSH host in the format `ssh://[host]:[port]`.
    
    Example:
    
    ```json
    "ssh://some.host:2222"
    ```
  
  - `credentials` (required)
    Type: object
    
    The credentials used to authenticate at the SSH host. Password and public key authentication are supported.
    
    - `type` (required)
      Type: string
      
      The type of credentials used to authenticate. Either `password` or `public-key`.
      
      enum: ["password","public-key"]
      
      Example:
      
      ```json
      "password"
      ```
    
    - `username` (required)
      Type: string
      
      The username used for the authentication.
      
      Example:
      
      ```json
      "user42"
      ```
    
    - `password` (optional)
      Type: string
      
      The password used for authentication when credentials type `password` is used.
      
      Example:
      
      ```json
      "secret!"
      ```
    
    - `publicKey` (optional)
      Type: string
      
      Public key in PEM base64-encoded format using X.509 syntax. This field is required for credentials type
      `public-key`.
      
      Example:
      
      ```json
      "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----\n"
      ```
    
    - `privateKey` (optional)
      Type: string
      
      Private key in PEM base64-encoded format using PKCS #8 syntax. This field is required for credentials type
      `public-key`.
      
      Example:
      
      ```json
      "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
      ```
  
  - `validateHost` (optional)
    Type: boolean
    
    Whether the SSH host is validated using the provided fingerprints.
    
    Example:
    
    ```json
    true
    ```
  
  - `knownHosts` (optional)
    Type: Array<string>
    
    A list of accepted public key fingerprints. One of these fingerprints must match the fingerprint 
    of the public key the SSH host provides.
    
    Example:
    
    ```json
    [
      "MD5:e0:3a:34:1c:68:ed:c6:bc:7c:ca:a8:67:c7:45:2b:19"
    ]
    ```
    
    Items:
      Type: string
      
      The fingerprint is in the format which the command line tool `ssh-keygen` produces,
      e.g. `MD5:e0:3a:34:1c:68:ed:c6:bc:7c:ca:a8:67:c7:45:2b:19`. The fingerprint is prefixed with the hash algorithm
      used to calculate the fingerprint. Supported algorithms are `MD5`, `SHA1`, `SHA224`, `SHA256`, `SHA384` and `SHA512`.

- `tags` (optional)
  Type: Array<string>
  
  The tags of the connection
  
  Items:
    Type: string

```json
{
  "name": "hono-example-connection-123",
  "connectionType": "hono",
  "connectionStatus": "open",
  "sources": [
    {
      "addresses": [
        "telemetry",
        "event",
        "..."
      ],
      "authorizationContext": [
        "ditto:inbound-auth-subject",
        "..."
      ],
      "consumerCount": 1,
      "enforcement": {
        "input": "{{ header:device_id }}",
        "filters": [
          "{{ thing:id }}"
        ]
      },
      "payloadMapping": [
        "Ditto",
        "status"
      ]
    }
  ],
  "targets": [
    {
      "address": "command",
      "topics": [
        "_/_/things/twin/events"
      ],
      "authorizationContext": [
        "ditto:outbound-auth-subject",
        "..."
      ],
      "headerMapping": {}
    }
  ]
}
```

Responses:

- 200: Will be returned when a dry-run succeeded (see description of the dry-run query parameter for further
information).

- 201: The connection was successfully created.

Content type: application/json

Type: object & NewConnection

Schema: [Connection](https://sourcey-ditto.pages.dev/http-api-doc/models/connection.md)

allOf:
  Type: object
  
  - `id` (optional)
    Type: string
    
    The generated unique identifier of the connection

  Reference: [NewConnection](https://sourcey-ditto.pages.dev/http-api-doc/models/newconnection.md); Type: NewConnection

- 400: The request could not be completed. Possible reasons:
* an `ID` was set in the request body, but the ID will be generated by Ditto
* the JSON of the connection to be created is invalid

Content type: application/json

Type: AdvancedError

Schema: [AdvancedError](https://sourcey-ditto.pages.dev/http-api-doc/models/advancederror.md)

- `status` (required)
  Type: integer
  
  The HTTP status of the error

- `error` (required)
  Type: string
  
  The error code of the occurred exception

- `message` (required)
  Type: string
  
  The message of the error - what went wrong

- `description` (optional)
  Type: string
  
  A description how to fix the error or more details

- `href` (optional)
  Type: string
  
  A link to further information about the error and how to fix it

- 401: The request could not be completed due to missing authentication.

Content type: application/json

Type: AdvancedError

Schema: [AdvancedError](https://sourcey-ditto.pages.dev/http-api-doc/models/advancederror.md)

- `status` (required)
  Type: integer
  
  The HTTP status of the error

- `error` (required)
  Type: string
  
  The error code of the occurred exception

- `message` (required)
  Type: string
  
  The message of the error - what went wrong

- `description` (optional)
  Type: string
  
  A description how to fix the error or more details

- `href` (optional)
  Type: string
  
  A link to further information about the error and how to fix it

- 403: The request could not be completed due to invalid authentication.

Content type: application/json

Type: AdvancedError

Schema: [AdvancedError](https://sourcey-ditto.pages.dev/http-api-doc/models/advancederror.md)

- `status` (required)
  Type: integer
  
  The HTTP status of the error

- `error` (required)
  Type: string
  
  The error code of the occurred exception

- `message` (required)
  Type: string
  
  The message of the error - what went wrong

- `description` (optional)
  Type: string
  
  A description how to fix the error or more details

- `href` (optional)
  Type: string
  
  A link to further information about the error and how to fix it

- 404: The request could not be completed. Connections not found.

Content type: application/json

Type: AdvancedError

Schema: [AdvancedError](https://sourcey-ditto.pages.dev/http-api-doc/models/advancederror.md)

- `status` (required)
  Type: integer
  
  The HTTP status of the error

- `error` (required)
  Type: string
  
  The error code of the occurred exception

- `message` (required)
  Type: string
  
  The message of the error - what went wrong

- `description` (optional)
  Type: string
  
  A description how to fix the error or more details

- `href` (optional)
  Type: string
  
  A link to further information about the error and how to fix it

## Examples

### cURL

```bash
curl -X POST 'https://ditto.eclipseprojects.io/api/2/connections' \
  -H 'Authorization: Basic WU9VUl9VU0VSTkFNRTpZT1VSX1BBU1NXT1JE' \
  -H 'Content-Type: application/json' \
  --data-raw '{
  "name": "hono-example-connection-123",
  "connectionType": "hono",
  "connectionStatus": "open",
  "sources": [
    {
      "addresses": [
        "telemetry",
        "event",
        "..."
      ],
      "authorizationContext": [
        "ditto:inbound-auth-subject",
        "..."
      ],
      "consumerCount": 1,
      "enforcement": {
        "input": "{{ header:device_id }}",
        "filters": [
          "{{ thing:id }}"
        ]
      },
      "payloadMapping": [
        "Ditto",
        "status"
      ]
    }
  ],
  "targets": [
    {
      "address": "command",
      "topics": [
        "_/_/things/twin/events"
      ],
      "authorizationContext": [
        "ditto:outbound-auth-subject",
        "..."
      ],
      "headerMapping": {}
    }
  ]
}'
```

### JavaScript

```javascript
const body = `{
  "name": "hono-example-connection-123",
  "connectionType": "hono",
  "connectionStatus": "open",
  "sources": [
    {
      "addresses": [
        "telemetry",
        "event",
        "..."
      ],
      "authorizationContext": [
        "ditto:inbound-auth-subject",
        "..."
      ],
      "consumerCount": 1,
      "enforcement": {
        "input": "{{ header:device_id }}",
        "filters": [
          "{{ thing:id }}"
        ]
      },
      "payloadMapping": [
        "Ditto",
        "status"
      ]
    }
  ],
  "targets": [
    {
      "address": "command",
      "topics": [
        "_/_/things/twin/events"
      ],
      "authorizationContext": [
        "ditto:outbound-auth-subject",
        "..."
      ],
      "headerMapping": {}
    }
  ]
}`;

const response = await fetch('https://ditto.eclipseprojects.io/api/2/connections', {
  method: 'POST',
  headers: {
    'Authorization': 'Basic WU9VUl9VU0VSTkFNRTpZT1VSX1BBU1NXT1JE',
    'Content-Type': 'application/json',
  },
  body,
});

const data = await response.text();
```

### Python

```python
import requests

body = '''{
  "name": "hono-example-connection-123",
  "connectionType": "hono",
  "connectionStatus": "open",
  "sources": [
    {
      "addresses": [
        "telemetry",
        "event",
        "..."
      ],
      "authorizationContext": [
        "ditto:inbound-auth-subject",
        "..."
      ],
      "consumerCount": 1,
      "enforcement": {
        "input": "{{ header:device_id }}",
        "filters": [
          "{{ thing:id }}"
        ]
      },
      "payloadMapping": [
        "Ditto",
        "status"
      ]
    }
  ],
  "targets": [
    {
      "address": "command",
      "topics": [
        "_/_/things/twin/events"
      ],
      "authorizationContext": [
        "ditto:outbound-auth-subject",
        "..."
      ],
      "headerMapping": {}
    }
  ]
}'''

response = requests.post(
    'https://ditto.eclipseprojects.io/api/2/connections',
    data=body.encode('utf-8'),
    headers={
        'Authorization': 'Basic WU9VUl9VU0VSTkFNRTpZT1VSX1BBU1NXT1JE',
        'Content-Type': 'application/json',
    },
)
print(response.text)
```
