

# Integrations for WebSocket APIs in API Gateway
<a name="apigateway-websocket-api-integrations"></a>

After setting up an API route, you must integrate it with an endpoint in the backend. A backend endpoint is also referred to as an integration endpoint and can be a Lambda function, an HTTP endpoint, or an AWS service action. The API integration has an integration request and an integration response.

In this section, you can learn how to set up integration requests and integration responses for your WebSocket API. 

**Topics**
+ [

# Set up a WebSocket API integration request in API Gateway
](apigateway-websocket-api-integration-requests.md)
+ [

# Set up a WebSocket API integration response in API Gateway
](apigateway-websocket-api-integration-responses.md)

# Set up a WebSocket API integration request in API Gateway
<a name="apigateway-websocket-api-integration-requests"></a>

Setting up an integration request involves the following:
+ Choosing a route key to integrate to the backend.
+ Specifying the backend endpoint to invoke. WebSocket APIs support the following integration types:
  + `AWS_PROXY`
  + `AWS`
  + `HTTP_PROXY`
  + `HTTP`
  + `MOCK`

  For more information about integration types, see [IntegrationType](https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis-apiid-integrations-integrationid.html#apis-apiid-integrations-integrationid-prop-integration-integrationtype) in the API Gateway V2 REST API.
+ Configuring how to transform the route request data, if necessary, into integration request data by specifying one or more request templates.

## Set up a WebSocket API integration request using the API Gateway console
<a name="apigateway-websocket-api-integration-request-using-console"></a>

**To add an integration request to a route in a WebSocket API using the API Gateway console**

1. Sign in to the API Gateway console, choose the API, and choose **Routes**.

1. Under **Routes**, choose the route.

1. Choose the **Integration request** tab, and then in the **Integration request settings** section, choose **Edit**.

1. For **Integration type**, select one of the following:
   + Choose **Lambda function** only if your API will be integrated with an AWS Lambda function that you have already created in this account or in another account.

     To create a new Lambda function in AWS Lambda, to set a resource permission on the Lambda function, or to perform any other Lambda service actions, choose **AWS Service** instead.
   + Choose **HTTP** if your API will be integrated with an existing HTTP endpoint. For more information, see [HTTP integrations for REST APIs in API Gateway](setup-http-integrations.md).
   + Choose **Mock** if you want to generate API responses from API Gateway directly, without the need for an integration backend. For more information, see [Mock integrations for REST APIs in API Gateway](how-to-mock-integration.md).
   + Choose **AWS service** if your API will be integrated with an AWS service.
   + Choose **VPC link** if your API will use a `VpcLink` as a private integration endpoint. For more information, see [Set up a private integration](set-up-private-integration.md).

1. If you chose **Lambda function**, do the following:

   1. For **Use Lambda proxy integration**, choose the check box if you intend to use [Lambda proxy integration](set-up-lambda-proxy-integrations.md#api-gateway-create-api-as-simple-proxy) or [cross-account Lambda proxy integration](apigateway-cross-account-lambda-integrations.md).

   1. For **Lambda function**, specify the function in one of the following ways:
      + If your Lambda function is in the same account, enter the function name and then select the function from the dropdown list.
**Note**  
The function name can optionally include its alias or version specification, as in `HelloWorld`, `HelloWorld:1`, or `HelloWorld:alpha`.
      + If the function is in a different account, enter the ARN for the function.

   1. To use the default timeout value of 29 seconds, keep **Default timeout** turned on. To set a custom timeout, choose **Default timeout** and enter a timeout value between `50` and `29000` milliseconds.

1. If you chose **HTTP**, follow the instructions in step 4 of [Set up an API integration request using the API Gateway console](how-to-method-settings-console.md).

1. If you chose **Mock**, proceed to the **Request Templates** step.

1. If you chose **AWS service**, follow the instructions in step 6 of [Set up an API integration request using the API Gateway console](how-to-method-settings-console.md).

1. If you chose **VPC link**, do the following:

   1. For **VPC proxy integration**, choose the check box if you want your requests to be proxied to your `VPCLink`'s endpoint.

   1. For **HTTP method**, choose the HTTP method type that most closely matches the method in the HTTP backend.

   1. From the **VPC link** dropdown list, select a VPC link. You can select `[Use Stage Variables]` and enter **\$1\$1stageVariables.vpcLinkId\$1** in the text box below the list.

      You can define the `vpcLinkId` stage variable after deploying the API to a stage and set its value to the ID of the `VpcLink`.

   1. For **Endpoint URL**, enter the URL of the HTTP backend you want this integration to use.

   1. To use the default timeout value of 29 seconds, keep **Default timeout** turned on. To set a custom timeout, choose **Default timeout** and enter a timeout value between `50` and `29000` milliseconds.

1. Choose **Save changes**.

1. Under **Request templates**, do the following:

   1. To enter a **Template selection expression**, under **Request templates**, choose **Edit**.

   1. Enter a **Template selection expression**. Use an expression that API Gateway looks for in the message payload. If it is found, it is evaluated, and the result is a template key value that is used to select the data mapping template to be applied to the data in the message payload. You create the data mapping template in the next step. Choose **Edit** to save your changes.

   1. Choose **Create template** to create the data mapping template. For **Template key**, enter a template key value that is used to select the data mapping template to be applied to the data in the message payload. Then, enter a mapping template. Choose **Create template**.

      For information about template selection expressions, see [Template selection expressions](websocket-api-data-transformations.md#apigateway-websocket-api-template-selection-expressions).

## Set up an integration request using the AWS CLI
<a name="apigateway-websocket-api-integration-request-using-awscli"></a>

You can set up an integration request for a route in a WebSocket API by using the AWS CLI as in the following example, which creates a mock integration:

1. Create a file named `integration-params.json`, with the following contents:

   ```
   {"PassthroughBehavior": "WHEN_NO_MATCH", "TimeoutInMillis": 29000, "ConnectionType": "INTERNET", "RequestTemplates": {"application/json": "{\"statusCode\":200}"}, "IntegrationType": "MOCK"}
   ```

1. Use the following [create-integration](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/create-integration.html) command to create the mock integration.

   ```
   aws apigatewayv2 --region us-east-1 create-integration --api-id aabbccddee --cli-input-json file://integration-params.json
   ```

   The output will look like the following:

   ```
   {
       "PassthroughBehavior": "WHEN_NO_MATCH",
       "TimeoutInMillis": 29000,
       "ConnectionType": "INTERNET",
       "IntegrationResponseSelectionExpression": "${response.statuscode}",
       "RequestTemplates": {
           "application/json": "{\"statusCode\":200}"
       },
       "IntegrationId": "0abcdef",
       "IntegrationType": "MOCK"
   }
   ```

Alternatively, you can set up an integration request for a proxy integration by using the AWS CLI.

1. Create a Lambda function in the Lambda console and give it a basic Lambda execution role.

1. Use the following [create-integration](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/create-integration.html) command to create the integration.

   ```
   aws apigatewayv2 create-integration --api-id aabbccddee --integration-type AWS_PROXY --integration-method POST --integration-uri arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123412341234:function:simpleproxy-echo-e2e/invocations
   ```

The output will look like the following:

```
{
    "PassthroughBehavior": "WHEN_NO_MATCH",
    "IntegrationMethod": "POST",
    "TimeoutInMillis": 29000,
    "ConnectionType": "INTERNET",
    "IntegrationUri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123412341234:function:simpleproxy-echo-e2e/invocations",
    "IntegrationId": "abcdefg",
    "IntegrationType": "AWS_PROXY"
}
```

## Input format of a Lambda function for proxy integration for WebSocket APIs
<a name="api-gateway-simple-proxy-for-lambda-input-format-websocket"></a>

In Lambda proxy integration, API Gateway maps the entire client request to the input `event` parameter of the backend Lambda function. The following example shows the structure of the input event from the `$connect` route and the input event from the `$disconnect` route that API Gateway sends to a Lambda proxy integration.

------
#### [ Input from the \$1connect route ]

```
{
    headers: {
      Host: 'abcd123.execute-api.us-east-1.amazonaws.com',
      'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
      'Sec-WebSocket-Key': '...',
      'Sec-WebSocket-Version': '13',
      'X-Amzn-Trace-Id': '...',
      'X-Forwarded-For': '192.0.2.1',
      'X-Forwarded-Port': '443',
      'X-Forwarded-Proto': 'https'
    },
    multiValueHeaders: {
      Host: [ 'abcd123.execute-api.us-east-1.amazonaws.com' ],
      'Sec-WebSocket-Extensions': [ 'permessage-deflate; client_max_window_bits' ],
      'Sec-WebSocket-Key': [ '...' ],
      'Sec-WebSocket-Version': [ '13' ],
      'X-Amzn-Trace-Id': [ '...' ],
      'X-Forwarded-For': [ '192.0.2.1' ],
      'X-Forwarded-Port': [ '443' ],
      'X-Forwarded-Proto': [ 'https' ]
    },
    requestContext: {
      routeKey: '$connect',
      eventType: 'CONNECT',
      extendedRequestId: 'ABCD1234=',
      requestTime: '09/Feb/2024:18:11:43 +0000',
      messageDirection: 'IN',
      stage: 'prod',
      connectedAt: 1707502303419,
      requestTimeEpoch: 1707502303420,
      identity: { sourceIp: '192.0.2.1' },
      requestId: 'ABCD1234=',
      domainName: 'abcd1234.execute-api.us-east-1.amazonaws.com',
      connectionId: 'AAAA1234=',
      apiId: 'abcd1234'
    },
    isBase64Encoded: false
  }
```

------
#### [ Input from the \$1disconnect route ]

```
{
    headers: {
      Host: 'abcd1234.execute-api.us-east-1.amazonaws.com',
      'x-api-key': '',
      'X-Forwarded-For': '',
      'x-restapi': ''
    },
    multiValueHeaders: {
      Host: [ 'abcd1234.execute-api.us-east-1.amazonaws.com' ],
      'x-api-key': [ '' ],
      'X-Forwarded-For': [ '' ],
      'x-restapi': [ '' ]
    },
    requestContext: {
      routeKey: '$disconnect',
      disconnectStatusCode: 1005,
      eventType: 'DISCONNECT',
      extendedRequestId: 'ABCD1234=',
      requestTime: '09/Feb/2024:18:23:28 +0000',
      messageDirection: 'IN',
      disconnectReason: 'Client-side close frame status not set',
      stage: 'prod',
      connectedAt: 1707503007396,
      requestTimeEpoch: 1707503008941,
      identity: { sourceIp: '192.0.2.1' },
      requestId: 'ABCD1234=',
      domainName: 'abcd1234.execute-api.us-east-1.amazonaws.com',
      connectionId: 'AAAA1234=',
      apiId: 'abcd1234'
    },
    isBase64Encoded: false
  }
```

------

# Set up a WebSocket API integration response in API Gateway
<a name="apigateway-websocket-api-integration-responses"></a>

The following section provides a brief overview of integration responses for WebSocket API and how to set up an integration response for a WebSocket API. 

**Topics**
+ [

## Overview of integration responses
](#apigateway-websocket-api-integration-response-overview)
+ [

## Integration responses for two-way communication
](#apigateway-websocket-api-integration-response-for-two-way-communication)
+ [

## Set up an integration response using the API Gateway console
](#apigateway-websocket-api-integration-response-using-console)
+ [

## Set up an integration response using the AWS CLI
](#apigateway-websocket-api-integration-response-using-awscli)

## Overview of integration responses
<a name="apigateway-websocket-api-integration-response-overview"></a>

API Gateway's integration response is a way of modeling and manipulating the response from a backend service. There are some differences in setup of a REST API versus a WebSocket API integration response, but conceptually the behavior is the same.

WebSocket routes can be configured for two-way or one-way communication.
+ When a route is configured for two-way communication, an integration response allows you to configure transformations on the returned message payload, similar to integration responses for REST APIs.
+ If a route is configured for one-way communication, then regardless of any integration response configuration, no response will be returned over the WebSocket channel after the message is processed.

 API Gateway will not pass the backend response through to the route response, unless you set up a route response. To learn about setting up a route response, see [Set up route responses for WebSocket APIs in API Gateway](apigateway-websocket-api-route-response.md).

## Integration responses for two-way communication
<a name="apigateway-websocket-api-integration-response-for-two-way-communication"></a>

Integrations can be divided into *proxy* integrations and *non-proxy* integrations.

**Important**  
For *proxy integrations*, API Gateway automatically passes the backend output to the caller as the complete payload. There is no integration response.

For *non-proxy integrations*, you must set up at least one integration response:
+ Ideally, one of your integration responses should act as a catch-all when no explicit choice can be made. This default case is represented by setting an integration response key of `$default`.
+ In all other cases, the integration response key functions as a regular expression. It should follow a format of `"/expression/"`.

For non-proxy HTTP integrations:
+ API Gateway will attempt to match the HTTP status code of the backend response. The integration response key will function as a regular expression in this case. If a match cannot be found, then `$default` is chosen as the integration response.
+ The template selection expression, as described above, functions identically. For example:
  + `/2\d\d/`: Receive and transform successful responses
  + `/4\d\d/`: Receive and transform bad request errors
  + `$default`: Receive and transform all unexpected responses

For more information about template selection expressions, see [Template selection expressions](websocket-api-data-transformations.md#apigateway-websocket-api-template-selection-expressions).

## Set up an integration response using the API Gateway console
<a name="apigateway-websocket-api-integration-response-using-console"></a>

To set up a route integration response for a WebSocket API using the API Gateway console:

1. Sign in to the API Gateway console at [https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway).

1.  Choose your WebSocket API and choose your route.

1. Choose the **Integration request** tab, and then in the **Integration response settings** section, choose **Create integration response**.

1. For **Response key**, enter a value that will be found in the response key in the outgoing message after evaluating the response selection expression. For instance, you can enter **/4\$1d\$1d/** to receive and transform bad request errors or enter **\$1default** to receive and transform all responses that match the template selection expression. 

1. For **Template selection expression**, enter a selection expression to evaluate the outgoing message.

1. Choose **Create response**.

1. You can also define a mapping template to configure transformations of your returned message payload. Choose **Create template**.

1. Enter a key name. If you are choosing the default template selection expression, enter **\$1\$1default**.

1. For **Response template**, enter your mapping template in the code editor.

1. Choose **Create template**.

1. Choose **Deploy API** to deploy your API.

 Use the following [ wscat](https://www.npmjs.com/package/wscat) command to connect to your API. For more information about `wscat`, see [Use `wscat` to connect to a WebSocket API and send messages to it](apigateway-how-to-call-websocket-api-wscat.md). 

```
wscat -c wss://api-id.execute-api.us-east-2.amazonaws.com/test
```

 When you call your route, the returned message payload should return. 

## Set up an integration response using the AWS CLI
<a name="apigateway-websocket-api-integration-response-using-awscli"></a>

The following [create-integration-response](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/create-integration-response.html) command creates a `$default` integration response:

```
aws apigatewayv2 create-integration-response \
    --api-id vaz7da96z6 \
    --integration-id a1b2c3 \
    --integration-response-key '$default'
```