Welcome to Knowledge Base!

KB at your finger tips

This is one stop global knowledge base where you can learn about all the products, solutions and support features.

Categories
All
Cloud-AWS
Delete an Amazon VPC link for an Amazon Gateway REST API

How can I delete an Amazon VPC link for my Amazon Gateway REST API?

Last updated: 2022-10-04

I'm trying to delete my Amazon Virtual Private Cloud (Amazon VPC) link for my Amazon Gateway REST API and received the following error:

"Cannot delete VPC link referenced in format of [Method:Resource]."

How can I resolve this?

Short description

If a resource using the Amazon VPC link integration is deleted, then you can't delete the link.

Resolution

To delete the Amazon VPC link, follow these steps depending on whether the REST API was or was not deployed.

Deployed REST APIs

Switch the integration type from the Amazon VPC link to another type. For example, a mock integration, HTTP integration, or AWS integration type. After switching the integration type, redeploy the REST API to the same stage name that you previously deployed. Then, try deleting the Amazon VPC link again.

Undeployed REST APIs

Switch the integration type from the Amazon VPC link to another type. For example, a mock integration, HTTP integration, or AWS integration type. Then, try deleting the Amazon VPC link again.


Tutorial: Build a REST API with API Gateway private integration

How can I access an API Gateway private REST API in another AWS account using an interface VPC endpoint?

Did this article help?

Submit feedback

Do you need billing or technical support?

Contact AWS Support
Access an Amazon API Gateway API from another AWS account

How can I access an Amazon API Gateway API from another AWS account?

Last updated: 2022-10-03

I want to access an Amazon API Gateway API from another AWS account. How can I do this?

Short description

Public API endpoints (Regional or edge-optimized) can be accessed directly from the public endpoint stage URL or a custom domain name.

Private REST APIs endpoints can be accessed from a virtual private cloud in Amazon Virtual Private Cloud (Amazon VPC) using an interface VPC endpoint.

Amazon API Gateway endpoints can be accessed using AWS Identity and Access Management (IAM) authentication with cross-account access.

Resolution

Public API endpoints

You can access API Gateway public endpoints directly from the API stage URL. For example, https://0123456789.execute-api.{region}.amazonaws.com/{stage-name}.

You can also access API Gateway public endpoints using a custom domain name in a public hosted zone.

Note: Custom domain names aren't supported for private APIs.

For more information, see How can I set up a custom domain name for my API Gateway API?

Private REST API endpoints

You can access API Gateway private REST APIs in another AWS account with an Amazon Virtual Private Cloud (Amazon VPC) using an interface endpoint.

If your private REST API is located in an AWS account and you want to access it from another account, you can edit the resource policy.

For more information, see How can I access an API Gateway private REST API in another AWS account using an interface VPC endpoint?

APIs using IAM authentication

Additional configuration is required to access an API Gateway API with cross-account access that uses IAM authentication. The IAM role of the source account must be allowed explicit access in the resource policy similar to the following:

REST APIs

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::account-id-2:user/Alice",
          "account-id-2"
        ]
      },
      "Action": "execute-api:Invoke",
      "Resource": [
        "arn:aws:execute-api:us-east-1:{account-id}:{api-id}/*/*/*"
      ]
    }
  ]
}

For more information, see How do I activate IAM authentication for API Gateway REST APIs?

HTTP APIs

The option to use resource policies to provide IAM authentication for cross-accounts isn't available for API Gateway HTTP APIs.

You can use the sts:AssumeRole API action to assume a role for the HTTP API account. The assumed role provides temporary security credentials that can be used to invoke the HTTP API in another account.

For more information, see How can I provide cross-account IAM authorization for API Gateway HTTP APIs?


Creating a private API in Amazon API Gateway

Example: Allow users in another AWS account to use an API

Did this article help?

Submit feedback

Do you need billing or technical support?

Contact AWS Support
Read article
Map status codes in API Gateway for HTTP APIs

How do I map the response status codes for API Gateway integrations in HTTP APIs?

Last updated: 2022-09-30

What are the differences between payload versions 1.0 and 2.0?

How do I map the status codes returned by HTTP APIs in Amazon API Gateway?

-or-

How do I map the status codes in HTTP APIs?

Resolution

When you want to override your backend response status codes, use API Gateway mapping templates or regular expressions to map the status codes. You can do this in proxy and non-proxy integrations with HTTP API.

Working with HTTP APIs

HTTP APIs are different in design when compared to REST APIs. HTTP APIs are integrated by default proxy and return the same response. Unlike REST APIs, HTTP APIs provide two payload format versions to use with Lambda integration. For the 1.0 and 2.0 payload format versions, there are associated Lambda function response formats.

When the payload format version 2.0 is used, if the Lambda function doesn’t explicitly pass the status code in a valid JSON response, API Gateway assumes the following:

  • IsBase64Encoded is false
  • statusCode is 200
  • content-type is application/json
  • body is the response from a Lambda function

In the previous example, the HTTP API doesn’t return any errors, but forwards the assumed status code 200.

When the payload format version 1.0 is used, the Lambda integration must return a response in the following format. API Gateway doesn’t make assumptions of the response and returns a 500 error.

{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headername": "headervalue", ... },
    "multiValueHeaders": { "headername": ["headervalue", "headervalue2", ...], ... },
    "body": "..."
}

Mapping status codes

To map the status code to a static value basing on the returned back-end response key:

  1. Navigate to the integrations configured in HTTP API.
  2. Choose the Integration route to modify. Choose Manage Integration . Scroll to the parameter mapping, and then choose Create parameter mapping .
  3. Set Mapping type to Response (based on a status code) . Also set Response status code because the integration responses that match this status code must have parameter mapping applied.
  4. Choose Add new mapping .
  5. Under Parameter to modify , choose statusCode . Set the Modification type to Overwrite .
  6. Set Value to Static value .
    Note : This value needs to be sent to the client.
  7. Choose Create .

Working with models and mapping templates

Transforming API requests and responses

Did this article help?

Submit feedback

Do you need billing or technical support?

Contact AWS Support
Read article
Map status codes in API Gateway for REST APIs

How do I map the response status codes for API Gateway integrations in REST APIs?

Last updated: 2022-09-30

Why is AWS Lambda returning 200 OK status code responses in REST APIs?

How do I map the status codes returned by REST APIs in Amazon API Gateway?

-or-

How do I map status codes in REST APIs?

Resolution

When you want to override your backend response status codes, use API Gateway mapping templates or regular expressions to map the status codes. You can do this in proxy and non-proxy integrations with REST API.

Proxy and non-proxy integrations are used to map response status codes in REST API. When there’s a proxy response, API Gateway receives the status codes as they’re sent by the backend. In a Lambda proxy integration, API Gateway requires the backend Lambda function to return the following output in JSON format:

{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode, 
    "headers": { "headerName": "headerValue", ... },
    "multiValueHeaders": { "headerName": ["headerValue", "headerValue2", ...], ... },
    "body": “…”65411
}

In a proxy integration with a Lambda function, a status code is passed directly to API Gateway from a backend Lambda function. A status code can’t be passed directly from the Lambda function in a non-proxy integration.

When API Gateway successfully invokes a Lambda function, the default response status code is 200. Status codes are also returned when Lambda experiences errors. You can customize API Gateway response codes. Use a non-proxy integration and a mapping template when you need to create a custom response code.

Configuring a response method with custom code

Follow these steps to configure a method to respond with custom response code from API Gateway:

1.    In the API Gateway console, create a public REST API.

2.    Create a resource and a method for the resource.

3.    Set up a method response that includes the status code that you want API Gateway to return.

4.    Configure a Lambda integration response.

  • For Lambda Error Regex , provide the regular expression pattern for the error message that's returned by the Lambda function.
    Note : You can also find the HTTP error regex for HTTP responses.
  • For the method response status, provide the status code that must be returned by API Gateway.
  • Choose an option for Content Handling to set how the response body is handled before the response is sent to the client.
  • Make sure that the default pattern of the status code is set to 200.

5.    After you finish configuring your integration response, save, test, and deploy your changes.

Mapping status codes to static values

For API Gateway to capture a group of status codes returned from your backend, map the status codes to static values:

1.    Go to the resource that has the status code you want to change.

2.    Set up a method response to return 400 as the API Gateway response code.

3.    Go back to the resource configurations and set up an integration response.

4.    The values in HTTP status regex capture the status returned by your backend. The status is then mapped to the response code defined in Step 2.

When HTTP status regex has a default value of "-" and is mapped to 200 as the method response status, all status codes are captured and returned by your backend map to 200. You can change the HTTP status regex values to 2\d{2} to capture all 2xx responses and map them to 200.

5.    Choose Add integration response to capture the other status codes.

For 4xx, in HTTP status regex , add 4\d{2} . For Method response status , choose 400 . This was defined in Step 2.

6.    Deploy your API. When the API returns any 2xx status codes, they're mapped to the 200 status code. If your API returns any 4xx status codes, they’re mapped to the 400 status code.

Regular expressions can be formatted in multiple ways. For example:

  • .*([01][0-9][0-9]|2[0-4][0-9]|25[0-5]).* matches for status codes between 100-199, 200-249, or 250-255.
  • .*5\d\d.* matches a status code , such as 5xx.

The following example code is for testing a Lambda function:

def lambda_handler(event, context):
    if "error" not in event or event['error'] == "":
        return("Pass")
    elif event['error'] == 'sample 400':
        raise Exception({"errorMessage": "Error: Raising 400 from within the Lambda function","errorType": "Exception"})
    elif event['error'] == 'sample 500':
        raise Exception({"errorMessage": "Error: Raising 500 from within the Lambda function","errorType": "Exception"})
    else:
        return("Error Value in the json request should either be 400 or 500 to demonstrate")

In the example, the code checks if the error value sent from API Gateway is a 400 or 500 error. When it’s a 400 or 500 error, the Lambda code raises an exception with an error message. When API Gateway receives the response, the service checks if the error message matches any pattern configured in the integration response. API Gateway responds accordingly if the Lambda regex pattern is matched.

7.    After a successful configuration, the status codes can be tested using the API Gateway console.

Mapping status codes with mapping templates

The previous example uses regular expressions, but it can also use mapping templates. The following example overrides the 200 status code from the backend to apply the 400 status code:

1.    Create a Lambda function with following example code:

----------------------
def lambda_handler(event, context):
    # TODO implement print(event)
    return { 'statusCode': 200, 'body': "customerror" }
-----------------------

2.    Create an API with Lambda non-proxy integration by using the previous Lambda function for the backend.

3.    Follow steps 6-10 described in the Override an API's response status code with the API Gateway console tutorial.

In this example, use the following mapping template:

----------------------
#set($inputRoot = $input.path('$'))
$input.json("$")
#if($inputRoot.toString().contains("customerror"))
#set($context.responseOverride.status = 400)
#end 
----------------------

4.    Save, test, and deploy the API.


Working with models and mapping templates

Transforming API requests and responses

Amazon API Gateway Developer Guide

Did this article help?

Submit feedback

Do you need billing or technical support?

Contact AWS Support
Read article
Troubleshoot wrong certificate returned for API Gateway custom domain names

Why was the wrong certificate returned when invoking my API Gateway custom domain name?

Last updated: 2022-09-29

I tried to make an API request to my Amazon API Gateway custom domain name, but the wrong certificate was returned. How do I fix this?

Short description

There are two types of custom domain names that you can create for API Gateway APIs: Regional or (for REST APIs only) edge-optimized.

For Regional custom domain names, API Gateway creates a Regional domain name. You must set up a DNS record to map the custom domain name to the hostname similar to "d-example.execute-api.<region>.amazonaws.com".

For edge-optimized custom domain names, API Gateway creates an Amazon CloudFront distribution. You must set up a DNS record to map the custom domain name to the CloudFront distribution name similar to "distribution-id.cloudfront.net".

In the following scenario, the SSL certificate *.example.com or www.example.com was uploaded to the custom domain name www.example.com. An API request to www.example.com returns an error similar to the following:

From a browser:

"This server could not prove that it is www.example.com; its security certificate is from *.execute-api.us-east-1.amazonaws.com. This may be caused by a misconfiguration or an attacker intercepting your connection."

From curl:

"curl: (60) SSL: no alternative certificate subject name matches target hostname 'www.example.com'. curl failed to verify the legitimacy of the server and therefore could not establish a secure connection to it. To learn more about this situation and how to fix it, please visit the web page mentioned above."

Resolution

Make sure that the CNAME or A record of the custom domain name points to the API Gateway domain name and not to the API Gateway stage URL.

1.    Run the following openssl command to verify that the SSL certificate is returned by the custom domain:

openssl s_client -connect www.example.com:443 -servername www.example.com

Example output:

subject=/CN=*.execute-api.us-east-1.amazonaws.com

2.    Run the following dig command on the custom domain:

dig www.example.com

The dig command output has either a CNAME record pointing to the API Gateway stage URL, or an A record pointing to the IP address.

3.    Check the DNS record for the domain www.example.com with your domain registrar to determine where it's pointing to. If your domain is registered with Amazon Route 53, then see Checking DNS responses from Route 53.

4.    To confirm that the DNS records are mapped correctly, open the API Gateway console. In the navigation pane, choose Custom domain names , and then choose your custom domain.

5.    From Domain details , choose Configuration , and then check the API Gateway domain name . The custom domain name must be mapped to the API Gateway domain name. Regional custom domain names use a prefix similar to "d-example.execute-api.<region>.amazonaws.com". Edge-optimized custom domain names use a prefix similar to "distribution-id.cloudfront.net".

6.    If the CNAME record points to the API Gateway stage URL instead of the API Gateway domain name, update the CNAME record. Change the CNAME record to point to your API Gateway domain name instead of the stage URL. If your custom domain name is registered with a third party, then contact your domain registrar. If your custom domain name is registered with Route 53, then see Editing records.


How can I set up a custom domain name for my API Gateway API?

How can I resolve certificate expired or "invalid certificate" errors when invoking an API Gateway API using a custom domain name?

Did this article help?

Submit feedback

Do you need billing or technical support?

Contact AWS Support
Read article
Configure a custom domain for API Gateway APIs behind a CloudFront web distribution

How can I configure a custom domain endpoint for multiple API Gateway APIs behind a CloudFront web distribution?

Last updated: 2022-09-28

I want to use an Amazon API Gateway custom domain endpoint behind an Amazon CloudFront web distribution. Then, I want to forward the API request to multiple APIs using base path mapping. How can I do this?

Resolution

Create the custom domain name for your REST API, HTTP API, or WebSocket API

If you haven't already done so, create your custom domain name, and then associate it with two different APIs.

Note: A custom domain name for a WebSocket API can't be mapped to REST APIs or HTTP APIs.

For REST APIs, follow the instructions in Setting up custom domain names for REST APIs.

For HTTP APIs, follow the instructions in Setting up custom domain names for HTTP APIs.

For WebSocket APIs, follow the instructions in Setting up custom domain names for WebSocket APIs.

Note: After a custom domain name is created in API Gateway, you must create or update your DNS provider's resource record to map to your API endpoint. For more information, see Register a domain name.

The example in this article uses a REST API Regional custom domain name setup.

Example API endpoint URLs

https://restapiId1.execute-api.us-west-2.amazonaws.com/example1/home
https://restapiId2.execute-api.us-west-2.amazonaws.com/example2/home

Example custom domain URL (without base path mapping)

https://apigw.customdomain.com/example1/home
https://apigw.customdomain.com/example2/home

Create a CloudFront web distribution

1.    Open the CloudFront console, and then choose Create Distribution .

2.    On the Select a delivery method for your content page, under Web , choose Get Started .

3.    On the Create Distribution page, for Origin Domain , paste your API's custom domain URL similar to the following example:

Origin domain name example

https://apigw.customdomain.com

4. For Origin path , leave it blank . Note: Entering an incorrect base path for origin path when invoking the CloudFront web distribution can result in an error. For example, an unauthorized request error that returns the error "Missing Authentication Token" and a 403 Forbidden response code.

5.    For Minimum Origin SSL Protocol , it's a best practice to choose TLSv1.2 . Don't choose SSLv3 . API Gateway doesn't support the SSLv3 protocol.

6.    For Protocol , choose HTTPS Only . Note: API Gateway doesn't support unencrypted HTTP endpoints. For more information, see Amazon API Gateway FAQs.

7.    (Optional) To forward custom headers to your origin, choose Add header , and enter your Header name and Value . Note: For a list of custom headers that CloudFront can't add, see Custom headers that CloudFront can't add to origin requests.

8.    Choose Create Distribution .

After CloudFront creates your distribution, the value of the Status column for your distribution changes from InProgress to Deployed .

For more information, see Creating a distribution.

Test your CloudFront web distribution

1.    Open the CloudFront console, copy the Domain Name of your web distribution to your clipboard similar to the following example:

Non-custom domain name example

a222222bcdefg5.cloudfront.net

2.    Follow the instructions for Testing a distribution.

A successful test returns a 200 OK response. If you get a 500 server error code, then the web distribution might not be deployed. If you get no response, the CloudFront DNS record hasn't propagated yet.

After the CloudFront distribution is created, your setup is configured as follows:

a222222bcdefg5.cloudfront.net/example1/home --> apigw.customdomain.com/example1/home --> API-1

a222222bcdefg5.cloudfront.net/example2/home --> apigw.customdomain.com/example2/home --> API-2

You are now able to make a request to two APIs from a single CloudFront distribution with your API Gateway custom domain name.

To configure forwarding for incoming authorization headers for your CloudFront web distribution, see How do I set up API Gateway with my own CloudFront distribution?


Choose an endpoint type to set up for an API Gateway API

Working with API mappings for Websocket APIs

Working with API mappings for REST APIs

Working with API mappings for HTTP APIs

Did this article help?

Submit feedback

Do you need billing or technical support?

Contact AWS Support
Read article