

Dies ist der AWS CDK v2-Entwicklerhandbuch. Das ältere CDK v1 wurde am 1. Juni 2022 in die Wartung aufgenommen und der Support wurde am 1. Juni 2023 eingestellt.

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# Tutorial: Eine serverlose Hello World-Anwendung erstellen
<a name="serverless-example"></a>

In diesem Tutorial verwenden Sie das AWS Cloud Development Kit (AWS CDK), um eine einfache serverlose `Hello World` Anwendung zu erstellen, die ein grundlegendes API-Backend implementiert, das aus den folgenden Komponenten besteht:
+  **Amazon API Gateway REST API** — Stellt einen HTTP-Endpunkt bereit, der verwendet wird, um Ihre Funktion über eine HTTP-GET-Anfrage aufzurufen.
+  ** AWS Lambda-Funktion — Funktion**, die eine `Hello World!` Nachricht zurückgibt, wenn sie mit dem HTTP-Endpunkt aufgerufen wird.
+  **Integrationen und Berechtigungen** — Konfigurationsdetails und Berechtigungen für Ihre Ressourcen, miteinander zu interagieren und Aktionen auszuführen, wie z. B. das Schreiben von Protokollen an Amazon CloudWatch.

Das folgende Diagramm zeigt die Komponenten dieser Anwendung:

![\[Diagramm einer Lambda-Funktion, die aufgerufen wird, wenn Sie eine GET-Anfrage an den API-Gateway-Endpunkt senden.\]](http://docs.aws.amazon.com/de_de/cdk/v2/guide/images/serverless-example-01.png)


In diesem Tutorial werden Sie Ihre Anwendung in den folgenden Schritten erstellen und mit ihr interagieren:

1. Erstellen Sie ein AWS CDK-Projekt.

1. Definieren Sie eine Lambda-Funktion und eine API-Gateway-REST-API mithilfe von L2-Konstrukten aus der AWS Construct-Bibliothek.

1. Stellen Sie Ihre Anwendung in der Cloud bereit. AWS 

1. Interagieren Sie mit Ihrer Anwendung in der AWS Cloud.

1. Löschen Sie die Beispielanwendung aus der AWS Cloud.

## Voraussetzungen
<a name="serverless-example-pre"></a>

Bevor Sie mit diesem Tutorial beginnen, müssen Sie folgende Aufgaben ausführen:
+ Erstellen Sie ein AWS Konto und lassen Sie die AWS Befehlszeilenschnittstelle (AWS CLI) installieren und konfigurieren.
+ Installieren Sie Node.js und`npm`.
+ Installieren Sie das CDK Toolkit global unter Verwendung von. `npm install -g aws-cdk`

Weitere Informationen finden Sie unter [Erste Schritte mit dem AWS CDK](getting-started.md).

Wir empfehlen außerdem ein grundlegendes Verständnis der folgenden Themen:
+  [Was ist das AWS CDK?](home.md) für eine grundlegende Einführung in das AWS CDK.
+  [Lernen Sie die AWS CDK-Kernkonzepte](core-concepts.md) kennen, um einen Überblick über die Kernkonzepte des AWS CDK zu erhalten.

## Schritt 1: Erstellen Sie ein CDK-Projekt
<a name="serverless-example-project"></a>

In diesem Schritt erstellen Sie mit dem `cdk init` CDK-CLI-Befehl ein neues AWS CDK-Projekt.

 **Um ein CDK-Projekt zu erstellen**   

1. Erstellen Sie von einem Startverzeichnis Ihrer Wahl aus ein Projektverzeichnis mit dem Namen `cdk-hello-world` auf Ihrem Computer und navigieren Sie zu diesem:

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

1. Verwenden Sie den `cdk init` Befehl, um ein neues Projekt in Ihrer bevorzugten Programmiersprache zu erstellen:  
**Example**  

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

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

   Installieren Sie AWS CDK-Bibliotheken:

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

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

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

    AWS CDK-Bibliotheken installieren:

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

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

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

   Aktivieren Sie die virtuelle Umgebung:

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

   Installieren Sie AWS CDK-Bibliotheken und Projektabhängigkeiten:

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

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

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

   Installieren Sie AWS CDK-Bibliotheken und Projektabhängigkeiten:

   ```
   $ mvn package
   ```

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

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

   Installieren Sie AWS CDK-Bibliotheken und Projektabhängigkeiten:

   ```
   $ dotnet restore src
   ```

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

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

   Installieren Sie die Projektabhängigkeiten:

   ```
   $ 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
   ```

------

   Die CDK-CLI erstellt ein Projekt mit der folgenden Struktur:  
**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
   ```

------

Die CDK-CLI erstellt automatisch eine CDK-App, die einen einzelnen Stack enthält. Die CDK-App-Instanz wird aus der Klasse erstellt. ` [App](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.App.html) ` Das Folgende ist ein Teil Ihrer CDK-Anwendungsdatei:

**Example**  
Befindet sich in`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', {
});
```
Befindet sich in`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', {
});
```
Befindet sich in`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()
```
Befindet sich in`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();
    }
}
```
Befindet sich in`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();
        }
    }
}
```
Befindet sich in`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
}
```

## Schritt 2: Erstellen Sie Ihre Lambda-Funktion
<a name="serverless-example-function"></a>

Erstellen Sie in Ihrem CDK-Projekt ein `lambda` Verzeichnis, das eine neue `hello.js` Datei enthält. Im Folgenden wird ein Beispiel gezeigt:

**Example**  
Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Folgendes sollte jetzt zu Ihrem CDK-Projekt hinzugefügt werden:  

```
cdk-hello-world
└── lambda
    └── hello.js
```
Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Folgendes sollte jetzt zu Ihrem CDK-Projekt hinzugefügt werden:  

```
cdk-hello-world
└── lambda
    └── hello.js
```
Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Folgendes sollte jetzt zu Ihrem CDK-Projekt hinzugefügt werden:  

```
cdk-hello-world
└── lambda
    └── hello.js
```
Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:  

```
$ mkdir -p src/main/resources/lambda
$ cd src/main/resources/lambda
$ touch hello.js
```
Folgendes sollte jetzt zu Ihrem CDK-Projekt hinzugefügt werden:  

```
cdk-hello-world
└── src
    └── main
        └──resources
            └──lambda
                └──hello.js
```
Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Folgendes sollte jetzt zu Ihrem CDK-Projekt hinzugefügt werden:  

```
cdk-hello-world
└── lambda
    └── hello.js
```
Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Folgendes sollte jetzt zu Ihrem CDK-Projekt hinzugefügt werden:  

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

**Anmerkung**  
Um dieses Tutorial einfach zu halten, verwenden wir eine JavaScript Lambda-Funktion für alle CDK-Programmiersprachen.

Definieren Sie Ihre Lambda-Funktion, indem Sie der neu erstellten Datei Folgendes hinzufügen:

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

## Schritt 3: Definieren Sie Ihre Konstrukte
<a name="serverless-example-constructs"></a>

In diesem Schritt definieren Sie Ihre Lambda- und API-Gateway-Ressourcen mithilfe von AWS CDK L2-Konstrukten.

Öffnen Sie die Projektdatei, die Ihren CDK-Stack definiert. Sie werden diese Datei ändern, um Ihre Konstrukte zu definieren. Das Folgende ist ein Beispiel für Ihre Start-Stack-Datei:

**Example**  
Befindet sich in`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

  }
}
```
Befindet sich in`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 }
```
Befindet sich in`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
```
Befindet sich in`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
    }
}
```
Befindet sich in`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
        }
    }
}
```
Befindet sich in`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

}
```

In dieser Datei macht das AWS CDK Folgendes:
+ Ihre CDK-Stack-Instanz wird aus der Klasse instanziiert. ` [Stack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html) `
+ Die ` [Constructs](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs-readme.html) ` Basisklasse wird importiert und als Bereich oder übergeordnetes Objekt Ihrer Stack-Instance bereitgestellt.

### Definieren Sie Ihre Lambda-Funktionsressource
<a name="serverless-example-constructs-lambda"></a>

Um Ihre Lambda-Funktionsressource zu definieren, importieren und verwenden Sie das ` [aws-lambda](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda-readme.html) ` L2-Konstrukt aus der AWS Construct-Bibliothek.

Ändern Sie Ihre Stack-Datei wie folgt:

**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
        )
```
Wir importieren das `aws_lambda` Modul, `\_lambda` weil `lambda` es ein integrierter Bezeichner in Python ist.

```
// ...
// 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
}

// ...
```

Hier erstellen Sie eine Lambda-Funktionsressource und definieren die folgenden Eigenschaften:
+  `runtime`— Die Umgebung, in der die Funktion ausgeführt wird. Hier verwenden wir Node.js Version 20.x.
+  `code`— Der Pfad zum Funktionscode auf Ihrem lokalen Computer.
+  `handler`— Der Name der spezifischen Datei, die Ihren Funktionscode enthält.

### Definieren Sie Ihre API-Gateway-REST-API-Ressource
<a name="serverless-example-constructs-api"></a>

Um Ihre REST API API-Gateway-Ressource zu definieren, importieren und verwenden Sie das ` [aws-apigateway](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway-readme.html) ` L2-Konstrukt aus der AWS Construct-Bibliothek.

Ändern Sie Ihre Stack-Datei wie folgt:

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

// ...
```

Hier erstellen Sie eine API-Gateway-REST-API-Ressource zusammen mit den folgenden Informationen:
+ Eine Integration zwischen der REST-API und Ihrer Lambda-Funktion, sodass die API Ihre Funktion aufrufen kann. Dies beinhaltet die Erstellung einer Lambda-Berechtigungsressource.
+ Eine neue Ressource oder ein neuer Pfad mit dem Namen`hello`, der dem Stamm des API-Endpunkts hinzugefügt wird. Dadurch wird ein neuer Endpunkt erstellt, der `/hello` zu Ihrer Basis-URL hinzugefügt wird.
+ Eine GET-Methode für die `hello` Ressource. Wenn eine GET-Anfrage an den `/hello` Endpunkt gesendet wird, wird die Lambda-Funktion aufgerufen und ihre Antwort zurückgegeben.

## Schritt 4: Bereiten Sie Ihre Anwendung für die Bereitstellung vor
<a name="serverless-example-deploy-prepare"></a>

In diesem Schritt bereiten Sie Ihre Anwendung für die Bereitstellung vor, indem Sie, falls erforderlich, eine grundlegende Validierung mit dem AWS `cdk synth` CDK-CLI-Befehl erstellen und durchführen.

Falls erforderlich, erstellen Sie Ihre Anwendung:

**Example**  
Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:  

```
$ npm run build
```
Ein Gebäude ist nicht erforderlich.
Ein Gebäude ist nicht erforderlich.
Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:  

```
$ mvn package
```
Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:  

```
$ dotnet build src
```
Ein Gebäude ist nicht erforderlich.

Führen Sie aus`cdk synth`, um eine AWS CloudFormation Vorlage aus Ihrem CDK-Code zu synthetisieren. Durch die Verwendung von L2-Konstrukten werden Ihnen viele der Konfigurationsdetails, die AWS CloudFormation zur Erleichterung der Interaktion zwischen Ihrer Lambda-Funktion und der REST-API erforderlich sind, vom CDK bereitgestellt. AWS 

Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:

```
$ cdk synth
```

**Anmerkung**  
Wenn Sie eine Fehlermeldung wie die folgende erhalten, überprüfen Sie, ob Sie sich im `cdk-hello-world` Verzeichnis befinden, und versuchen Sie es erneut:  

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

Bei Erfolg gibt die AWS CDK-CLI die AWS CloudFormation Vorlage an der Eingabeaufforderung im `YAML` Format aus. Eine `JSON` formatierte Vorlage wird ebenfalls im Verzeichnis gespeichert. `cdk.out`

Im Folgenden finden Sie ein Beispiel für die Ausgabe der AWS CloudFormation Vorlage:

### AWS CloudFormation Vorlage
<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.
```

Mithilfe von L2-Konstrukten definieren Sie einige Eigenschaften, um Ihre Ressourcen zu konfigurieren, und verwenden Hilfsmethoden, um sie miteinander zu integrieren. Das AWS CDK konfiguriert den Großteil Ihrer AWS CloudFormation Ressourcen und Eigenschaften, die für die Bereitstellung Ihrer Anwendung erforderlich sind.

## Schritt 5: Ihre Anwendung bereitstellen
<a name="serverless-example-deploy"></a>

In diesem Schritt verwenden Sie den AWS `cdk deploy` CDK-CLI-Befehl, um Ihre Anwendung bereitzustellen. Das AWS CDK arbeitet mit dem AWS CloudFormation Service zusammen, um Ihre Ressourcen bereitzustellen.

**Wichtig**  
Sie müssen vor der Bereitstellung ein einmaliges Bootstrapping Ihrer AWS Umgebung durchführen. Anweisungen finden Sie unter [Bootstrap Ihrer Umgebung für die Verwendung mit dem CDK](bootstrapping-env.md). AWS 

Führen Sie im Stammverzeichnis Ihres Projekts den folgenden Befehl aus. Bestätigen Sie Änderungen, wenn Sie dazu aufgefordert werden:

```
$ cdk deploy

✨  Synthesis time: 2.44s

...

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

Wenn die Bereitstellung abgeschlossen ist, gibt die AWS CDK-CLI Ihre Endpunkt-URL aus. Kopieren Sie diese URL für den nächsten Schritt. Im Folgenden wird ein Beispiel gezeigt:

```
...
✅  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
...
```

## Schritt 6: Interagieren Sie mit Ihrer Anwendung
<a name="serverless-example-interact"></a>

In diesem Schritt initiieren Sie eine GET-Anfrage an Ihren API-Endpunkt und erhalten Ihre Lambda-Funktionsantwort.

Suchen Sie Ihre Endpunkt-URL aus dem vorherigen Schritt und fügen Sie den `/hello` Pfad hinzu. Senden Sie dann über Ihren Browser oder die Befehlszeile eine GET-Anfrage an Ihren Endpunkt. Im Folgenden wird ein Beispiel gezeigt:

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

Herzlichen Glückwunsch\$1 Sie haben Ihre Anwendung mithilfe des AWS CDK erfolgreich erstellt, bereitgestellt und mit ihr interagiert\$1

## Schritt 7: Löschen Sie Ihre Anwendung
<a name="serverless-example-delete"></a>

In diesem Schritt verwenden Sie die AWS CDK-CLI, um Ihre Anwendung aus der AWS Cloud zu löschen.

Führen `cdk destroy` Sie den Befehl aus, um Ihre Anwendung zu löschen. Wenn Sie dazu aufgefordert werden, bestätigen Sie Ihre Anfrage zum Löschen der Anwendung:

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

## Fehlersuche
<a name="serverless-example-troubleshooting"></a>

### Fehler: \$1"Nachricht“: „Interner Serverfehler"\$1%
<a name="serverless-example-trobuleshooting-error1"></a>

Wenn Sie die bereitgestellte Lambda-Funktion aufrufen, erhalten Sie diesen Fehler. Dieser Fehler kann aus mehreren Gründen auftreten.

 **Um weitere Fehler zu beheben**   
Verwenden Sie die AWS CLI, um Ihre Lambda-Funktion aufzurufen.  

1. Ändern Sie Ihre Stack-Datei, um den Ausgabewert Ihres bereitgestellten Lambda-Funktionsnamens zu erfassen. Im Folgenden wird ein Beispiel gezeigt:

   ```
   ...
   
   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. Stellen Sie Ihre Anwendung erneut bereit. Die AWS CDK-CLI gibt den Wert Ihres bereitgestellten Lambda-Funktionsnamens aus:

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

1. Verwenden Sie die AWS CLI, um Ihre Lambda-Funktion in der AWS Cloud aufzurufen und die Antwort in eine Textdatei auszugeben:

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

1. Überprüfen Sie`output.txt`, um Ihre Ergebnisse zu sehen.  
 **Mögliche Ursache: Die API-Gateway-Ressource ist in Ihrer Stack-Datei falsch definiert**   
Wenn eine erfolgreiche Lambda-Funktionsantwort `output.txt` angezeigt wird, liegt das Problem möglicherweise daran, wie Sie Ihre API-Gateway-REST-API definiert haben. Die AWS CLI ruft Ihr Lambda direkt auf, nicht über Ihren Endpunkt. Überprüfen Sie Ihren Code, um sicherzustellen, dass er mit diesem Tutorial übereinstimmt. Stellen Sie es dann erneut bereit.  
 **Mögliche Ursache: Die Lambda-Ressource ist in Ihrer Stack-Datei falsch definiert**   
Wenn ein Fehler `output.txt` zurückgegeben wird, liegt das Problem möglicherweise daran, wie Sie Ihre Lambda-Funktion definiert haben. Überprüfen Sie Ihren Code, um sicherzustellen, dass er mit diesem Tutorial übereinstimmt. Stellen Sie es dann erneut bereit.