

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Tutorial: Menyebarkan aplikasi Hello World dengan AWS SAM
<a name="serverless-getting-started-hello-world"></a>

Dalam tutorial ini, Anda menggunakan AWS Serverless Application Model Command Line Interface (AWS SAMCLI) untuk menyelesaikan yang berikut:
+ Menginisialisasi, membangun, dan menyebarkan contoh aplikasi **Hello World**.
+ Buat perubahan lokal dan sinkronkan ke AWS CloudFormation.
+ Lakukan pengujian lokal pada host pengembangan Anda.
+ Hapus aplikasi sampel dari file AWS Cloud.

Contoh aplikasi **Hello World** mengimplementasikan backend API dasar. Ini terdiri dari sumber daya berikut:
+ **Amazon API Gateway** — Titik akhir API yang akan Anda gunakan untuk menjalankan fungsi Anda.
+ **AWS Lambda**— Fungsi yang memproses permintaan HTTP API GET dan mengembalikan `hello world` pesan.
+ **AWS Identity and Access Management Peran (IAM)** — Memberikan izin bagi layanan untuk berinteraksi dengan aman.

Diagram berikut menunjukkan komponen untuk aplikasi ini:

![\[Diagram dari fungsi Lamda yang dipanggil ketika Anda mengirim permintaan GET ke titik akhir API Gateway.\]](http://docs.aws.amazon.com/id_id/serverless-application-model/latest/developerguide/images/gs-01.png)


**Topics**
+ [

## Prasyarat
](#serverless-getting-started-hello-world-prerequisites)
+ [

## Langkah 1: Inisialisasi contoh aplikasi Hello World
](#serverless-getting-started-hello-world-init)
+ [

## Langkah 2: Bangun aplikasi Anda
](#serverless-getting-started-hello-world-build)
+ [

## Langkah 3: Menyebarkan aplikasi Anda ke AWS Cloud
](#serverless-getting-started-hello-world-deploy)
+ [

## Langkah 4: Jalankan aplikasi Anda
](#serverless-getting-started-hello-world-run)
+ [

## Langkah 5: Berinteraksi dengan fungsi Anda di AWS Cloud
](#serverless-getting-started-hello-world-remote-invoke)
+ [

## Langkah 6: Ubah dan sinkronkan aplikasi Anda ke AWS Cloud
](#serverless-getting-started-hello-world-sync)
+ [

## Langkah 7: (Opsional) Uji aplikasi Anda secara lokal
](#serverless-getting-started-hello-world-test)
+ [

## Langkah 8: Hapus aplikasi Anda dari AWS Cloud
](#serverless-getting-started-hello-world-delete)
+ [

## Pemecahan masalah
](#serverless-getting-started-hello-world-troubleshoot)
+ [

## Pelajari selengkapnya
](#serverless-getting-started-hello-world-learn)

## Prasyarat
<a name="serverless-getting-started-hello-world-prerequisites"></a>

Verifikasi bahwa Anda telah menyelesaikan yang berikut ini:
+ [AWS SAM prasyarat](prerequisites.md)
+ [Instal AWS SAMCLI](install-sam-cli.md)

**catatan**  
Jika Anda lebih suka menggunakan Visual Studio Code untuk pengembangan tanpa server, lihat [Membuat aplikasi tanpa server](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/sam-get-started.html#serverless-apps-create) di Panduan Pengguna Toolkit for VS Code step-by-step untuk petunjuk menggunakan antarmuka VS Code. AWS 

## Langkah 1: Inisialisasi contoh aplikasi Hello World
<a name="serverless-getting-started-hello-world-init"></a>

Pada langkah ini, Anda akan menggunakan AWS SAMCLI untuk membuat contoh proyek aplikasi **Hello World** pada mesin lokal Anda.

**Untuk menginisialisasi contoh aplikasi Hello World**

1. Di baris perintah Anda, jalankan yang berikut dari direktori awal pilihan Anda:

   ```
   $ sam init
   ```
**catatan**  
Perintah ini menginisialisasi aplikasi tanpa server Anda dan membuat direktori proyek. Direktori berisi beberapa file dan folder, termasuk `template.yaml` file, yang merupakan AWS SAM template Anda.  
Versi Python yang diinstal harus cocok dengan `Runtime` properti yang ditentukan dalam. `template.yaml` Untuk beban kerja produksi, sebaiknya gunakan Python 3.12 atau versi sebelumnya yang didukung penuh di lingkungan. AWS Jika versi Python tidak cocok, Anda akan menemukan kesalahan build.  
Untuk mengatasi masalah kompatibilitas versi:  
 Tentukan [runtime](sam-cli-command-reference-sam-init.md#sam-cli-command-reference-sam-init-options-runtime) yang kompatibel selama inisialisasi: `sam init --runtime python3.9`
Ubah `Runtime` properti `template.yaml` setelah inisialisasi

1. Ini AWS SAMCLI akan memandu Anda melalui inisialisasi aplikasi baru. Konfigurasikan berikut ini:

   1. Pilih **AWS Quick Start Templates** untuk memilih template awal.

   1. Pilih template **Hello World Example** dan unduh.

   1. Gunakan Python runtime dan tipe `zip` paket.

   1. Untuk tutorial ini, pilih keluar dari AWS X-Ray tracing. Untuk mempelajari lebih lanjut, lihat [Apa itu AWS X-Ray?](https://docs.aws.amazon.com/xray/latest/devguide/aws-xray.html) di *Panduan AWS X-Ray Pengembang*.

   1. Untuk tutorial ini, pilih keluar dari pemantauan dengan Amazon CloudWatch Application Insights. Untuk mempelajari selengkapnya, lihat [Wawasan CloudWatch Aplikasi Amazon](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html) di *Panduan CloudWatch Pengguna Amazon*.

   1. Untuk tutorial ini, pilih keluar dari pengaturan Structured Logging dalam format JSON pada fungsi Lambda Anda.

   1. Beri nama aplikasi Anda sebagai **sam-app**.

   Untuk menggunakan aliran AWS SAMCLI interaktif:
   + Kurung (`[ ]`) menunjukkan nilai default. Biarkan jawaban Anda kosong untuk memilih nilai default.
   + Masukkan **`y`** untuk **ya**, dan **`n`** untuk **tidak**.

   Berikut ini adalah contoh aliran `sam init` interaktif:

   ```
   $ sam init
   ...
   Which template source would you like to use?
       1 - AWS Quick Start Templates
       2 - Custom Template Location
   Choice: 1
   
   Choose an AWS Quick Start application template
       1 - Hello World Example
       2 - Data processing
       3 - Hello World Example with Powertools for AWS Lambda
       4 - Multi-step workflow
       5 - Scheduled task
       6 - Standalone function
       7 - Serverless API
       8 - Infrastructure event management 
       9 - Lambda Response Streaming
      10 - GraphQLApi Hello World Example
      11 - Full Stack
      12 - Lambda EFS example
      13 - Serverless Connector Hello World Example
      14 - Multi-step workflow with Connectors
      15 - DynamoDB Example
      16 - Machine Learning
   Template: 1
   
   Use the most popular runtime and package type? (Python and zip) [y/N]: y
   
   Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: ENTER
   
   Would you like to enable monitoring using CloudWatch Application Insights?
   For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: ENTER
   					
   Would you like to set Structured Logging in JSON format on your Lambda functions?  [y/N]: ENTER
   
   Project name [sam-app]: ENTER
   ```

1.  AWS SAMCLIDownload template awal Anda dan membuat struktur direktori proyek aplikasi pada mesin lokal Anda. Berikut ini adalah contoh dari AWS SAMCLI output:

   ```
   Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)
   
       -----------------------
       Generating application:
       -----------------------
       Name: sam-app
       Runtime: python3.9
       Architectures: x86_64
       Dependency Manager: pip
       Application Template: hello-world
       Output Directory: .
       Configuration file: sam-app/samconfig.toml
   
       Next steps can be found in the README file at sam-app/README.md
   
   
   Commands you can use next
   =========================
   [*] Create pipeline: cd sam-app && sam pipeline init --bootstrap
   [*] Validate SAM template: cd sam-app && sam validate
   [*] Test Function in the Cloud: cd sam-app && sam sync --stack-name {stack-name} --watch
   ```

1. Dari baris perintah Anda, pindah ke `sam-app` direktori yang baru dibuat. Berikut ini adalah contoh dari apa yang AWS SAMCLI telah dibuat:
**catatan**  
Jika `tree` perintah tidak diinstal secara otomatis, jalankan perintah ini: `brew install tree`

   ```
   $ cd sam-app
   
   $ tree
   
   ├── README.md
   ├── __init__.py
   ├── events
   │   └── event.json
   ├── hello_world
   │   ├── __init__.py
   │   ├── app.py
   │   └── requirements.txt
   ├── samconfig.toml
   ├── template.yaml
   └── tests
       ├── __init__.py
       ├── integration
       │   ├── __init__.py
       │   └── test_api_gateway.py
       ├── requirements.txt
       └── unit
           ├── __init__.py
           └── test_handler.py
           
   6 directories, 14 files
   ```

   Beberapa file penting untuk disorot:
   + `hello_world/app.py`— Berisi kode fungsi Lambda Anda.
   + `hello_world/requirements.txt`— Berisi Python dependensi apa pun yang dibutuhkan fungsi Lambda Anda.
   + `samconfig.toml`— File konfigurasi untuk aplikasi Anda yang menyimpan parameter default yang digunakan oleh file AWS SAMCLI.
   + `template.yaml`— AWS SAM Template yang berisi kode infrastruktur aplikasi Anda.

Anda sekarang memiliki aplikasi tanpa server yang sepenuhnya ditulis di mesin lokal Anda\$1

## Langkah 2: Bangun aplikasi Anda
<a name="serverless-getting-started-hello-world-build"></a>

Pada langkah ini, Anda menggunakan AWS SAMCLI untuk membangun aplikasi Anda dan mempersiapkan penerapan. Saat Anda membangun, AWS SAMCLI membuat `.aws-sam` direktori dan mengatur dependensi fungsi, kode proyek, dan file proyek Anda di sana.

**Untuk membangun aplikasi Anda**
+ Di baris perintah Anda, dari direktori `sam-app` proyek, jalankan yang berikut ini:

  ```
  $ sam build
  ```
**catatan**  
 Jika Anda tidak memiliki Python di mesin lokal Anda, gunakan **sam build --use-container ** perintah sebagai gantinya. AWS SAMCLIAkan membuat Docker wadah yang menyertakan runtime dan dependensi fungsi Anda. Perintah ini membutuhkan Docker pada mesin lokal Anda. Untuk menginstalDocker, lihat[Menginstal Docker](install-docker.md).

  Berikut ini adalah contoh dari AWS SAMCLI output:

  ```
  $ sam build
  Starting Build use cache
  Manifest file is changed (new hash: 3298f1304...d4d421) or dependency folder (.aws-sam/deps/4d3dfad6-a267-47a6-a6cd-e07d6fae318c) is missing for (HelloWorldFunction), downloading dependencies and copying/building source
  Building codeuri: /Users/.../Demo/sam-tutorial1/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction
  Running PythonPipBuilder:CleanUp
  Running PythonPipBuilder:ResolveDependencies
  Running PythonPipBuilder:CopySource
  Running PythonPipBuilder:CopySource
  
  Build Succeeded
  
  Built Artifacts  : .aws-sam/build
  Built Template   : .aws-sam/build/template.yaml
  
  Commands you can use next
  =========================
  [*] Validate SAM template: sam validate
  [*] Invoke Function: sam local invoke
  [*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
  [*] Deploy: sam deploy --guided
  ```

  Berikut ini adalah contoh singkat dari `.aws-sam` direktori yang dibuat oleh AWS SAM CLI:

  ```
  .aws-sam
  ├── build
  │   ├── HelloWorldFunction
  │   │   ├── __init__.py
  │   │   ├── app.py
  │   │   └── requirements.txt
  │   └── template.yaml
  └── build.toml
  ```

Beberapa file penting untuk disorot:
+ `build/HelloWorldFunction`— Berisi kode fungsi Lambda Anda dan dependensi. AWS SAMCLIMembuat direktori untuk setiap fungsi dalam aplikasi Anda.
+ `build/template.yaml`— Berisi salinan AWS SAM template Anda yang direferensikan oleh CloudFormation saat penyebaran.
+ `build.toml`— File konfigurasi yang menyimpan nilai parameter default yang direferensikan oleh AWS SAMCLI saat membangun dan menerapkan aplikasi Anda.

Anda sekarang siap untuk menyebarkan aplikasi Anda ke. AWS Cloud

## Langkah 3: Menyebarkan aplikasi Anda ke AWS Cloud
<a name="serverless-getting-started-hello-world-deploy"></a>

**catatan**  
Langkah ini membutuhkan konfigurasi AWS kredensil. Untuk informasi selengkapnya, lihat [Langkah 5: Gunakan AWS CLI untuk mengkonfigurasi AWS kredensil](prerequisites.md#prerequisites-configure-credentials) di [AWS SAM prasyarat](prerequisites.md).

Pada langkah ini, Anda menggunakan AWS SAMCLI untuk menyebarkan aplikasi Anda ke file. AWS Cloud Yang AWS SAMCLI akan melakukan hal berikut:
+ Memandu Anda melalui konfigurasi pengaturan aplikasi Anda untuk penyebaran.
+ Unggah file aplikasi Anda ke Amazon Simple Storage Service (Amazon S3).
+ Ubah AWS SAM template Anda menjadi CloudFormation template. Kemudian mengunggah template Anda ke CloudFormation layanan untuk menyediakan AWS sumber daya Anda.

**Untuk menyebarkan aplikasi Anda**

1. Di baris perintah Anda, dari direktori `sam-app` proyek, jalankan yang berikut ini:

   ```
   $ sam deploy --guided
   ```

1. Ikuti alur AWS SAMCLI interaktif untuk mengonfigurasi pengaturan aplikasi Anda. Konfigurasikan berikut ini:

   1. **Nama CloudFormation tumpukan** — Tumpukan adalah kumpulan sumber AWS daya yang dapat Anda kelola sebagai satu unit. Untuk mempelajari lebih lanjut, lihat [Bekerja dengan tumpukan](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacks.html) di *Panduan AWS CloudFormation Pengguna*.

   1. **Wilayah AWS**Untuk menyebarkan CloudFormation tumpukan Anda ke. Untuk informasi selengkapnya, lihat [CloudFormation titik akhir](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-endpoints.html) di *Panduan AWS CloudFormation Pengguna*.

   1. Untuk tutorial ini, pilih keluar dari **konfirmasi perubahan sebelum menerapkan**.

   1. **Izinkan pembuatan peran IAM** — Ini memungkinkan AWS SAM membuat peran IAM yang diperlukan untuk sumber daya API Gateway dan sumber daya fungsi Lambda Anda untuk berinteraksi.

   1. Untuk tutorial ini, pilih keluar dari **menonaktifkan rollback**.

   1. Izinkan **HelloWorldFunction tanpa otorisasi yang ditentukan** - Pesan ini ditampilkan karena titik akhir API Gateway Anda dikonfigurasi agar dapat diakses publik, tanpa otorisasi. Karena ini adalah konfigurasi yang dimaksudkan untuk aplikasi Hello World Anda, izinkan AWS SAMCLI untuk melanjutkan. Untuk informasi selengkapnya tentang mengonfigurasi otorisasi, lihat. [Kontrol akses API dengan AWS SAM template Anda](serverless-controlling-access-to-apis.md)

   1. **Simpan argumen ke file konfigurasi** — Ini akan memperbarui `samconfig.toml` file aplikasi Anda dengan preferensi penerapan Anda.

   1. Pilih **nama file konfigurasi** default.

   1. Pilih **lingkungan konfigurasi** default.

   Berikut ini adalah contoh output dari aliran `sam deploy --guided` interaktif:

   ```
   $ sam deploy --guided
   
   Configuring SAM deploy
   ======================
   
       Looking for config file [samconfig.toml] :  Found
       Reading default arguments  :  Success
   
       Setting default arguments for 'sam deploy'
       =========================================
       Stack Name [sam-app]: ENTER
       AWS Region [us-west-2]: ENTER
       #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
       Confirm changes before deploy [Y/n]: n
       #SAM needs permission to be able to create roles to connect to the resources in your template
       Allow SAM CLI IAM role creation [Y/n]: ENTER
       #Preserves the state of previously provisioned resources when an operation fails
       Disable rollback [y/N]: ENTER
       HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y
       Save arguments to configuration file [Y/n]: ENTER
       SAM configuration file [samconfig.toml]: ENTER
       SAM configuration environment [default]: ENTER
   ```

1.  AWS SAMCLIMenyebarkan aplikasi Anda dengan melakukan hal berikut:
   +  AWS SAMCLIIni membuat bucket Amazon S3 dan mengunggah direktori Anda. `.aws-sam`
   + Ini AWS SAMCLI mengubah AWS SAM template Anda menjadi CloudFormation dan mengunggahnya ke layanan. CloudFormation 
   + CloudFormation menyediakan sumber daya Anda.

   Selama penerapan, AWS SAMCLI menampilkan kemajuan Anda. Berikut ini adalah contoh output:

   ```
   Looking for resources needed for deployment:
   
       Managed S3 bucket: aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
       A different default S3 bucket can be set in samconfig.toml
   
       Parameter "stack_name=sam-app" in [default.deploy.parameters] is defined as a global parameter [default.global.parameters].
       This parameter will be only saved under [default.global.parameters] in /Users/.../Demo/sam-tutorial1/sam-app/samconfig.toml.
   
       Saved arguments to config file
       Running 'sam deploy' for future deployments will use the parameters saved above.
       The above parameters can be changed by modifying samconfig.toml
       Learn more about samconfig.toml syntax at
       https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html
   
   File with same data already exists at sam-app/da3c598813f1c2151579b73ad788cac8, skipping upload
   
       Deploying with following values
       ===============================
       Stack name                   : sam-app
       Region                       : us-west-2
       Confirm changeset            : False
       Disable rollback             : False
       Deployment s3 bucket         : aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
       Capabilities                 : ["CAPABILITY_IAM"]
       Parameter overrides          : {}
       Signing Profiles             : {}
   
   Initiating deployment
   =====================
   
   File with same data already exists at sam-app/2bebf67c79f6a743cc5312f6dfc1efee.template, skipping upload
   
   
   Waiting for changeset to be created..
   
   CloudFormation stack changeset
   ---------------------------------------------------------------------------------------------------------------------------------------------
   Operation                           LogicalResourceId                   ResourceType                        Replacement
   ---------------------------------------------------------------------------------------------------------------------------------------------
   * Modify                            HelloWorldFunction                  AWS::Lambda::Function               False
   * Modify                            ServerlessRestApi                   AWS::ApiGateway::RestApi            False
   - Delete                            AwsSamAutoDependencyLayerNestedSt   AWS::CloudFormation::Stack          N/A
                                       ack
   ---------------------------------------------------------------------------------------------------------------------------------------------
   
   
   Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1678917603/22e05525-08f9-4c52-a2c4-f7f1fd055072
   
   
   2023-03-15 12:00:16 - Waiting for stack create/update to complete
   
   CloudFormation events from stack operations (refresh every 0.5 seconds)
   ---------------------------------------------------------------------------------------------------------------------------------------------
   ResourceStatus                      ResourceType                        LogicalResourceId                   ResourceStatusReason
   ---------------------------------------------------------------------------------------------------------------------------------------------
   UPDATE_IN_PROGRESS                  AWS::Lambda::Function               HelloWorldFunction                  -
   UPDATE_COMPLETE                     AWS::Lambda::Function               HelloWorldFunction                  -
   UPDATE_COMPLETE_CLEANUP_IN_PROGRE   AWS::CloudFormation::Stack          sam-app                             -
   SS
   DELETE_IN_PROGRESS                  AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                           ack
   DELETE_COMPLETE                     AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                           ack
   UPDATE_COMPLETE                     AWS::CloudFormation::Stack          sam-app                             -
   ---------------------------------------------------------------------------------------------------------------------------------------------
   
   CloudFormation outputs from deployed stack
   ----------------------------------------------------------------------------------------------------------------------------------------------
   Outputs
   ----------------------------------------------------------------------------------------------------------------------------------------------
   Key                 HelloWorldFunctionIamRole
   Description         Implicit IAM Role created for Hello World function
   Value               arn:aws:iam::012345678910:role/sam-app-HelloWorldFunctionRole-15GLOUR9LMT1W
   
   Key                 HelloWorldApi
   Description         API Gateway endpoint URL for Prod stage for Hello World function
   Value               https://<restapiid>.execute-api.us-west-2.amazonaws.com/Prod/hello/
   
   Key                 HelloWorldFunction
   Description         Hello World Lambda Function ARN
   Value               arn:aws:lambda:us-west-2:012345678910:function:sam-app-HelloWorldFunction-yQDNe17r9maD
   ----------------------------------------------------------------------------------------------------------------------------------------------
   
   
   Successfully created/updated stack - sam-app in us-west-2
   ```

Aplikasi Anda sekarang digunakan dan berjalan di\$1 AWS Cloud

## Langkah 4: Jalankan aplikasi Anda
<a name="serverless-getting-started-hello-world-run"></a>

Pada langkah ini, Anda akan mengirim permintaan GET ke titik akhir API Anda dan melihat output fungsi Lambda Anda.

**Untuk mendapatkan nilai endpoint API Anda**

1. Dari informasi yang ditampilkan oleh AWS SAMCLI pada langkah sebelumnya, cari `Outputs` bagian. Di bagian ini, cari `HelloWorldApi` sumber daya Anda untuk menemukan nilai titik akhir HTTP Anda. Berikut ini adalah contoh output:

   ```
   ----------------------------------------------------------------------------------------------------------------------------------------------
   Outputs
   ----------------------------------------------------------------------------------------------------------------------------------------------
   ...
   Key                 HelloWorldApi
   Description         API Gateway endpoint URL for Prod stage for Hello World function
   Value               https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod/hello/
   ...
   ----------------------------------------------------------------------------------------------------------------------------------------------
   ```

1. Atau, Anda dapat menggunakan **sam list endpoints --output json** perintah untuk mendapatkan informasi ini. Berikut ini adalah contoh output:

   ```
   $ sam list endpoints --output json
   2023-03-15 12:39:19 Loading policies from IAM...
   2023-03-15 12:39:25 Finished loading policies from IAM.
   [
     {
       "LogicalResourceId": "HelloWorldFunction",
       "PhysicalResourceId": "sam-app-HelloWorldFunction-yQDNe17r9maD",
       "CloudEndpoint": "-",
       "Methods": "-"
     },
     {
       "LogicalResourceId": "ServerlessRestApi",
       "PhysicalResourceId": "ets1gv8lxi",
       "CloudEndpoint": [
         "https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod",
         "https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Stage"
       ],
       "Methods": [
         "/hello['get']"
       ]
     }
   ]
   ```

**Untuk memanggil fungsi Anda**
+ Menggunakan browser atau baris perintah, kirim permintaan GET ke titik akhir API Anda. Berikut ini adalah contoh menggunakan perintah curl:

  ```
  $ curl https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod/hello/
  {"message": "hello world"}
  ```

## Langkah 5: Berinteraksi dengan fungsi Anda di AWS Cloud
<a name="serverless-getting-started-hello-world-remote-invoke"></a>

Pada langkah ini, Anda menggunakan AWS SAMCLI untuk menjalankan fungsi Lambda Anda di. AWS Cloud

**Untuk menjalankan fungsi Lambda Anda di cloud**

1. Catat fungsi Anda `LogicalResourceId` dari langkah sebelumnya. Seharusnya begitu`HelloWorldFunction`.

1. Di baris perintah Anda, dari direktori `sam-app` proyek, jalankan yang berikut ini:

   ```
   $ sam remote invoke HelloWorldFunction --stack-name sam-app
   ```

1.  AWS SAMCLIMemanggil fungsi Anda di cloud dan mengembalikan respons. Berikut ini adalah contoh output:

   ```
   $ sam remote invoke HelloWorldFunction --stack-name sam-app
   
   Invoking Lambda Function HelloWorldFunction                                       
   START RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9 Version: $LATEST
   END RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9
   REPORT RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9  Duration: 6.62 ms       Billed Duration: 7 ms     Memory Size: 128 MB     Max Memory Used: 67 MB  Init Duration: 164.06 ms
   {"statusCode":200,"body":"{\"message\":\"hello world\"}"}%
   ```

## Langkah 6: Ubah dan sinkronkan aplikasi Anda ke AWS Cloud
<a name="serverless-getting-started-hello-world-sync"></a>

Pada langkah ini, Anda menggunakan AWS SAMCLI **sam sync --watch** perintah untuk menyinkronkan perubahan lokal ke file AWS Cloud.

**Untuk menggunakan sinkronisasi sam**

1. Di baris perintah Anda, dari direktori `sam-app` proyek, jalankan yang berikut ini:

   ```
   $ sam sync --watch
   ```

1. Ini AWS SAMCLI meminta Anda untuk mengonfirmasi bahwa Anda menyinkronkan tumpukan pengembangan. Karena **sam sync --watch** perintah secara otomatis menyebarkan perubahan lokal ke AWS Cloud dalam waktu nyata, kami merekomendasikannya hanya untuk lingkungan pengembangan.

    AWS SAMCLIMelakukan penerapan awal sebelum mulai memantau perubahan lokal. Berikut ini adalah contoh output:

   ```
   $ sam sync --watch
   The SAM CLI will use the AWS Lambda, Amazon API Gateway, and AWS StepFunctions APIs to upload your code without
   performing a CloudFormation deployment. This will cause drift in your CloudFormation stack.
   **The sync command should only be used against a development stack**.
   
   Confirm that you are synchronizing a development stack.
   
   Enter Y to proceed with the command, or enter N to cancel:
    [Y/n]: y
   Queued infra sync. Waiting for in progress code syncs to complete...
   Starting infra sync.
   Manifest is not changed for (HelloWorldFunction), running incremental build
   Building codeuri: /Users/.../Demo/sam-tutorial1/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction
   Running PythonPipBuilder:CopySource
   
   Build Succeeded
   
   Successfully packaged artifacts and wrote output template to file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpq3x9vh63.
   Execute the following command to deploy the packaged template
   sam deploy --template-file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpq3x9vh63 --stack-name <YOUR STACK NAME>
   
   
       Deploying with following values
       ===============================
       Stack name                   : sam-app
       Region                       : us-west-2
       Disable rollback             : False
       Deployment s3 bucket         : aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
       Capabilities                 : ["CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND"]
       Parameter overrides          : {}
       Signing Profiles             : null
   
   Initiating deployment
   =====================
   
   
   2023-03-15 13:10:05 - Waiting for stack create/update to complete
   
   CloudFormation events from stack operations (refresh every 0.5 seconds)
   ---------------------------------------------------------------------------------------------------------------------------------------------
   ResourceStatus                      ResourceType                        LogicalResourceId                   ResourceStatusReason
   ---------------------------------------------------------------------------------------------------------------------------------------------
   UPDATE_IN_PROGRESS                  AWS::CloudFormation::Stack          sam-app                             Transformation succeeded
   CREATE_IN_PROGRESS                  AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                           ack
   CREATE_IN_PROGRESS                  AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   Resource creation Initiated
                                                                           ack
   CREATE_COMPLETE                     AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                           ack
   UPDATE_IN_PROGRESS                  AWS::Lambda::Function               HelloWorldFunction                  -
   UPDATE_COMPLETE                     AWS::Lambda::Function               HelloWorldFunction                  -
   UPDATE_COMPLETE_CLEANUP_IN_PROGRE   AWS::CloudFormation::Stack          sam-app                             -
   SS
   UPDATE_COMPLETE                     AWS::CloudFormation::Stack          sam-app                             -
   ---------------------------------------------------------------------------------------------------------------------------------------------
   
   CloudFormation outputs from deployed stack
   ----------------------------------------------------------------------------------------------------------------------------------------------
   Outputs
   ----------------------------------------------------------------------------------------------------------------------------------------------
   Key                 HelloWorldFunctionIamRole
   Description         Implicit IAM Role created for Hello World function
   Value               arn:aws:iam::012345678910:role/sam-app-HelloWorldFunctionRole-15GLOUR9LMT1W
   
   Key                 HelloWorldApi
   Description         API Gateway endpoint URL for Prod stage for Hello World function
   Value               https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod/hello/
   
   Key                 HelloWorldFunction
   Description         Hello World Lambda Function ARN
   Value               arn:aws:lambda:us-west-2:012345678910:function:sam-app-HelloWorldFunction-yQDNe17r9maD
   ----------------------------------------------------------------------------------------------------------------------------------------------
   
   
   Stack update succeeded. Sync infra completed.
   
   Infra sync completed.
   CodeTrigger not created as CodeUri or DefinitionUri is missing for ServerlessRestApi.
   ```

Selanjutnya, Anda akan memodifikasi kode fungsi Lambda Anda. Secara otomatis AWS SAMCLI akan mendeteksi perubahan ini dan menyinkronkan aplikasi Anda ke file AWS Cloud.

**Untuk memodifikasi dan menyinkronkan aplikasi Anda**

1. Dalam IDE pilihan Anda, buka `sam-app/hello_world/app.py` file.

1. Ubah `message` dan simpan file Anda. Berikut ini adalah contohnya:

   ```
   import json
   ...
   def lambda_handler(event, context):
       ...
       return {
           "statusCode": 200,
           "body": json.dumps({
               "message": "hello everyone!",
               ...
           }),
       }
   ```

1.  AWS SAMCLIMendeteksi perubahan Anda dan menyinkronkan aplikasi Anda ke file. AWS Cloud Berikut ini adalah contoh output:

   ```
   Syncing Lambda Function HelloWorldFunction...
   Manifest is not changed for (HelloWorldFunction), running incremental build
   Building codeuri: /Users/.../Demo/sam-tutorial1/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction
   Running PythonPipBuilder:CopySource
   Finished syncing Lambda Function HelloWorldFunction.
   ```

1. Untuk memverifikasi perubahan Anda, kirim permintaan GET ke titik akhir API Anda lagi.

   ```
   $ curl https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod/hello/
   {"message": "hello everyone!"}
   ```

## Langkah 7: (Opsional) Uji aplikasi Anda secara lokal
<a name="serverless-getting-started-hello-world-test"></a>

**catatan**  
Langkah ini bersifat opsional.

**penting**  
Langkah ini membutuhkan Docker pada mesin lokal Anda. Anda harus telah Docker menginstal dan mengkonfigurasi untuk menggunakan AWS SAMCLI untuk pengujian lokal. Untuk informasi selengkapnya, lihat [Menginstal Docker](install-docker.md).

Pada langkah ini, Anda menggunakan AWS SAMCLI **sam local** perintah untuk menguji aplikasi Anda secara lokal. Untuk mencapai hal ini, AWS SAMCLI menciptakan lingkungan lokal menggunakanDocker. Lingkungan lokal ini mengemulasi lingkungan eksekusi berbasis cloud dari fungsi Lambda Anda.

Anda akan melakukan hal berikut:

1. Buat lingkungan lokal untuk fungsi Lambda Anda dan panggil.

1. Host titik akhir HTTP API Anda secara lokal dan gunakan untuk menjalankan fungsi Lambda Anda.

**Untuk menjalankan fungsi Lambda Anda secara lokal**

1. Di baris perintah Anda, dari direktori `sam-app` proyek, jalankan yang berikut ini:

   ```
   $ sam local invoke
   ```

1.  AWS SAMCLIMembuat Docker wadah lokal dan memanggil fungsi Anda. Berikut ini adalah contoh output:

   ```
   $ sam local invoke
   Invoking app.lambda_handler (python3.9)
   Local image was not found.
   Removing rapid images for repo public.ecr.aws/sam/emulation-python3.9
   Building image.....................
   Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64.
   
   Mounting /Users/.../Demo/sam-tutorial1/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
   START RequestId: b046db01-2a00-415d-af97-35f3a02e9eb6 Version: $LATEST
   END RequestId: b046db01-2a00-415d-af97-35f3a02e9eb6
   REPORT RequestId: b046db01-2a00-415d-af97-35f3a02e9eb6    Init Duration: 1.01 ms    Duration: 633.45 ms    Billed Duration: 634 ms    Memory Size: 128 MB    Max Memory Used: 128 MB
   {"statusCode": 200, "body": "{\"message\": \"hello world\"}"}
   ```

**Untuk meng-host API Anda secara lokal**

1. Di baris perintah Anda, dari direktori `sam-app` proyek, jalankan yang berikut ini:

   ```
   $ sam local start-api
   ```

1.  AWS SAMCLIIni membuat Docker wadah lokal untuk fungsi Lambda Anda dan membuat server HTTP lokal untuk mensimulasikan titik akhir API Anda. Berikut ini adalah contoh output:

   ```
   $ sam local start-api
   Initializing the lambda functions containers.
   Local image is up-to-date
   Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64.
   
   Mounting /Users/.../Demo/sam-tutorial1/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
   Containers Initialization is done.
   Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
   You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. If you used sam build before running local commands, you will need to re-run sam build for the changes to be picked up. You only need to restart AWS SAM CLI if you update your AWS SAM template
   2023-03-15 14:25:21 WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
    * Running on http://127.0.0.1:3000
   2023-03-15 14:25:21 Press CTRL+C to quit
   ```

1. Menggunakan browser Anda atau baris perintah, kirim permintaan GET ke endpoint API lokal Anda. Berikut ini adalah contoh menggunakan perintah curl:

   ```
   $ curl http://127.0.0.1:3000/hello
   {"message": "hello world"}
   ```

## Langkah 8: Hapus aplikasi Anda dari AWS Cloud
<a name="serverless-getting-started-hello-world-delete"></a>

Pada langkah ini, Anda menggunakan AWS SAMCLI **sam delete** perintah untuk menghapus aplikasi Anda dari file AWS Cloud.

**Untuk menghapus aplikasi Anda dari AWS Cloud**

1. Di baris perintah Anda, dari direktori `sam-app` proyek, jalankan yang berikut ini:

   ```
   $ sam delete
   ```

1. Mereka AWS SAMCLI akan meminta Anda untuk mengkonfirmasi. Kemudian, itu akan menghapus bucket dan CloudFormation stack Amazon S3 aplikasi Anda. Berikut ini adalah contoh output:

   ```
   $ sam delete
       Are you sure you want to delete the stack sam-app in the region us-west-2 ? [y/N]: y
       Are you sure you want to delete the folder sam-app in S3 which contains the artifacts? [y/N]: y
       - Deleting S3 object with key c6ce8fa8b5a97dd022ecd006536eb5a4
       - Deleting S3 object with key 5d513a459d062d644f3b7dd0c8b56a2a.template
       - Deleting S3 object with key sam-app/2bebf67c79f6a743cc5312f6dfc1efee.template
       - Deleting S3 object with key sam-app/6b208d0e42ad15d1cee77d967834784b.template
       - Deleting S3 object with key sam-app/da3c598813f1c2151579b73ad788cac8
       - Deleting S3 object with key sam-app/f798cdd93cee188a71d120f14a035b11
       - Deleting Cloudformation stack sam-app
   
   Deleted successfully
   ```

## Pemecahan masalah
<a name="serverless-getting-started-hello-world-troubleshoot"></a>

Untuk memecahkan masalah AWS SAMCLI, lihat. [AWS SAMCLIpemecahan masalah](sam-cli-troubleshooting.md)

## Pelajari selengkapnya
<a name="serverless-getting-started-hello-world-learn"></a>

Untuk terus mempelajarinya AWS SAM, lihat sumber daya berikut:
+ **[AWS SAM Lokakarya Lengkap](https://s12d.com/sam-ws-en-intro)** — Lokakarya yang dirancang untuk mengajari Anda banyak fitur utama yang AWS SAM menyediakan.
+ **[Sesi dengan SAM](https://www.youtube.com/playlist?list=PLJo-rJlep0ED198FJnTzhIB5Aut_1vDAd)** - Seri video yang dibuat oleh tim Advokat Pengembang AWS Tanpa Server kami tentang penggunaan. AWS SAM
+ **[Serverless Land](https://serverlessland.com/)** — Situs yang menyatukan informasi terbaru, blog, video, kode, dan sumber belajar untuk AWS tanpa server.