

Ceci est le guide du développeur du AWS CDK v2. L'ancien CDK v1 est entré en maintenance le 1er juin 2022 et a pris fin le 1er juin 2023.

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

# Tutoriel : Création d'une application Hello World sans serveur
<a name="serverless-example"></a>

Dans ce didacticiel, vous allez utiliser le AWS Cloud Development Kit (AWS CDK) pour créer une `Hello World` application sans serveur simple qui implémente un backend d'API de base composé des éléments suivants :
+  **API REST Amazon API Gateway** : fournit un point de terminaison HTTP utilisé pour appeler votre fonction via une requête HTTP GET.
+  AWS Fonction **Lambda : fonction** qui renvoie un `Hello World!` message lorsqu'elle est invoquée avec le point de terminaison HTTP.
+  **Intégrations et autorisations** : détails de configuration et autorisations permettant à vos ressources d'interagir entre elles et d'effectuer des actions, telles que la rédaction de journaux sur Amazon CloudWatch.

Le diagramme suivant montre les composants de cette application :

![\[Schéma d'une fonction Lambda invoquée lorsque vous envoyez une requête GET au point de terminaison API Gateway.\]](http://docs.aws.amazon.com/fr_fr/cdk/v2/guide/images/serverless-example-01.png)


Dans le cadre de ce didacticiel, vous allez créer et interagir avec votre application en suivant les étapes suivantes :

1. Créez un projet AWS CDK.

1. Définissez une fonction Lambda et une API REST API Gateway à l'aide des constructions L2 de la bibliothèque Construct. AWS 

1. Déployez votre application dans le AWS cloud.

1. Interagissez avec votre application dans le AWS cloud.

1. Supprimez l'exemple d'application du AWS cloud.

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

Avant de commencer ce didacticiel, exécutez les tâches suivantes :
+ Créez un AWS compte et installez et AWS configurez l'interface de ligne de AWS commande (CLI).
+ Installez Node.js et`npm`.
+ Installez le kit d'outils CDK globalement, en utilisant`npm install -g aws-cdk`.

Pour plus d'informations, consultez [Commencer à utiliser le AWS CDK.](getting-started.md)

Nous recommandons également une compréhension de base des éléments suivants :
+  [Qu'est-ce que le AWS CDK ?](home.md) pour une introduction de base au AWS CDK.
+  [Apprenez les concepts de base du AWS CDK](core-concepts.md) pour avoir un aperçu des concepts de base du AWS CDK.

## Étape 1 : Création d'un projet CDK
<a name="serverless-example-project"></a>

Au cours de cette étape, vous créez un nouveau projet CDK à l'aide de la AWS commande CDK `cdk init` CLI.

 **Pour créer un projet CDK**   

1. À partir du répertoire de départ de votre choix, créez et naviguez vers un répertoire de projet nommé `cdk-hello-world` sur votre machine :

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

1. Utilisez la `cdk init` commande pour créer un nouveau projet dans le langage de programmation de votre choix :  
**Example**  

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

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

   Installez les bibliothèques AWS CDK :

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

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

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

   Installez les bibliothèques AWS CDK :

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

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

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

   Activez l'environnement virtuel :

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

   Installez les bibliothèques AWS CDK et les dépendances du projet :

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

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

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

   Installez les bibliothèques AWS CDK et les dépendances du projet :

   ```
   $ mvn package
   ```

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

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

   Installez les bibliothèques AWS CDK et les dépendances du projet :

   ```
   $ dotnet restore src
   ```

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

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

   Installez les dépendances du projet :

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

------

   La CLI CDK crée un projet avec la structure suivante :  
**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
   ```

------

La CLI CDK crée automatiquement une application CDK contenant une seule pile. L'instance de l'application CDK est créée à partir de la ` [App](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.App.html) ` classe. Voici une partie de votre fichier de candidature CDK :

**Example**  
Situé dans `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', {
});
```
Situé dans `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', {
});
```
Situé dans `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()
```
Situé dans `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();
    }
}
```
Situé dans `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();
        }
    }
}
```
Situé dans `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
}
```

## Étape 2 : Création de votre fonction Lambda
<a name="serverless-example-function"></a>

Dans votre projet CDK, créez un `lambda` répertoire qui inclut un nouveau `hello.js` fichier. Voici un exemple :

**Example**  
À partir de la racine de votre projet, exécutez ce qui suit :  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Les éléments suivants devraient maintenant être ajoutés à votre projet CDK :  

```
cdk-hello-world
└── lambda
    └── hello.js
```
À partir de la racine de votre projet, exécutez ce qui suit :  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Les éléments suivants devraient maintenant être ajoutés à votre projet CDK :  

```
cdk-hello-world
└── lambda
    └── hello.js
```
À partir de la racine de votre projet, exécutez ce qui suit :  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Les éléments suivants devraient maintenant être ajoutés à votre projet CDK :  

```
cdk-hello-world
└── lambda
    └── hello.js
```
À partir de la racine de votre projet, exécutez ce qui suit :  

```
$ mkdir -p src/main/resources/lambda
$ cd src/main/resources/lambda
$ touch hello.js
```
Les éléments suivants devraient maintenant être ajoutés à votre projet CDK :  

```
cdk-hello-world
└── src
    └── main
        └──resources
            └──lambda
                └──hello.js
```
À partir de la racine de votre projet, exécutez ce qui suit :  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Les éléments suivants devraient maintenant être ajoutés à votre projet CDK :  

```
cdk-hello-world
└── lambda
    └── hello.js
```
À partir de la racine de votre projet, exécutez ce qui suit :  

```
$ mkdir lambda && cd lambda
$ touch hello.js
```
Les éléments suivants devraient maintenant être ajoutés à votre projet CDK :  

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

**Note**  
Pour simplifier ce didacticiel, nous utilisons une fonction JavaScript Lambda pour tous les langages de programmation CDK.

Définissez votre fonction Lambda en ajoutant ce qui suit au fichier nouvellement créé :

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

## Étape 3 : Définissez vos constructions
<a name="serverless-example-constructs"></a>

Au cours de cette étape, vous allez définir vos ressources Lambda et API Gateway à l'aide des constructions AWS CDK L2.

Ouvrez le fichier de projet qui définit votre pile de CDK. Vous allez modifier ce fichier pour définir vos constructions. Voici un exemple de votre fichier de pile de départ :

**Example**  
Situé dans `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

  }
}
```
Situé dans `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 }
```
Situé dans `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
```
Situé dans `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
    }
}
```
Situé dans `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
        }
    }
}
```
Situé à l'adresse `cdk-hello-world.go` suivante :  

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

}
```

Dans ce fichier, le AWS CDK effectue les opérations suivantes :
+ Votre instance de stack CDK est instanciée à partir de la classe. ` [Stack](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html) `
+ La classe ` [Constructs](https://docs.aws.amazon.com/cdk/api/v2/docs/constructs-readme.html) ` de base est importée et fournie en tant que portée ou parent de votre instance de stack.

### Définissez votre ressource de fonction Lambda
<a name="serverless-example-constructs-lambda"></a>

Pour définir votre ressource de fonction Lambda, vous devez importer et utiliser la construction ` [aws-lambda](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda-readme.html) ` L2 depuis la AWS bibliothèque de constructions.

Modifiez votre fichier de pile comme suit :

**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
        )
```
Nous importons le `aws_lambda` module `\_lambda` car il `lambda` s'agit d'un identifiant intégré en 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
}

// ...
```

Ici, vous créez une ressource de fonction Lambda et définissez les propriétés suivantes :
+  `runtime`— L'environnement dans lequel la fonction s'exécute. Ici, nous utilisons la version 20.x de Node.js.
+  `code`— Le chemin d'accès au code de fonction sur votre machine locale.
+  `handler`— Le nom du fichier spécifique qui contient votre code de fonction.

### Définissez votre ressource d'API REST API Gateway
<a name="serverless-example-constructs-api"></a>

Pour définir votre REST API ressource API Gateway, vous devez importer et utiliser la construction ` [aws-apigateway](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway-readme.html) ` L2 depuis la bibliothèque AWS Construct.

Modifiez votre fichier de pile comme suit :

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

// ...
```

Ici, vous créez une ressource d'API REST API Gateway, ainsi que les éléments suivants :
+ Une intégration entre l'API REST et votre fonction Lambda, permettant à l'API d'appeler votre fonction. Cela inclut la création d'une ressource d'autorisation Lambda.
+ Nouveau nom `hello` de ressource ou de chemin ajouté à la racine du point de terminaison de l'API. Cela crée un nouveau point de terminaison qui `/hello` s'ajoute à votre URL de base.
+ Méthode GET pour la `hello` ressource. Lorsqu'une requête GET est envoyée au point de `/hello` terminaison, la fonction Lambda est invoquée et sa réponse est renvoyée.

## Étape 4 : préparer votre application pour le déploiement
<a name="serverless-example-deploy-prepare"></a>

Au cours de cette étape, vous préparez votre application pour le déploiement en créant, si nécessaire, et en effectuant une validation de base à l'aide de la `cdk synth` commande AWS CDK CLI.

Si nécessaire, créez votre application :

**Example**  
À partir de la racine de votre projet, exécutez ce qui suit :  

```
$ npm run build
```
Il n'est pas nécessaire de construire.
Il n'est pas nécessaire de construire.
À partir de la racine de votre projet, exécutez ce qui suit :  

```
$ mvn package
```
À partir de la racine de votre projet, exécutez ce qui suit :  

```
$ dotnet build src
```
Il n'est pas nécessaire de construire.

Exécutez `cdk synth` pour synthétiser un AWS CloudFormation modèle à partir de votre code CDK. En utilisant des constructions L2, de nombreux détails de configuration requis AWS CloudFormation pour faciliter l'interaction entre votre fonction Lambda et l'API REST vous sont fournis par le CDK. AWS 

À partir de la racine de votre projet, exécutez ce qui suit :

```
$ cdk synth
```

**Note**  
Si le message d'erreur suivant s'affiche, vérifiez que vous êtes bien dans le `cdk-hello-world` répertoire et réessayez :  

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

En cas de succès, la CLI AWS CDK affichera le AWS CloudFormation modèle au `YAML` format à l'invite de commande. Un modèle `JSON` formaté est également enregistré dans le `cdk.out` répertoire.

Voici un exemple de sortie du AWS CloudFormation modèle :

### AWS CloudFormation modèle
<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.
```

En utilisant des constructions L2, vous définissez quelques propriétés pour configurer vos ressources et utilisez des méthodes d'assistance pour les intégrer ensemble. Le AWS CDK configure la majorité des AWS CloudFormation ressources et des propriétés nécessaires au provisionnement de votre application.

## Étape 5 : déployer votre application
<a name="serverless-example-deploy"></a>

Au cours de cette étape, vous utilisez la `cdk deploy` commande AWS CDK CLI pour déployer votre application. Le AWS CDK travaille avec le AWS CloudFormation service pour mettre à disposition vos ressources.

**Important**  
Vous devez effectuer un démarrage unique de votre AWS environnement avant le déploiement. Pour obtenir des instructions, consultez [Bootstrap votre environnement pour l'utiliser avec le AWS CDK](bootstrapping-env.md).

À partir de la racine de votre projet, exécutez ce qui suit. Confirmez les modifications si vous y êtes invité :

```
$ cdk deploy

✨  Synthesis time: 2.44s

...

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

Une fois le déploiement terminé, la CLI AWS CDK affiche l'URL de votre point de terminaison. Copiez cette URL pour l'étape suivante. Voici un exemple :

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

## Étape 6 : Interagissez avec votre application
<a name="serverless-example-interact"></a>

Au cours de cette étape, vous lancez une requête GET à destination de votre point de terminaison d'API et recevez la réponse de votre fonction Lambda.

Localisez l'URL de votre point de terminaison à l'étape précédente et ajoutez le `/hello` chemin. Ensuite, à l'aide de votre navigateur ou de votre invite de commande, envoyez une requête GET à votre terminal. Voici un exemple :

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

Félicitations, vous avez créé, déployé et interagi avec succès avec votre application à l'aide du AWS CDK \$1

## Étape 7 : Supprimer votre application
<a name="serverless-example-delete"></a>

Au cours de cette étape, vous utilisez la CLI AWS CDK pour supprimer votre application du AWS cloud.

Pour supprimer votre application, exécutez`cdk destroy`. Lorsque vous y êtes invité, confirmez votre demande de suppression de l'application :

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

## Dépannage
<a name="serverless-example-troubleshooting"></a>

### Erreur : \$1"message » : « Erreur interne du serveur"\$1 %
<a name="serverless-example-trobuleshooting-error1"></a>

Lorsque vous appelez la fonction Lambda déployée, vous recevez cette erreur. Cette erreur peut se produire pour plusieurs raisons.

 **Pour résoudre d'autres problèmes**   
Utilisez la AWS CLI pour appeler votre fonction Lambda.  

1. Modifiez votre fichier de pile pour capturer la valeur de sortie du nom de votre fonction Lambda déployée. Voici un exemple :

   ```
   ...
   
   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. Déployez à nouveau votre application. La CLI AWS CDK affichera la valeur du nom de votre fonction Lambda déployée :

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

1. Utilisez la AWS CLI pour appeler votre fonction Lambda dans le AWS Cloud et générer la réponse dans un fichier texte :

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

1. Vérifiez `output.txt` vos résultats.  
 **Cause possible : la ressource API Gateway est définie de manière incorrecte dans votre fichier de pile**   
Si `output.txt` la réponse de la fonction Lambda est réussie, le problème vient peut-être de la façon dont vous avez défini votre API REST API Gateway. La AWS CLI appelle directement votre Lambda, et non via votre point de terminaison. Vérifiez votre code pour vous assurer qu'il correspond à ce didacticiel. Ensuite, déployez à nouveau.  
 **Cause possible : la ressource Lambda n'est pas définie correctement dans votre fichier de pile**   
S'il `output.txt` renvoie une erreur, le problème peut être lié à la façon dont vous avez défini votre fonction Lambda. Vérifiez votre code pour vous assurer qu'il correspond à ce didacticiel. Déployez ensuite à nouveau.