Top AWS API Gateway Interview Questions(2021) | CodeUsingJava
















Top AWS API Gateway Interview Questions(2021)

In this post we will look at AWS API Gateway Interview questions. Examples are provided with explanation.
  1. What is AWS API Gateway?
  2. Explain the Architecture of API Gateway?
  3. What are the processes involved in working with AWS lambda and API Gateway?
  4. How can we use an API key in Amazon API Gateway?
  5. What is Mapping Template?
  6. What is API Caching?
  7. What are the Features of API Gateway?
  8. What API types are supported by Amazon API Gateway?
  9. What is a resource?
  10. What is AWS Lambda Function?
  11. How to add CloudFront in front of API Gateway?
  12. How can we use API Gateway to create HTTP APIs?
  13. How can we find the API endpoint of a lambda function?
  14. How can we call an API Gateway API?
  15. What are the types of API ?
  16. How can we get the list of APIs and their IDs?
  17. How can we find the arn of an API Gateway stage?
  18. How can we integrate API Gateway with SQS?
  19. How to debug AWS API Gateway & Lambda's AWS/ApiGateway 5XXError?


What is AWS API Gateway?

AWS API Gateway is used by the developers for creating, publishing, maintaining, monitoring and securing APIs at any scale.By using this API, we can create RESTfulAPIs and WebSocket APIs which helps in enabling real time two way communication applications.
API Gateway helps in providing WebSocket API Management functionality as follows:Monitoring and throttling of connections and messages. Using AWS X-Ray to trace messages as they travel through the APIs to backend services. Easy integration with HTTP/HTTPS endpoints.


How Ansible Works?

Ansible works by connecting nodes and pushing out all small programs known as Ansible Modules, it executes modules and removes them when they are finished.Modules helps in residing any machine, and there are no servers, daemons and database required.
Ansible removes the modules once they are installed and connects to the host machine, also executes the instruction when it is successfully installed removes the code which is copied on the host machine which is executed.


Explain the Architecture of API Gateway?


API Gateway


What are the processes involved in working with AWS lambda and API Gateway?

Process involved in working with AWS Lambda and API Gateway are as follows:

API Gateway
Create IAM role for permission
Create AWS lambda function
Create API Gateway
Link lambda function to API Gateway
Passing data to API Gateway


How can we use an API key in Amazon API Gateway?


$ curl -X POST -H "x-api-key: theKey" -H "Content-Type: application/json" -d '{"key":"val"}' https://[api-id].execute-api.[region].


What is Mapping Template?


#set($inputRoot = $input.path('$'))
<soap12:Envelope xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="https://www.w3.org/2001/XMLSchema" xmlns:soap12="https://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<ConvertTemp xmlns="https://www.webserviceX.NET/">
<Temperature>$inputRoot.Temperature</Temperature>
<FromUnit>$inputRoot.FromUnit</FromUnit>
<ToUnit>$inputRoot.ToUnit</ToUnit>
</ConvertTemp>
</soap12:Body>
</soap12:Envelope>



What is API Caching?

Caching API is used for storing and retrieving all the network requests and also in corresponding responses.It is created for enabling service workers for cache network requests do so it can help in providing fast responses, speed or availibility.Caching is the ability for storing copies of freaquently accessed data in several places along the request response path and also indicates wether a response can be cached or no.
We can enable API Caching in AWS API Gateway for caching our endpoint responses, we can reduce the number of calls made to our endpoint and in improving the latency of requests to our API.

What are the Features of API Gateway?

Features of API Gateway are as follows:
  • Cost Effective helps in low cost and efficient as API provides a tiered pricing model for API reuests.
  • Scalable autoscaling groups responding to API requests and scales automatically.
  • Caching and Throttling used for caching the endpoint responses that improves the latency of requests to our API.
  • Flexible implements for launching an EC2 instance or setting up the Gateway Software.
  • Security integrate with a gateway that provides tools such as AWS credentials, i.e., access and secret keys to access an API.

What API types are supported by Amazon API Gateway?

Types of APIs supported by AWS API Gateway are:
  • HTTP API - optimized for building APIs that are proxy for AWS Lambda.
  • REST API - offers proxy functionality and API management features.
  • WebSocket API - helps in enabling real-time message communication.

What is a resource?

Resource is a object which is typed and is a part of our API domain.Each resource that have associated data model, relationships to other resources and also can respond to different methods and also can define resources as variables for intercepting requests for multiple child resources.

What is AWS Lambda Function?

AWS Lambda is used for uploading codes or business logic to the AWS infrastructure and aslo manages it, it is provided by Amazon.This uploading code is known as Lamda Function, we can use the code as -
An event driven service which triggers on some change like a change in the data of an S3 bucket or a Dynamo DB table.
As the back-end of an AWS API gateway.


How to add CloudFront in front of API Gateway?

Here is a CloudFormation resource object that has all the required configuration:

CloudFront:  
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Enabled: true
        IPV6Enabled: true
        HttpVersion: http2
        Comment: !Join [ &#39;--&#39;, [!Ref &#39;AWS::StackName&#39;, &#39; Cloud Front&#39;]]
        Aliases: [!Ref CloudFrontCname]
        ViewerCertificate:
          AcmCertificateArn: !Ref AcmCertificateArn
          SslSupportMethod: sni-only
          MinimumProtocolVersion: TLSv1.1_2016
        Origins:
        - Id: APIGOrigin
          DomainName: !Sub
            - ${apigId}.execute-api.${AWS::Region}.amazonaws.com
            - { apigId: !Ref ApiGatewayLambdaProxy }
          OriginPath: !Sub
            - /${Stage}
            - { Stage: !Select [ "0", !Split [ &#39;--&#39;, !Ref &#39;AWS::StackName&#39; ] ] }
          CustomOriginConfig:
            # HTTPPort: 80
            HTTPSPort: 443
            OriginProtocolPolicy: https-only
          OriginCustomHeaders:
            - HeaderName: &#39;Verify-From-Cf&#39;
              HeaderValue: !Ref VerifyFromCfHeaderVal
        DefaultCacheBehavior:
          AllowedMethods: ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
          CachedMethods: ["GET", "HEAD", "OPTIONS"]
          ForwardedValues:
            Headers:
            - Access-Control-Request-Headers
            - Access-Control-Request-Method
            - Origin
            - Authorization
            # - Host APIG needs to use SNI
            QueryString: true
          TargetOriginId: APIGOrigin
          ViewerProtocolPolicy: https-only
          Compress: true
          DefaultTTL: 0
        CustomErrorResponses:
        - ErrorCachingMinTTL: 0
          ErrorCode: 400
        - ErrorCachingMinTTL: 1
          ErrorCode: 403
        - ErrorCachingMinTTL: 5
          ErrorCode: 500
  DNSARecord:    
    Type: AWS::Route53::RecordSet
    Properties:
      Comment: !Ref &#39;AWS::StackName&#39;
      Name: !Ref CloudFrontCname
      Type: A
      HostedZoneName: !Join [&#39;.&#39;, [ !Select [1, !Split [&#39;.&#39;, !Ref CloudFrontCname]], !Select [2, !Split [&#39;.&#39;, !Ref CloudFrontCname]], &#39;&#39;]]
      AliasTarget:
        HostedZoneId: !Ref Route53HostedZoneId
        DNSName: !GetAtt CloudFront.DomainName
  DNSAAAARecord:    
    Type: AWS::Route53::RecordSet
    Properties:
      Comment: !Ref &#39;AWS::StackName&#39;
      Name: !Ref CloudFrontCname
      Type: AAAA
      HostedZoneName: !Join [&#39;.&#39;, [ !Select [1, !Split [&#39;.&#39;, !Ref CloudFrontCname]], !Select [2, !Split [&#39;.&#39;, !Ref CloudFrontCname]], &#39;&#39;]]
      AliasTarget:
        HostedZoneId: !Ref Route53HostedZoneId
        DNSName: !GetAtt CloudFront.DomainName


How can we use API Gateway to create HTTP APIs?

HTTP APIs are designed for low latency, cost effective integrations with the services also including with AWS Lambda and HTTP endpoints.HTTP also supports OIDC and OAuth authorization and supports CORS and automatic deployments.Previous-generation REST APIs currently offer more features.
HTTP APIs helps in enabling us for creating RESTful APIs with lower latency and lower cost than RESTAPIs.It also helps in sending mrequests to the AWS Lambda functions to any routable HTTP endpoints.We can also create an HTTP APIs that integrates with a lambda functions on the function.


How can we find the API endpoint of a lambda function?

Lambda function that has an exposed API Gateway endpoint, and I can get the URL for that via the AWS console.
import boto3

apigw = boto3.client('apigateway')

def get_rest_api_internal_endpoint(api_id, stage_name, region=None):
    if region is None:
        region = apigw.meta.region_name
    return f"https://{api_id}.execute-api.{region}.amazonaws.com/{stage_name}"

def get_rest_api_public_endpoints(api_id, stage_name):
    endpoints = []
    for item in apigw.get_domain_names().get('items',[]):
        domain_name = item['domainName']
        for mapping in apigw.get_base_path_mappings(domainName=domain_name).get('items', []):
            if mapping['restApiId'] == api_id and mapping['stage'] == stage_name:
                path = mapping['basePath']
                endpoint = f"https://{domain_name}"
                if path != "(none)":
                    endpoint += path
                endpoints.append(endpoint)
    return endpoints


How can we call an API Gateway API?

The app developer helps in working with API Gateway Service component for API execution which is named executeapi, that is used for invoking API which was created or deployed in an API Gateway.These underlying programming entities that are exposed by the created API and there are several ways for calling an API.

What are the types of API ?

There are 2 types of API:
RESTful APIs--
Used for optimizing the serverless workloads and HTTP backends using HTTP APIs, it is required for API proxy functionality and API management features in a single solution, API Gateway also offers REST APIs.
WEBSOCKET APIs--
These are built real time two way communication applications like chat apps and streaming dashboards.It also maintains persistent connection for handling messages for transfering between our backend service and our clients.


How can we get the list of APIs and their IDs?


aws apigateway get-rest-apis


How can we find the arn of an API Gateway stage?

{region}::/restapis/{rest_api_id}/stages/{stage_name}


How can we integrate API Gateway with SQS?

The following is the configuration for the method:
PostMethod:
    Type: "AWS::ApiGateway::Method"
    Properties:
      ApiKeyRequired: "true"
      HttpMethod: "POST"
      ResourceId: !Ref "SomeResource"
      RestApiId: !Ref "SomeRestApi"
      Integration:
        IntegrationHttpMethod: "POST"
        IntegrationResponses:
        - StatusCode: 200
        Type: "AWS"
        Uri: "arn:aws:apigateway:${AWS::Region}:sqs:action/SendMessage"


How to debug AWS API Gateway & Lambda's AWS/ApiGateway 5XXError?

We need to create an IAM role to allow API Gateway to push logs to CloudWatch:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:DescribeLogGroups",
                "logs:DescribeLogStreams",
                "logs:PutLogEvents",
                "logs:GetLogEvents",
                "logs:FilterLogEvents"
            ],
            "Resource": "*"
        }
    ]