# Create an Integration

## API Overview

An Integration is a connection from a SendGrid Marketing Campaign to a supported third-party application. Integrations with different external applications allow you to sync data and create a more cohesive cross-product data experience.

Currently, only [Segment](https://segment.com/docs) Integrations are supported. Segment Integrations allow you to customize and automate email event forwarding to your Segment account.

The Integrations API allows you to create, retrieve, update, and delete your Integrations.

## Operation overview

```json
{"path":"https://api.sendgrid.com/v3/marketing/integrations","method":"post","servers":[{"url":"https://api.sendgrid.com","description":"for global users and subusers"},{"url":"https://api.eu.sendgrid.com","description":"for EU regional subusers"}]}
```

This endpoint creates an Integration for email event forwarding. Each Integration has a maximum number of allowed Integration instances per user. For example, users can create up to 10 Segment Integrations.

## Operation details

### Authentication

API Key

### Headers

```json
[{"in":"header","name":"Authorization","required":true,"default":"Bearer <<YOUR_API_KEY_HERE>>","schema":{"type":"string"}}]
```

### Request body

```json
{"schema":{"type":"object","required":["destination","filters","properties"],"refName":"IntegrationInput","modelName":"IntegrationInput","properties":{"destination":{"type":"string","description":"The third-party application you would like to forward your events to.","enum":["Segment"],"refName":"Destination2","modelName":"Destination2"},"filters":{"type":"object","required":["email_events"],"description":"The configurable filters for SendGrid to destination email event forwarding.","properties":{"email_events":{"type":"array","description":"The possible SendGrid email event types for event forwarding. Specify all the email event types that you would like to forward to the Integration's destination.","items":{"type":"string","enum":["drop","processed","deferred","group_unsubscribe","bounce","delivered","click","unsubscribe","open","group_resubscribe","spamreport","machine_opened"],"refName":"Items1","modelName":"Items1"}}}},"properties":{"type":"object","description":"The properties of an Integration required to send events to a specific third-party application.","required":["write_key","destination_region"],"properties":{"write_key":{"description":"The write key provided by the Segment Source you'd like to have events forwarded to. Must be between 6 and 51 characters.","type":"string","example":"1234-abc"},"destination_region":{"description":"The workspace region where the Segment Source write key lives.","type":"string","enum":["EU","US"],"refName":"DestinationRegion1","modelName":"DestinationRegion1"}}},"label":{"type":"string","default":"Untitled Integration","example":"My New Segment Integration!","description":"The nickname for the Integration."}}},"example":{"filters":{"email_events":["click","drop","open","processed","delivered"]},"destination":"Segment","label":"optional label","properties":{"destination_region":"US","write_key":"a123456"}},"encodingType":"application/json"}
```

### Responses

```json
[{"responseCode":"201","schema":{"description":"Successful Operation","content":{"application/json":{"schema":{"type":"object","refName":"Integration","modelName":"Integration","properties":{"integration_id":{"type":"string","description":"The unique ID of an Integration.","example":"12345"},"user_id":{"type":"string","example":"123456","description":"Your Twilio SendGrid account ID."},"filters":{"type":"object","description":"The configurable filters for SendGrid to destination email event forwarding.","properties":{"email_events":{"type":"array","description":"The possible SendGrid email event types for event forwarding. Specify all the email event types that you would like to forward to the Integration's destination.","items":{"type":"string","enum":["drop","processed","deferred","group_unsubscribe","bounce","delivered","click","unsubscribe","open","group_resubscribe","spamreport","machine_opened"],"refName":"Items2","modelName":"Items2"}}}},"properties":{"type":"object","description":"The properties of an Integration required to send events to a specific third-party application.","properties":{"write_key":{"description":"The write key provided by the Segment Source you'd like to have events forwarded to. Must be between 6 and 51 characters.","type":"string","example":"1234-abc"},"destination_region":{"description":"The workspace region where the Segment Source write key lives.","type":"string","enum":["EU","US"],"refName":"DestinationRegion2","modelName":"DestinationRegion2"}}},"label":{"type":"string","default":"Untitled Integration","example":"My New Segment Integration!","description":"The nickname for the Integration."},"destination":{"type":"string","description":"The third-party application you would like to forward your events to.","enum":["Segment"],"refName":"Destination3","modelName":"Destination3"}}},"example":{"user_id":"12345","integration_id":"5a1234","filters":{"email_events":["click","drop","open","processed","delivered"]},"destination":"Segment","label":"optional label","properties":{"destination_region":"US","write_key":"a123456"}}}}}},{"responseCode":"400","schema":{"description":"Invalid Request","content":{"application/json":{"schema":{"properties":{"errors":{"type":"array","items":{"type":"object","refName":"InvalidRequest","modelName":"InvalidRequest","properties":{"message":{"type":"string","description":"The error message tells you the cause of validation failure(s), separated by commas if there are multiple failures.","example":"destination_region must be EU or US, write_key must be at least 7 characters"},"field":{"type":"string","example":"request","description":"The field shows more information on where the error is when available."}}}}}}}}}},{"responseCode":"403","schema":{"description":"Forbidden. You may have hit the max number of allowed Integrations or may not have required API token scope.","content":{"application/json":{"schema":{"properties":{"errors":{"type":"array","items":{"type":"object","refName":"Forbidden","modelName":"Forbidden","properties":{"message":{"type":"string","description":"The error message tells you the cause of failure.","example":"access forbidden. please ensure you have the correct scopes defined. see /docs/sendgrid/api-reference/how-to-use-the-sendgrid-v3-api/authorization#api-key-permissions-list"}}}}}}}}}},{"responseCode":"500","schema":{"description":"Internal Error","content":{"application/json":{"schema":{"properties":{"errors":{"type":"array","items":{"type":"object","refName":"InternalError","modelName":"InternalError","properties":{"message":{"type":"string","description":"The error message tells you the cause of failure.","example":"internal error"}}}}}}}}}}]
```

Create an Integration

```js
const client = require("@sendgrid/client");
client.setApiKey(process.env.SENDGRID_API_KEY);

const data = {
  filters: {
    email_events: ["click", "drop", "open", "processed", "delivered"],
  },
  destination: "Segment",
  label: "optional label",
  properties: {
    destination_region: "US",
    write_key: "a123456",
  },
};

const request = {
  url: `/v3/marketing/integrations`,
  method: "POST",
  body: data,
};

client
  .request(request)
  .then(([response, body]) => {
    console.log(response.statusCode);
    console.log(response.body);
  })
  .catch((error) => {
    console.error(error);
  });
```

```python
import os
from sendgrid import SendGridAPIClient


sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY"))

data = {
    "filters": {
        "email_events": ["click", "drop", "open", "processed", "delivered"]
    },
    "destination": "Segment",
    "label": "optional label",
    "properties": {"destination_region": "US", "write_key": "a123456"},
}

response = sg.client.marketing.integrations.post(request_body=data)

print(response.status_code)
print(response.body)
print(response.headers)
```

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SendGrid;

public class Program {
    public static async Task Main() {
        string apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
        var client = new SendGridClient(apiKey);

        var data =
            @"{
            ""filters"": {
                ""email_events"": [
                    ""click"",
                    ""drop"",
                    ""open"",
                    ""processed"",
                    ""delivered""
                ]
            },
            ""destination"": ""Segment"",
            ""label"": ""optional label"",
            ""properties"": {
                ""destination_region"": ""US"",
                ""write_key"": ""a123456""
            }
        }";

        var response = await client.RequestAsync(
            method: SendGridClient.Method.POST,
            urlPath: "marketing/integrations",
            requestBody: data);

        Console.WriteLine(response.StatusCode);
        Console.WriteLine(response.Body.ReadAsStringAsync().Result);
        Console.WriteLine(response.Headers.ToString());
    }
}
```

```java
import com.sendgrid.*;
import java.io.IOException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Arrays;

public class Example {
    public static void main(String[] args) throws IOException {
        try {
            SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
            Request request = new Request();
            request.setMethod(Method.POST);
            request.setEndpoint("/marketing/integrations");
            request.setBody(new JSONObject(new HashMap<String, Object>() {
                {
                    put("filters", new HashMap<String, Object>() {
                        {
                            put("email_events", Arrays.asList("click", "drop", "open", "processed", "delivered"));
                        }
                    });
                    put("destination", "Segment");
                    put("label", "optional label");
                    put("properties", new HashMap<String, Object>() {
                        {
                            put("destination_region", "US");
                            put("write_key", "a123456");
                        }
                    });
                }
            }).toString());
            Response response = sg.api(request);
            System.out.println(response.getStatusCode());
            System.out.println(response.getBody());
            System.out.println(response.getHeaders());
        } catch (IOException ex) {
            throw ex;
        }
    }
}
```

```go
package main

import (
	"fmt"
	"github.com/sendgrid/sendgrid-go"
	"os"
)

func main() {
	apiKey := os.Getenv("SENDGRID_API_KEY")
	host := "https://api.sendgrid.com"
	request := sendgrid.GetRequest(apiKey, "/v3/marketing/integrations", host)
	request.Method = "POST"
	request.Body = []byte(`{
  "filters": {
    "email_events": [
      "click",
      "drop",
      "open",
      "processed",
      "delivered"
    ]
  },
  "destination": "Segment",
  "label": "optional label",
  "properties": {
    "destination_region": "US",
    "write_key": "a123456"
  }
}`)
	response, err := sendgrid.API(request)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		fmt.Println(response.StatusCode)
		fmt.Println(response.Body)
		fmt.Println(response.Headers)
	}
}
```

```php
<?php
// Uncomment the next line if you're using a dependency loader (such as Composer) (recommended)
// require 'vendor/autoload.php';

// Uncomment next line if you're not using a dependency loader (such as Composer)
// require_once '<PATH TO>/sendgrid-php.php';

$apiKey = getenv("SENDGRID_API_KEY");
$sg = new \SendGrid($apiKey);
$request_body = json_decode('{
    "filters": {
        "email_events": [
            "click",
            "drop",
            "open",
            "processed",
            "delivered"
        ]
    },
    "destination": "Segment",
    "label": "optional label",
    "properties": {
        "destination_region": "US",
        "write_key": "a123456"
    }
}');

try {
    $response = $sg->client
        ->marketing()
        ->integrations()
        ->post($request_body);
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
} catch (Exception $ex) {
    echo "Caught exception: " . $ex->getMessage();
}
```

```ruby
require 'sendgrid-ruby'
include SendGrid

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
data = JSON.parse('{
  "filters": {
    "email_events": [
      "click",
      "drop",
      "open",
      "processed",
      "delivered"
    ]
  },
  "destination": "Segment",
  "label": "optional label",
  "properties": {
    "destination_region": "US",
    "write_key": "a123456"
  }
}')

response = sg.client.marketing.integrations.post(request_body: data)
puts response.status_code
puts response.headers
puts response.body
```

```bash
curl -X POST "https://api.sendgrid.com/v3/marketing/integrations" \
--header "Authorization: Bearer $SENDGRID_API_KEY" \
--header "Content-Type: application/json" \
--data '{"filters": {"email_events": ["click", "drop", "open", "processed", "delivered"]}, "destination": "Segment", "label": "optional label", "properties": {"destination_region": "US", "write_key": "a123456"}}'
```
