Selecione suas preferências de cookies

Usamos cookies essenciais e ferramentas semelhantes que são necessárias para fornecer nosso site e serviços. Usamos cookies de desempenho para coletar estatísticas anônimas, para que possamos entender como os clientes usam nosso site e fazer as devidas melhorias. Cookies essenciais não podem ser desativados, mas você pode clicar em “Personalizar” ou “Recusar” para recusar cookies de desempenho.

Se você concordar, a AWS e terceiros aprovados também usarão cookies para fornecer recursos úteis do site, lembrar suas preferências e exibir conteúdo relevante, incluindo publicidade relevante. Para aceitar ou recusar todos os cookies não essenciais, clique em “Aceitar” ou “Recusar”. Para fazer escolhas mais detalhadas, clique em “Personalizar”.

Tutorial: Criar uma aplicação Hello World em tecnologia sem servidor

Modo de foco
Tutorial: Criar uma aplicação Hello World em tecnologia sem servidor - AWS Cloud Development Kit (AWS CDK) v2

Este é o Guia do Desenvolvedor 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á.

Este é o Guia do Desenvolvedor 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á.

Neste tutorial, você usa o AWS Cloud Development Kit (AWS CDK) para criar um sistema simples sem servidor Hello World aplicativo que implementa um back-end básico de API que consiste no seguinte:

  • Amazon API Gateway REST API— Fornece um endpoint HTTP que é usado para invocar sua função por meio de um HTTP GET pedido.

  • AWS Lambda function — Função que retorna uma Hello World! mensagem quando invocada com o HTTP ponto final.

  • 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 registros na 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.

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

  1. Crie um AWS CDK projeto.

  2. Defina uma função Lambda e a API REST do API Gateway usando construções L2 da Construct Library. AWS

  3. Implante seu aplicativo no Nuvem AWS.

  4. Interaja com seu aplicativo no Nuvem AWS.

  5. Exclua a amostra da aplicação do Nuvem AWS.

Pré-requisitos

Antes de começar este tutorial, conclua as seguintes etapas:

  • Crie um Conta da AWS e tenha o AWS Command Line Interface (AWS CLI) instalado e configurado.

  • Instalar Node.js and npm.

  • Instalar o CDK Toolkit globalmente, usando npm install -g aws-cdk.

Para obter mais informações, consulte Começando com o AWS CDK.

Também recomendamos uma compreensão básica do seguinte:

Etapa 1: criar um projeto CDK

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

Para criar um projeto 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
  2. Use o comando cdk init para criar um novo projeto na linguagem de programação de sua preferência:

    TypeScript
    $ cdk init --language typescript

    Instale AWS CDK bibliotecas:

    $ npm install aws-cdk-lib constructs
    JavaScript
    $ cdk init --language javascript

    Instale AWS CDK bibliotecas:

    $ 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 AWS CDK bibliotecas e dependências do projeto:

    (.venv)$ python3 -m pip install -r requirements.txt
    Java
    $ cdk init --language java

    Instale AWS CDK bibliotecas e dependências do projeto:

    $ mvn package
    C#
    $ cdk init --language csharp

    Instale AWS CDK bibliotecas e 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
    $ cdk init --language typescript

    Instale AWS CDK bibliotecas:

    $ npm install aws-cdk-lib constructs

    O CDK CLI cria um projeto com a seguinte estrutura:

    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#
    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
    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

O CDK CLI cria automaticamente um aplicativo CDK que contém uma única pilha. A instância da aplicação CDK é criada a partir da classe App. A seguir está uma parte do seu arquivo de aplicação CDK:

TypeScript

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', { });
JavaScript

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', { });
Python

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()
Java

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(); } }
C#

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(); } } }
Go

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 }

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', { });

Etapa 2: Criar sua função do Lambda

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

TypeScript

Da raiz do seu projeto, execute o seguinte:

$ mkdir lambda && cd lambda $ touch hello.js

Agora, o seguinte deve ser adicionado ao seu projeto CDK:

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

Da raiz do seu projeto, execute o seguinte:

$ mkdir lambda && cd lambda $ touch hello.js

Agora, o seguinte deve ser adicionado ao seu projeto CDK:

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

Da raiz do seu projeto, execute o seguinte:

$ mkdir lambda && cd lambda $ touch hello.js

Agora, o seguinte deve ser adicionado ao seu projeto CDK:

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

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 CDK:

cdk-hello-world └── src └── main └──resources └──lambda └──hello.js
C#

Da raiz do seu projeto, execute o seguinte:

$ mkdir lambda && cd lambda $ touch hello.js

Agora, o seguinte deve ser adicionado ao seu projeto CDK:

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

Da raiz do seu projeto, execute o seguinte:

$ mkdir lambda && cd lambda $ touch hello.js

Agora, o seguinte deve ser adicionado ao seu projeto 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 CDK:

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

Para manter este tutorial simples, usamos um JavaScript Função Lambda para todas as linguagens de programação 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

Nesta etapa, você definirá seus recursos do Lambda e do API Gateway usando construções AWS CDK L2.

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

TypeScript

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 } }
JavaScript

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 }
Python

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
Java

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 } }
C#

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 } } }
Go

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 }

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 } }

Nesse arquivo, o AWS CDK está fazendo o seguinte:

  • Sua instância de pilha do CDK é instanciada a partir da classe Stack.

  • A classe base Constructs é importada e fornecida como escopo ou pai da sua instância de pilha.

Definir recursos da sua função do Lambda

Para definir seu recurso de função do Lambda, você importa e usa o constructo aws-lambda L2 da Biblioteca de Constructos da AWS .

Modifique seu arquivo de pilha da seguinte forma:

TypeScript
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 }); } }
JavaScript
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 }
Python
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 )
nota

Importamos o aws_lambda módulo _lambda porque lambda é um identificador embutido no Python.

Java
// ... // 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(); } }
C#
// ... // 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 }); } } }
Go
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 } // ...
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 }); } }

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 Node.js version 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.

Defina seu API Gateway REST API recurso

Para definir seu API Gateway REST API recurso, você importa e usa a construção aws-apigateway L2 da Construct Library. AWS

Modifique seu arquivo de pilha da seguinte forma:

TypeScript
// ... //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'); } }
JavaScript
// ... // 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'); }; }; // ...
Python
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")
Java
// ... // 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"); } }
C#
// ... // 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"); } } }
Go

// ... 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 } // ...
// ... //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'); } }

Aqui, você cria um API Gateway REST API recurso, junto com o seguinte:

  • Uma integração entre o REST API e sua função 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 é adicionado /hello à sua base URL.

  • 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

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

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

TypeScript

Da raiz do seu projeto, execute o seguinte:

$ npm run build
JavaScript

Não é necessário compilar.

Python

Não é necessário compilar.

Java

Da raiz do seu projeto, execute o seguinte:

$ mvn package
C#

Da raiz do seu projeto, execute o seguinte:

$ dotnet build src
Go

Não é necessário compilar.

Da raiz do seu projeto, execute o seguinte:

$ npm run build

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

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 for bem-sucedido, o AWS CDK CLI produzirá o AWS CloudFormation modelo em YAML formato no prompt de comando. A JSON o modelo formatado também é salvo no cdk.out diretório.

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

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.

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 AWS CloudFormation recursos e propriedades necessários para provisionar seu aplicativo.

Etapa 5: implantar a aplicação

Nesta etapa, você usa o AWS CDK CLI cdk deploycomando para implantar seu aplicativo. Ele AWS CDK trabalha com o AWS CloudFormation serviço para provisionar seus recursos.

Importante

Você deve executar uma única inicialização do seu AWS ambiente antes da implantação. Para obter instruções, consulte Inicialize seu ambiente para uso com o AWS CDK.

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, o AWS CDK CLI 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

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!

Etapa 7: Excluir sua aplicação

Nesta etapa, você usa o AWS CDK CLI para excluir seu aplicativo do 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

Erro: {“message”: “Erro interno do servidor”}%

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 o AWS CLI para invocar sua função 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 // ...
  2. Implante a aplicação novamente. O AWS CDK CLI exibirá o valor do nome da função Lambda implantada:

    $ cdk deploy ✨ Synthesis time: 0.29s ... ✅ CdkHelloWorldStack ✨ Deployment time: 20.36s Outputs: ... CdkHelloWorldStack.HelloWorldFunctionName = CdkHelloWorldStack-HelloWorldFunctionunique-identifier ...
  3. Use o AWS CLI para invocar sua função Lambda no e enviar Nuvem AWS a resposta para um arquivo de texto:

    $ aws lambda invoke --function-name CdkHelloWorldStack-HelloWorldFunctionunique-identifier output.txt
  4. 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. Ele 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.

PrivacidadeTermos do sitePreferências de cookies
© 2025, Amazon Web Services, Inc. ou suas afiliadas. Todos os direitos reservados.