

Este é o Guia do desenvolvedor do AWS CDK v2. O CDK v1 antigo entrou em manutenção em 1º de junho de 2022 e encerrou o suporte em 1º de junho de 2023.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# Tutorial: Criar uma aplicação Hello World em tecnologia sem servidor
<a name="serverless-example"></a>

Neste tutorial, você usará o kit de desenvolvimento em nuvem da AWS (CDK da AWS) para criar uma aplicação simples `Hello World` em tecnologia sem servidor que implemente um backend de API básico composto pelo seguinte:
+  **API REST do Amazon API Gateway**: fornece um endpoint de HTTP que é usado para invocar sua função por meio de uma solicitação HTTP GET.
+  **Função do AWS Lambda**: função que retorna uma mensagem `Hello World!` quando invocada com o endpoint de HTTP.
+  **Integrações e permissões** — Detalhes de configuração e permissões para que seus recursos interajam entre si e realizem ações, como gravar logs no Amazon CloudWatch.

O diagrama a seguir mostra os componentes deste aplicação:

![\[Diagrama de uma função do Lambda que é invocada quando você envia uma solicitação GET ao endpoint do API Gateway.\]](http://docs.aws.amazon.com/pt_br/cdk/v2/guide/images/serverless-example-01.png)


Neste tutorial, você criará e interagirá com a aplicação nas seguintes etapas:

1. Criação de um projeto do AWS CDK

1. Definir uma função do Lambda e a API REST do API Gateway usando constructos L2 da Biblioteca de Constructos da AWS.

1. Implantação da sua aplicação na Nuvem AWS.

1. Interação com sua aplicação na Nuvem AWS.

1. Exclusão da aplicação de exemplo da Nuvem AWS.

## Pré-requisitos
<a name="serverless-example-pre"></a>

Antes de começar este tutorial, conclua as seguintes etapas:
+ Crie uma conta da AWS e tenha a interface de linha de comandos (AWS CLI) da AWS instalada e configurada.
+ Instale o Node.js e o `npm`
+ Instalar o Kit de Ferramentas CDK globalmente, usando `npm install -g aws-cdk`.

Para obter mais informações, consulte [Conceitos básicos do AWS CDK](getting-started.md).

Também recomendamos uma compreensão básica do seguinte:
+  [O que é o AWS CDK?](home.md) para uma introdução básica ao AWS CDK.
+  [Saiba mais dobre os principais conceitos do AWS CDK](core-concepts.md) para uma visão geral dos principais conceitos do AWS CDK.

## Etapa 1: criar um projeto do CDK
<a name="serverless-example-project"></a>

Nesta etapa, você cria um novo projeto do CDK usando o comando `cdk init` da CLI do AWS CDK.

 **Para criar um projeto do CDK**   

1. Em um diretório inicial de sua escolha, crie e navegue até um diretório de projeto chamado `cdk-hello-world` na sua máquina:

   ```
   $ mkdir cdk-hello-world && cd cdk-hello-world
   ```

1. Use o comando `cdk init` para criar um novo projeto na linguagem de programação de sua preferência:  
**Example**  

------
#### [ TypeScript ]

   ```
   $ cdk init --language typescript
   ```

   Instale as bibliotecas do AWS CDK:

   ```
   $ npm install aws-cdk-lib constructs
   ```

------
#### [ JavaScript ]

   ```
   $ cdk init --language javascript
   ```

   Instale as bibliotecas do AWS CDK:

   ```
   $ npm install aws-cdk-lib constructs
   ```

------
#### [ Python ]

   ```
   $ cdk init --language python
   ```

   Ative o ambiente virtual:

   ```
   $ source .venv/bin/activate # On Windows, run '.\venv\Scripts\activate' instead
   ```

   Instale as bibliotecas do AWS e as dependências do projeto:

   ```
   (.venv)$ python3 -m pip install -r requirements.txt
   ```

------
#### [ Java ]

   ```
   $ cdk init --language java
   ```

   Instale as bibliotecas do AWS e as dependências do projeto:

   ```
   $ mvn package
   ```

------
#### [ C\$1 ]

   ```
   $ cdk init --language csharp
   ```

   Instale as bibliotecas do AWS e as dependências do projeto:

   ```
   $ dotnet restore src
   ```

------
#### [ Go ]

   ```
   $ cdk init --language go
   ```

   Instalar dependências do projeto:

   ```
   $ go get github.com/aws/aws-cdk-go/awscdk/v2
   $ go get github.com/aws/aws-cdk-go/awscdk/v2/awslambda
   $ go get github.com/aws/aws-cdk-go/awscdk/v2/awsapigateway
   $ go mod tidy
   ```

------

   A CLI do CDK cria um projeto com a estrutura a seguir:  
**Example**  

------
#### [ TypeScript ]

   ```
   cdk-hello-world
   ├── .git
   ├── .gitignore
   ├── .npmignore
   ├── README.md
   ├── bin
   │   └── cdk-hello-world.ts
   ├── cdk.json
   ├── jest.config.js
   ├── lib
   │   └── cdk-hello-world-stack.ts
   ├── node_modules
   ├── package-lock.json
   ├── package.json
   ├── test
   │   └── cdk-hello-world.test.ts
   └── tsconfig.json
   ```

------
#### [ JavaScript ]

   ```
   cdk-hello-world
   ├── .git
   ├── .gitignore
   ├── .npmignore
   ├── README.md
   ├── bin
   │   └── cdk-hello-world.js
   ├── cdk.json
   ├── jest.config.js
   ├── lib
   │   └── cdk-hello-world-stack.js
   ├── node_modules
   ├── package-lock.json
   ├── package.json
   └── test
       └── cdk-hello-world.test.js
   ```

------
#### [ Python ]

   ```
   cdk-hello-world
   ├── .git
   ├── .gitignore
   ├── .venv
   ├── README.md
   ├── app.py
   ├── cdk.json
   ├── cdk_hello_world
   │   ├── __init__.py
   │   └── cdk_hello_world_stack.py
   ├── requirements-dev.txt
   ├── requirements.txt
   ├── source.bat
   └── tests
   ```

------
#### [ Java ]

   ```
   cdk-hello-world
   ├── .git
   ├── .gitignore
   ├── README.md
   ├── cdk.json
   ├── pom.xml
   ├── src
   │   ├── main
   │   │   └── java
   │   │       └── com
   │   │           └── myorg
   │   │               ├── CdkHelloWorldApp.java
   │   │               └── CdkHelloWorldStack.java
   └── target
   ```

------
#### [ C\$1 ]

   ```
   cdk-hello-world
   ├── .git
   ├── .gitignore
   ├── README.md
   ├── cdk.json
   └── src
       ├── CdkHelloWorld
       │   ├── CdkHelloWorld.csproj
       │   ├── CdkHelloWorldStack.cs
       │   ├── GlobalSuppressions.cs
       │   └── Program.cs
       └── CdkHelloWorld.sln
   ```

------
#### [ Go ]

   ```
   cdk-hello-world
   ├── .git
   ├── .gitignore
   ├── README.md
   ├── cdk-hello-world.go
   ├── cdk-hello-world_test.go
   ├── cdk.json
   ├── go.mod
   └── go.sum
   ```

------

A CLI do CDK cria automaticamente uma aplicação do CDK que contém uma única pilha. A instância da aplicação CDK é criada a partir da classe ` [App](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.App.html) `. A seguir está uma parte do seu arquivo de aplicação CDK:

**Example**  
Localizado em `bin/cdk-hello-world.ts`:  

```
#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { CdkHelloWorldStack } from '../lib/cdk-hello-world-stack';

const app = new cdk.App();
new CdkHelloWorldStack(app, 'CdkHelloWorldStack', {
});
```
Localizado em `bin/cdk-hello-world.js`:  

```
#!/usr/bin/env node
const cdk = require('aws-cdk-lib');
const { CdkHelloWorldStack } = require('../lib/cdk-hello-world-stack');
const app = new cdk.App();
new CdkHelloWorldStack(app, 'CdkHelloWorldStack', {
});
```
Localizado em `app.py`:  

```
#!/usr/bin/env python3
import os
import aws_cdk as cdk
from cdk_hello_world.cdk_hello_world_stack import CdkHelloWorldStack

app = cdk.App()
CdkHelloWorldStack(app, "CdkHelloWorldStack",)
app.synth()
```
Localizado em `src/main/java/…​/CdkHelloWorldApp.java`:  

```
package com.myorg;

import software.amazon.awscdk.App;
import software.amazon.awscdk.Environment;
import software.amazon.awscdk.StackProps;

import java.util.Arrays;

public class JavaApp {
    public static void main(final String[] args) {
        App app = new App();

        new JavaStack(app, "JavaStack", StackProps.builder()
                .build());

        app.synth();
    }
}
```
Localizado em `src/CdkHelloWorld/Program.cs`:  

```
using Amazon.CDK;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CdkHelloWorld
{
    sealed class Program
    {
        public static void Main(string[] args)
        {
            var app = new App();
            new CdkHelloWorldStack(app, "CdkHelloWorldStack", new StackProps
            {

            });
            app.Synth();
        }
    }
}
```
Localizado em `cdk-hello-world.go`:  

```
package main
import (
    "github.com/aws/aws-cdk-go/awscdk/v2"
    "github.com/aws/constructs-go/constructs/v10"
    "github.com/aws/jsii-runtime-go"
)

// ...

func main() {
    defer jsii.Close()
    app := awscdk.NewApp(nil)
    NewCdkHelloWorldStack(app, "CdkHelloWorldStack", &CdkHelloWorldStackProps{
        awscdk.StackProps{
            Env: env(),
        },
    })
    app.Synth(nil)
}

func env() *awscdk.Environment {
    return nil
}
```

## Etapa 2: Criar sua função do Lambda
<a name="serverless-example-function"></a>

Em seu projeto do CDK, crie um diretório `lambda` que inclua um novo arquivo `hello.js`. Veja um exemplo a seguir:

**Example**  
Da raiz do seu projeto, execute o seguinte:  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Agora, o seguinte deve ser adicionado ao seu projeto do CDK:  

```
cdk-hello-world
└── lambda
    └── hello.js
```
Da raiz do seu projeto, execute o seguinte:  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Agora, o seguinte deve ser adicionado ao seu projeto do CDK:  

```
cdk-hello-world
└── lambda
    └── hello.js
```
Da raiz do seu projeto, execute o seguinte:  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Agora, o seguinte deve ser adicionado ao seu projeto do CDK:  

```
cdk-hello-world
└── lambda
    └── hello.js
```
Da raiz do seu projeto, execute o seguinte:  

```
$ mkdir -p src/main/resources/lambda
$ cd src/main/resources/lambda
$ touch hello.js
```
Agora, o seguinte deve ser adicionado ao seu projeto do CDK:  

```
cdk-hello-world
└── src
    └── main
        └──resources
            └──lambda
                └──hello.js
```
Da raiz do seu projeto, execute o seguinte:  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Agora, o seguinte deve ser adicionado ao seu projeto do CDK:  

```
cdk-hello-world
└── lambda
    └── hello.js
```
Da raiz do seu projeto, execute o seguinte:  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Agora, o seguinte deve ser adicionado ao seu projeto do CDK:  

```
cdk-hello-world
└── lambda
    └── hello.js
```

**nota**  
Para manter este tutorial simples, usamos uma função do Lambda de JavaScript para todas as linguagens de programação do CDK.

Defina a função do Lambda adicionando o arquivo recém-criado:

```
exports.handler = async (event) => {
    return {
        statusCode: 200,
        headers: { "Content-Type": "text/plain" },
        body: JSON.stringify({ message: "Hello, World!" }),
    };
};
```

## Etapa 3: definir seus constructos
<a name="serverless-example-constructs"></a>

Nesta etapa, você definirá seus recursos do Lambda e do API Gateway usando constructos L2 do CDK da AWS.

Abra o arquivo do projeto que define sua pilha do CDK. Você modificará esse arquivo para definir seus constructos. Veja a seguir um exemplo do arquivo de pilha inicial:

**Example**  
Localizado em `lib/cdk-hello-world-stack.ts`:  

```
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';

export class CdkHelloWorldStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Your constructs will go here

  }
}
```
Localizado em `lib/cdk-hello-world-stack.js`:  

```
const { Stack, Duration } = require('aws-cdk-lib');
const lambda = require('aws-cdk-lib/aws-lambda');
const apigateway = require('aws-cdk-lib/aws-apigateway');

class CdkHelloWorldStack extends Stack {

  constructor(scope, id, props) {
    super(scope, id, props);

    // Your constructs will go here

  }
}

module.exports = { CdkHelloWorldStack }
```
Localizado em `cdk_hello_world/cdk_hello_world_stack.py`:  

```
from aws_cdk import Stack
from constructs import Construct

class CdkHelloWorldStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

          // Your constructs will go here
```
Localizado em `src/main/java/…​/CdkHelloWorldStack.java`:  

```
package com.myorg;

import software.constructs.Construct;
import software.amazon.awscdk.Stack;
import software.amazon.awscdk.StackProps;

public class CdkHelloWorldStack extends Stack {
    public CdkHelloWorldStack(final Construct scope, final String id) {
        this(scope, id, null);
    }

    public CdkHelloWorldStack(final Construct scope, final String id, final StackProps props) {
        super(scope, id, props);

        // Your constructs will go here
    }
}
```
Localizado em `src/CdkHelloWorld/CdkHelloWorldStack.cs`:  

```
using Amazon.CDK;
using Constructs;

namespace CdkHelloWorld
{
    public class CdkHelloWorldStack : Stack
    {
        internal CdkHelloWorldStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            // Your constructs will go here
        }
    }
}
```
Localizado em `cdk-hello-world.go`:  

```
package main

import (
    "github.com/aws/aws-cdk-go/awscdk/v2"
    "github.com/aws/constructs-go/constructs/v10"
    "github.com/aws/jsii-runtime-go"
)

type CdkHelloWorldStackProps struct {
    awscdk.StackProps
}

func NewCdkHelloWorldStack(scope constructs.Construct, id string, props *CdkHelloWorldStackProps) awscdk.Stack {
    var sprops awscdk.StackProps
    if props != nil {
        sprops = props.StackProps
    }
    stack := awscdk.NewStack(scope, &id, &sprops)

    // Your constructs will go here

    return stack
}

func main() {

    // ...

}

func env() *awscdk.Environment {

    return nil

}
```

Nesse arquivo, o AWS CDK está fazendo o seguinte:
+ Sua instância de pilha do CDK é instanciada a partir da classe ` [Stack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html) `.
+ A classe base ` [Constructs](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs-readme.html) ` é importada e fornecida como escopo ou pai da sua instância de pilha.

### Definir recursos da sua função do Lambda
<a name="serverless-example-constructs-lambda"></a>

Para definir o recurso da sua função do Lambda, você importa e usa o constructo ` [aws-lambda](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda-readme.html) ` L2 da Biblioteca de Constructos da AWS.

Modifique seu arquivo de pilha da seguinte forma:

**Example**  

```
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
// Import Lambda L2 construct
import * as lambda from 'aws-cdk-lib/aws-lambda';

export class CdkHelloWorldStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Define the Lambda function resource
    const helloWorldFunction = new lambda.Function(this, 'HelloWorldFunction', {
      runtime: lambda.Runtime.NODEJS_20_X, // Choose any supported Node.js runtime
      code: lambda.Code.fromAsset('lambda'), // Points to the lambda directory
      handler: 'hello.handler', // Points to the 'hello' file in the lambda directory
    });
  }
}
```

```
const { Stack, Duration } = require('aws-cdk-lib');
// Import Lambda L2 construct
const lambda = require('aws-cdk-lib/aws-lambda');


class CdkHelloWorldStack extends Stack {
  constructor(scope, id, props) {
    super(scope, id, props);

    // Define the Lambda function resource
    const helloWorldFunction = new lambda.Function(this, 'HelloWorldFunction', {
      runtime: lambda.Runtime.NODEJS_20_X, // Choose any supported Node.js runtime
      code: lambda.Code.fromAsset('lambda'), // Points to the lambda directory
      handler: 'hello.handler', // Points to the 'hello' file in the lambda directory
    });
  }
}

module.exports = { CdkHelloWorldStack }
```

```
from aws_cdk import (
    Stack,
    # Import Lambda L2 construct
    aws_lambda as _lambda,
)
# ...

class CdkHelloWorldStack(Stack):

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # Define the Lambda function resource
        hello_world_function = _lambda.Function(
            self,
            "HelloWorldFunction",
            runtime = _lambda.Runtime.NODEJS_20_X, # Choose any supported Node.js runtime
            code = _lambda.Code.from_asset("lambda"), # Points to the lambda directory
            handler = "hello.handler", # Points to the 'hello' file in the lambda directory
        )
```
Importamos o módulo `aws_lambda` como `\_lambda` porque `lambda` é um identificador embutido no Python.

```
// ...
// Import Lambda L2 construct
import software.amazon.awscdk.services.lambda.Code;
import software.amazon.awscdk.services.lambda.Function;
import software.amazon.awscdk.services.lambda.Runtime;

public class CdkHelloWorldStack extends Stack {
    public CdkHelloWorldStack(final Construct scope, final String id) {
        this(scope, id, null);
    }

    public CdkHelloWorldStack(final Construct scope, final String id, final StackProps props) {
        super(scope, id, props);

        // Define the Lambda function resource
        Function helloWorldFunction = Function.Builder.create(this, "HelloWorldFunction")
                .runtime(Runtime.NODEJS_20_X)  // Choose any supported Node.js runtime
                .code(Code.fromAsset("src/main/resources/lambda")) // Points to the lambda directory
                .handler("hello.handler")  // Points to the 'hello' file in the lambda directory
                .build();
    }
}
```

```
// ...
// Import Lambda L2 construct
using Amazon.CDK.AWS.Lambda;

namespace CdkHelloWorld
{
    public class CdkHelloWorldStack : Stack
    {
        internal CdkHelloWorldStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            // Define the Lambda function resource
            var helloWorldFunction = new Function(this, "HelloWorldFunction", new FunctionProps
            {
                Runtime = Runtime.NODEJS_20_X, // Choose any supported Node.js runtime
                Code = Code.FromAsset("lambda"), // Points to the lambda directory
                Handler = "hello.handler" // Points to the 'hello' file in the lambda directory
            });
        }
    }
}
```

```
package main

import (
    // ...
    // Import Lambda L2 construct
    "github.com/aws/aws-cdk-go/awscdk/v2/awslambda"
    // Import S3 assets construct
    "github.com/aws/aws-cdk-go/awscdk/v2/awss3assets"
    // ...
)

// ...

func NewCdkHelloWorldStack(scope constructs.Construct, id string, props *CdkHelloWorldStackProps) awscdk.Stack {
    var sprops awscdk.StackProps
    if props != nil {
        sprops = props.StackProps
    }
    stack := awscdk.NewStack(scope, &id, &sprops)

    // Define the Lambda function resource
    helloWorldFunction := awslambda.NewFunction(stack, jsii.String("HelloWorldFunction"), &awslambda.FunctionProps{
        Runtime: awslambda.Runtime_NODEJS_20_X(), // Choose any supported Node.js runtime
        Code:    awslambda.Code_FromAsset(jsii.String("lambda"), &awss3assets.AssetOptions{}), // Points to the lambda directory
        Handler: jsii.String("hello.handler"), // Points to the 'hello' file in the lambda directory
    })

    return stack
}

// ...
```

Aqui, você cria um recurso de função do Lambda e define as propriedades a seguir:
+  `runtime` — O ambiente em que a função é executada. Aqui, usamos o Node.js versão 20.x.
+  `code` — O caminho para o código de função em sua máquina local.
+  `handler` — O nome do arquivo específico que contém seu código de função.

### Definição do seu recurso API REST do API Gateway
<a name="serverless-example-constructs-api"></a>

Para definir seu recurso do REST API do API Gateway, você importa e usa o constructo ` [aws-apigateway](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway-readme.html) ` L2 da Biblioteca de Constructos da AWS.

Modifique seu arquivo de pilha da seguinte forma:

**Example**  

```
// ...
//Import API Gateway L2 construct
import * as apigateway from 'aws-cdk-lib/aws-apigateway';


export class CdkHelloWorldStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // ...

    // Define the API Gateway resource
    const api = new apigateway.LambdaRestApi(this, 'HelloWorldApi', {
      handler: helloWorldFunction,
      proxy: false,
    });

    // Define the '/hello' resource with a GET method
    const helloResource = api.root.addResource('hello');
    helloResource.addMethod('GET');
  }
}
```

```
// ...
// Import API Gateway L2 construct
const apigateway = require('aws-cdk-lib/aws-apigateway');


class CdkHelloWorldStack extends Stack {
  constructor(scope, id, props) {
    super(scope, id, props);

    // ...

    // Define the API Gateway resource
    const api = new apigateway.LambdaRestApi(this, 'HelloWorldApi', {
      handler: helloWorldFunction,
      proxy: false,
    });

    // Define the '/hello' resource with a GET method
    const helloResource = api.root.addResource('hello');
    helloResource.addMethod('GET');
  };
};

// ...
```

```
from aws_cdk import (
    # ...
    # Import API Gateway L2 construct
    aws_apigateway as apigateway,
)
from constructs import Construct

class CdkHelloWorldStack(Stack):

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # ...

        # Define the API Gateway resource
        api = apigateway.LambdaRestApi(
            self,
            "HelloWorldApi",
            handler = hello_world_function,
            proxy = False,
        )

        # Define the '/hello' resource with a GET method
        hello_resource = api.root.add_resource("hello")
        hello_resource.add_method("GET")
```

```
// ...
// Import API Gateway L2 construct
import software.amazon.awscdk.services.apigateway.LambdaRestApi;
import software.amazon.awscdk.services.apigateway.Resource;

public class CdkHelloWorldStack extends Stack {
    public CdkHelloWorldStack(final Construct scope, final String id) {
        this(scope, id, null);
    }

    public CdkHelloWorldStack(final Construct scope, final String id, final StackProps props) {
        super(scope, id, props);

        // ...

        // Define the API Gateway resource
        LambdaRestApi api = LambdaRestApi.Builder.create(this, "HelloWorldApi")
                .handler(helloWorldFunction)
                .proxy(false) // Turn off default proxy integration
                .build();

        // Define the '/hello' resource and its GET method
        Resource helloResource = api.getRoot().addResource("hello");
        helloResource.addMethod("GET");
    }
}
```

```
// ...
// Import API Gateway L2 construct
using Amazon.CDK.AWS.APIGateway;

namespace CdkHelloWorld
{
    public class CdkHelloWorldStack : Stack
    {
        internal CdkHelloWorldStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
           // ...

            // Define the API Gateway resource
            var api = new LambdaRestApi(this, "HelloWorldApi", new LambdaRestApiProps
            {
                Handler = helloWorldFunction,
                Proxy = false
            });

            // Add a '/hello' resource with a GET method
            var helloResource = api.Root.AddResource("hello");
            helloResource.AddMethod("GET");
        }
    }
}
```

```
// ...

import (
    // ...
    // Import Api Gateway L2 construct
    "github.com/aws/aws-cdk-go/awscdk/v2/awsapigateway"
    // ...
)

// ...

func NewCdkHelloWorldStack(scope constructs.Construct, id string, props *CdkHelloWorldStackProps) awscdk.Stack {
    var sprops awscdk.StackProps
    if props != nil {
        sprops = props.StackProps
    }
    stack := awscdk.NewStack(scope, &id, &sprops)

    // Define the Lambda function resource
    // ...

    // Define the API Gateway resource
    api := awsapigateway.NewLambdaRestApi(stack, jsii.String("HelloWorldApi"), &awsapigateway.LambdaRestApiProps{
        Handler: helloWorldFunction,
        Proxy: jsii.Bool(false),
    })

    // Add a '/hello' resource with a GET method
    helloResource := api.Root().AddResource(jsii.String("hello"), &awsapigateway.ResourceOptions{})
    helloResource.AddMethod(jsii.String("GET"), awsapigateway.NewLambdaIntegration(helloWorldFunction, &awsapigateway.LambdaIntegrationOptions{}), &awsapigateway.MethodOptions{})

    return stack
}

// ...
```

Aqui, você cria um recurso API REST do API Gateway, junto com o seguinte:
+ Uma integração entre a API REST e sua função do Lambda, permitindo que a API invoque sua função. Isso inclui a criação de um recurso de permissão do Lambda.
+ Um novo recurso ou caminho chamado `hello` que é adicionado à raiz do endpoint da API. Isso cria um novo endpoint que adiciona o `/hello` ao seu URL básico.
+ Um método GET para o recurso `hello`. Quando uma solicitação GET é enviada ao endpoint `/hello`, você invoca a função do Lambda e retorna a resposta.

## Etapa 4: preparar sua aplicação para a implantação
<a name="serverless-example-deploy-prepare"></a>

Nesta etapa, você prepara sua aplicação para implantação criando, se necessário, e executando a validação básica com o comando `cdk synth` da CLI do AWS CDK.

Se necessário, crie sua aplicação:

**Example**  
Da raiz do seu projeto, execute o seguinte:  

```
$ npm run build
```
Não é necessário compilar.
Não é necessário compilar.
Da raiz do seu projeto, execute o seguinte:  

```
$ mvn package
```
Da raiz do seu projeto, execute o seguinte:  

```
$ dotnet build src
```
Não é necessário compilar.

Execute `cdk synth` para sintetizar um modelo do AWS CloudFormation a partir do seu código do CDK. Ao usar constructos L2, muitos dos detalhes de configuração necessários pelo AWS CloudFormation para facilitar a interação entre sua função do Lambda e a API REST são provisionados para você pelo CDK da AWS.

Da raiz do seu projeto, execute o seguinte:

```
$ cdk synth
```

**nota**  
Se você receber um erro como o seguinte, verifique se você está no diretório `cdk-hello-world` e tente novamente:  

```
--app is required either in command-line, in cdk.json or in ~/.cdk.json
```

Se tiver êxito, a CLI do AWS CDK exibirá o modelo do AWS CloudFormation em formato `YAML` no prompt de comando. Um modelo formatado `JSON` também é salvo no diretório `cdk.out`.

Veja a seguir um exemplo de saída do modelo do AWS CloudFormation:

### Modelo do AWS CloudFormation
<a name="serverless-example-deploy-cfn"></a>

```
Resources:
  HelloWorldFunctionServiceRoleunique-identifier:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
        Version: "2012-10-17"		 	 	 
      ManagedPolicyArns:
        - Fn::Join:
            - ""
            - - "arn:"
              - Ref: AWS::Partition
              - :iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
    Metadata:
      aws:cdk:path: CdkHelloWorldStack/HelloWorldFunction/ServiceRole/Resource
  HelloWorldFunctionunique-identifier:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket:
          Fn::Sub: cdk-unique-identifier-assets-${AWS::AccountId}-${AWS::Region}
        S3Key: unique-identifier.zip
      Handler: hello.handler
      Role:
        Fn::GetAtt:
          - HelloWorldFunctionServiceRoleunique-identifier
          - Arn
      Runtime: nodejs20.x
    DependsOn:
      - HelloWorldFunctionServiceRoleunique-identifier
    Metadata:
      aws:cdk:path: CdkHelloWorldStack/HelloWorldFunction/Resource
      aws:asset:path: asset.unique-identifier
      aws:asset:is-bundled: false
      aws:asset:property: Code
  HelloWorldApiunique-identifier:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Name: HelloWorldApi
    Metadata:
      aws:cdk:path: CdkHelloWorldStack/HelloWorldApi/Resource
  HelloWorldApiDeploymentunique-identifier:
    Type: AWS::ApiGateway::Deployment
    Properties:
      Description: Automatically created by the RestApi construct
      RestApiId:
        Ref: HelloWorldApiunique-identifier
    DependsOn:
      - HelloWorldApihelloGETunique-identifier
      - HelloWorldApihellounique-identifier
    Metadata:
      aws:cdk:path: CdkHelloWorldStack/HelloWorldApi/Deployment/Resource
  HelloWorldApiDeploymentStageprod012345ABC:
    Type: AWS::ApiGateway::Stage
    Properties:
      DeploymentId:
        Ref: HelloWorldApiDeploymentunique-identifier
      RestApiId:
        Ref: HelloWorldApiunique-identifier
      StageName: prod
    Metadata:
      aws:cdk:path: CdkHelloWorldStack/HelloWorldApi/DeploymentStage.prod/Resource
  HelloWorldApihellounique-identifier:
    Type: AWS::ApiGateway::Resource
    Properties:
      ParentId:
        Fn::GetAtt:
          - HelloWorldApiunique-identifier
          - RootResourceId
      PathPart: hello
      RestApiId:
        Ref: HelloWorldApiunique-identifier
    Metadata:
      aws:cdk:path: CdkHelloWorldStack/HelloWorldApi/Default/hello/Resource
  HelloWorldApihelloGETApiPermissionCdkHelloWorldStackHelloWorldApiunique-identifier:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:InvokeFunction
      FunctionName:
        Fn::GetAtt:
          - HelloWorldFunctionunique-identifier
          - Arn
      Principal: apigateway.amazonaws.com
      SourceArn:
        Fn::Join:
          - ""
          - - "arn:"
            - Ref: AWS::Partition
            - ":execute-api:"
            - Ref: AWS::Region
            - ":"
            - Ref: AWS::AccountId
            - ":"
            - Ref: HelloWorldApi9E278160
            - /
            - Ref: HelloWorldApiDeploymentStageprodunique-identifier
            - /GET/hello
    Metadata:
      aws:cdk:path: CdkHelloWorldStack/HelloWorldApi/Default/hello/GET/ApiPermission.CdkHelloWorldStackHelloWorldApiunique-identifier.GET..hello
  HelloWorldApihelloGETApiPermissionTestCdkHelloWorldStackHelloWorldApiunique-identifier:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:InvokeFunction
      FunctionName:
        Fn::GetAtt:
          - HelloWorldFunctionunique-identifier
          - Arn
      Principal: apigateway.amazonaws.com
      SourceArn:
        Fn::Join:
          - ""
          - - "arn:"
            - Ref: AWS::Partition
            - ":execute-api:"
            - Ref: AWS::Region
            - ":"
            - Ref: AWS::AccountId
            - ":"
            - Ref: HelloWorldApiunique-identifier
            - /test-invoke-stage/GET/hello
    Metadata:
      aws:cdk:path: CdkHelloWorldStack/HelloWorldApi/Default/hello/GET/ApiPermission.Test.CdkHelloWorldStackHelloWorldApiunique-identifier.GET..hello
  HelloWorldApihelloGETunique-identifier:
    Type: AWS::ApiGateway::Method
    Properties:
      AuthorizationType: NONE
      HttpMethod: GET
      Integration:
        IntegrationHttpMethod: POST
        Type: AWS_PROXY
        Uri:
          Fn::Join:
            - ""
            - - "arn:"
              - Ref: AWS::Partition
              - ":apigateway:"
              - Ref: AWS::Region
              - :lambda:path/2015-03-31/functions/
              - Fn::GetAtt:
                  - HelloWorldFunctionunique-identifier
                  - Arn
              - /invocations
      ResourceId:
        Ref: HelloWorldApihellounique-identifier
      RestApiId:
        Ref: HelloWorldApiunique-identifier
    Metadata:
      aws:cdk:path: CdkHelloWorldStack/HelloWorldApi/Default/hello/GET/Resource
  CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
      Analytics: v2:deflate64:unique-identifier
    Metadata:
      aws:cdk:path: CdkHelloWorldStack/CDKMetadata/Default
    Condition: CDKMetadataAvailable
Outputs:
  HelloWorldApiEndpointunique-identifier:
    Value:
      Fn::Join:
        - ""
        - - https://
          - Ref: HelloWorldApiunique-identifier
          - .execute-api.
          - Ref: AWS::Region
          - "."
          - Ref: AWS::URLSuffix
          - /
          - Ref: HelloWorldApiDeploymentStageprodunique-identifier
          - /
Conditions:
  CDKMetadataAvailable:
    Fn::Or:
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - af-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-east-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-northeast-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-northeast-2
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-southeast-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-southeast-2
          - Fn::Equals:
              - Ref: AWS::Region
              - ca-central-1
          - Fn::Equals:
              - Ref: AWS::Region
              - cn-north-1
          - Fn::Equals:
              - Ref: AWS::Region
              - cn-northwest-1
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-central-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-north-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-2
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-3
          - Fn::Equals:
              - Ref: AWS::Region
              - il-central-1
          - Fn::Equals:
              - Ref: AWS::Region
              - me-central-1
          - Fn::Equals:
              - Ref: AWS::Region
              - me-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - sa-east-1
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - us-east-1
          - Fn::Equals:
              - Ref: AWS::Region
              - us-east-2
          - Fn::Equals:
              - Ref: AWS::Region
              - us-west-1
          - Fn::Equals:
              - Ref: AWS::Region
              - us-west-2
Parameters:
  BootstrapVersion:
    Type: AWS::SSM::Parameter::Value<String>
    Default: /cdk-bootstrap/hnb659fds/version
    Description: Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]
Rules:
  CheckBootstrapVersion:
    Assertions:
      - Assert:
          Fn::Not:
            - Fn::Contains:
                - - "1"
                  - "2"
                  - "3"
                  - "4"
                  - "5"
                - Ref: BootstrapVersion
        AssertDescription: CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI.
```

Ao usar constructos L2, você define algumas propriedades para configurar seus recursos e usa métodos auxiliares para integrá-los. O AWS CDK configura a maioria dos seus recursos do AWS CloudFormation e propriedades necessários para provisionar sua aplicação.

## Etapa 5: implantar a aplicação
<a name="serverless-example-deploy"></a>

Nesta etapa, você usa o comando `cdk deploy` da CLI do AWS CDK para implantar sua aplicação. O AWS CDK trabalha com o serviço do AWS CloudFormation para provisionar seus recursos.

**Importante**  
É necessário executar uma única inicialização do seu ambiente AWS antes da implantação. Para obter instruções, consulte [Bootstrapping do seu ambiente para uso com o AWS CDK](bootstrapping-env.md).

Da raiz do seu projeto, execute o seguinte. Confirme as alterações, se solicitado:

```
$ cdk deploy

✨  Synthesis time: 2.44s

...

Do you wish to deploy these changes (y/n)? <y>
```

Quando a implantação for concluída, a CLI do AWS CDK exibirá o URL do seu endpoint. Copie esse URL para a próxima etapa. Veja um exemplo a seguir:

```
...
✅  HelloWorldStack

✨  Deployment time: 45.37s

Outputs:
HelloWorldStack.HelloWorldApiEndpointunique-identifier = https://<api-id>.execute-api.<region>.amazonaws.com/prod/
Stack ARN:
arn:aws:cloudformation:region:account-id:stack/HelloWorldStack/unique-identifier
...
```

## Etapa 6: Interagir com sua aplicação
<a name="serverless-example-interact"></a>

Nesta etapa, você inicia uma solicitação GET para seu endpoint da API e recebe a resposta da sua função do Lambda.

Localize o URL do endpoint da etapa anterior e adicione o caminho `/hello`. Em seguida, usando seu navegador ou a linha de comando, envie uma solicitação GET para seu endpoint. Veja um exemplo a seguir:

```
$ curl https://<api-id>.execute-api.<region>.amazonaws.com/prod/hello
{"message":"Hello World!"}%
```

Parabéns, você criou, implantou e interagiu com sucesso com sua aplicação usando o AWS CDK\$1

## Etapa 7: Excluir sua aplicação
<a name="serverless-example-delete"></a>

Nesta etapa, você usa a CLI do AWS CDK para excluir sua aplicação da Nuvem AWS.

Para excluir sua aplicação, execute `cdk destroy`. Quando solicitado, confirme sua solicitação para excluir a aplicação:

```
$ cdk destroy
Are you sure you want to delete: CdkHelloWorldStack (y/n)? y
CdkHelloWorldStack: destroying... [1/1]
...
 ✅  CdkHelloWorldStack: destroyed
```

## Solução de problemas
<a name="serverless-example-troubleshooting"></a>

### Erro: \$1“message”: “Erro interno do servidor”\$1%
<a name="serverless-example-trobuleshooting-error1"></a>

Ao invocar a função do Lambda implantada, você recebe esse erro. Esse erro pode ocorrer por vários motivos.

 **Para solucionar problemas ainda mais**   
Use a AWS CLI para invocar sua função do Lambda.  

1. Modifique seu arquivo de pilha para capturar o valor de saída do nome da função do Lambda implantada. Veja um exemplo a seguir:

   ```
   ...
   
   class CdkHelloWorldStack extends Stack {
     constructor(scope, id, props) {
       super(scope, id, props);
   
       // Define the Lambda function resource
       // ...
   
       new CfnOutput(this, 'HelloWorldFunctionName', {
         value: helloWorldFunction.functionName,
         description: 'JavaScript Lambda function'
       });
   
       // Define the API Gateway resource
       // ...
     }
   }
   ```

1. Implante a aplicação novamente. A CLI do AWS CDK exibirá o valor do nome da função do Lambda implantada:

   ```
   $ cdk deploy
   
   ✨  Synthesis time: 0.29s
   ...
    ✅  CdkHelloWorldStack
   
   ✨  Deployment time: 20.36s
   
   Outputs:
   ...
   CdkHelloWorldStack.HelloWorldFunctionName = CdkHelloWorldStack-HelloWorldFunctionunique-identifier
   ...
   ```

1. Use a AWS CLI para invocar sua função do Lambda na Nuvem AWS e enviar a resposta para um arquivo de texto:

   ```
   $ aws lambda invoke --function-name CdkHelloWorldStack-HelloWorldFunctionunique-identifier output.txt
   ```

1. Verifique `output.txt` para ver seus resultados.  
 **Possível causa: o recurso API Gateway está definido incorretamente em seu arquivo de pilha**   
Se o `output.txt` mostrar uma resposta bem-sucedida da função do Lambda, o problema pode estar na forma como você definiu sua API REST do API Gateway. A AWS CLI invoca seu Lambda diretamente, não por meio de seu endpoint. Verifique seu código para garantir que ele corresponda a este tutorial. Em seguida, implante novamente.  
 **Possível causa: o recurso Lambda está definido incorretamente em seu arquivo de pilha**   
Se o `output.txt` retornar um erro, o problema pode estar na forma como você definiu sua função do Lambda. Verifique seu código para garantir que ele corresponda a este tutorial. Em seguida, implante novamente.