Buongiorno a tutti e bentornati in nuovo articolo di tooldech, oggi parleremo di Serverless.
Cos’è il Serverless su AWS
Il modello Serverless su AWS permette di eseguire codice senza dover gestire server fisici o virtuali. Utilizzando servizi come AWS Lambda, API Gateway e DynamoDB, puoi costruire applicazioni scalabili e a basso costo, dove AWS si occupa dell’infrastruttura.
Perché scegliere il Serverless
- Nessuna gestione server: non devi preoccuparti di provisioning, patching o scalabilità.
- Scalabilità automatica: l’applicazione si adatta al carico in tempo reale.
- Pagamento a consumo: paghi solo per l’uso effettivo di risorse.
Obiettivo del progetto
Creeremo un’applicazione serverless in grado di:
- Esporre un’API REST tramite API Gateway.
- Innescare una funzione AWS Lambda alla ricezione di richieste HTTP.
- Salvare i dati ricevuti in una tabella DynamoDB.
Requisiti preliminari
- Account AWS attivo
- AWS CLI installata e configurata (
aws configure
) - Node.js installato (per il codice Lambda)
- IAM user con permessi per Lambda, API Gateway e DynamoDB
Passo 1: Creazione della tabella DynamoDB
Apri il terminale e crea una tabella DynamoDB chiamata Contacts
:
aws dynamodb create-table \
--table-name Contacts \
--attribute-definitions AttributeName=id,AttributeType=S \
--key-schema AttributeName=id,KeyType=HASH \
--billing-mode PAY_PER_REQUEST
Spiegazione
AttributeName=id,AttributeType=S
: definisce una chiave primariaid
di tipo stringa.PAY_PER_REQUEST
: modello di pagamento che scala automaticamente.

Passo 2: Creazione della funzione Lambda
1. Crea una cartella per il progetto
mkdir lambda-contact-api
cd lambda-contact-api

2. Inizializza un progetto Node.js e installa AWS SDK
npm init -y

npm install aws-sdk

3. Crea il file index.js
con questo contenuto:
const AWS = require('aws-sdk');
const dynamo = new AWS.DynamoDB.DocumentClient();
const { v4: uuidv4 } = require('uuid');
exports.handler = async (event) => {
const body = JSON.parse(event.body);
const id = uuidv4();
const params = {
TableName: 'Contacts',
Item: {
id: id,
name: body.name,
email: body.email
}
};
await dynamo.put(params).promise();
return {
statusCode: 200,
body: JSON.stringify({ message: 'Contatto salvato con successo', id })
};
};
N.B. va inserito nella cartella “lambda-contact-api”.
4. Installa uuid
e crea file zip
npm install uuid

zip -r function.zip .
Questo comando viene usato e funziona su Unix/Linux/macOS, ma su Windows PowerShell non è supportato nativamente nello stesso modo, io ve lo lascio lo stesso se usate altri sistemi operativi.
Ci sono altri modi ma il modo che ho trovato è questo se USATE WINDOWS
Compress-Archive -Path * -DestinationPath function.zip


5. Crea la funzione Lambda
aws lambda create-function \
--function-name SaveContact \
--runtime nodejs18.x \
--role arn:aws:iam::<ACCOUNT_ID>:role/<ROLE_NAME> \
--handler index.handler \
--zip-file fileb://function.zip

Sostituisci
<ACCOUNT_ID>
e<ROLE_NAME>
con i valori reali del tuo account e IAM role con permessi per DynamoDB.
N.B. se non hai un ruolo pronto lo devi creare ecco un link su come creare un ruolo IAM.
Passo 3: Configurazione di API Gateway
1. Crea una nuova REST API
aws apigateway create-rest-api \
--name "ContactAPI"
Segna l’ID dell’API restituito (es. abc123
).

2. Recupera l’ID della risorsa root
aws apigateway get-resources --rest-api-id abc123

Segna il id
della root (/
) che in questo caso è “lhuytjg3pa”.
3. Crea la risorsa /contact
aws apigateway create-resource \
--rest-api-id abc123 \
--parent-id <root_id> \
--path-part contact

4. Aggiungi metodo POST
aws apigateway put-method \
--rest-api-id abc123 \
--resource-id <contact_id> \
--http-method POST \
--authorization-type NONE

5. Collega Lambda come integrazione
aws apigateway put-integration \
--rest-api-id abc123 \
--resource-id <contact_id> \
--http-method POST \
--type AWS_PROXY \
--integration-http-method POST \
--uri arn:aws:apigateway:<region>:lambda:path/2015-03-31/functions/arn:aws:lambda:<region>:<account_id>:function:SaveContact/invocations
Ricorda di sostituire
<region>
e<account_id>
con i tuoi valori reali.

6. Concedi a API Gateway il permesso di invocare Lambda
aws lambda add-permission \
--function-name SaveContact \
--statement-id apigateway-access \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com \
--source-arn arn:aws:execute-api:<region>:<account_id>:<api_id>/*/POST/contact

N.B. api-id è sempre il nostro nvjqmw8ywd.
7. Deploy dell’API
aws apigateway create-deployment \
--rest-api-id abc123 \
--stage-name prod

Bene ora che abbiamo deployato dobbiamo vedere se tutto funziona correttamente
Passo 4: Test dell’applicazione
Adesso proviamo a fare un test! Ad inviare una richiesta POST usando curl
:
curl -X POST https://<api_id>.execute-api.<region>.amazonaws.com/prod/contact \
-H "Content-Type: application/json" \
-d '{"name":"Mario Rossi", "email":"mario@example.com"}'
Se il test dovesse andare male con questo errore

Mancano delle configurazioni, non allarmatevi e le ragioni dell’errore possono essere 3:
A. Il pacchetto uuid
non è incluso nel .zip
Hai usato require('uuid')
, ma forse non è stato incluso nel pacchetto. Controlla che nel function.zip
ci sia node_modules/uuid
.
B. La tabella DynamoDB non esiste o il nome è sbagliato
Controlla che esista esattamente una tabella chiamata Contacts
.
C. Il ruolo IAM non ha permesso dynamodb:PutItem
Assicurati di aver attaccato la policy AmazonDynamoDBFullAccess
al ruolo della Lambda.
Nel mio caso è perché non ho messo la policy di DynamoDB al ruolo della lambda.
Con questo comando
aws iam attach-role-policy --role-name LambdaDynamoDBRole --policy-arn arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess
Puoi attaccare la policy al ruolo della lambda, attendi qualche secondo e poi rilancia il comando di deploy.

Risposta attesa:
{
"message": "Contatto salvato con successo",
"id": "d91f..."
}

Verifica nella console DynamoDB che i dati siano stati salvati correttamente.

Come possiamo vedere dalla scheramta di DynamoDb, la nostra chiamata POST è andata a buon fine.
Conclusione
Hai appena realizzato una web API completamente serverless con Lambda, API Gateway e DynamoDB, senza dover gestire alcun server!
Siamo arrivati alla fine di questo tutorial, spero che vi sia servito per capire meglio o aiutarvi a risolvere dei altri porblemi su questo tema, vi ringrazio di essere arrivati fin qui e ci vediamo al prossimo tutorial a presto!!
Inizia ora il tuo viaggio Serverless!
Hai trovato utile questa guida? Condividila o visita tooldech.com per altri tutorial pratici su DevOps, Cloud e Automazioni!
Seguimi sui canali social!
I have been browsing online more than three hours today yet I never found any interesting article like yours It is pretty worth enough for me In my view if all website owners and bloggers made good content as you did the internet will be a lot more useful than ever before
Thank you Tatyana, your message is really powerfull for me
Your blog is a true gem in the world of online content. I’m continually impressed by the depth of your research and the clarity of your writing. Thank you for sharing your wisdom with us.
certainly like your website but you need to take a look at the spelling on quite a few of your posts Many of them are rife with spelling problems and I find it very troublesome to inform the reality nevertheless I will definitely come back again
Your blog is a testament to your expertise and dedication to your craft. I’m constantly impressed by the depth of your knowledge and the clarity of your explanations. Keep up the amazing work!
Your writing has a way of making even the most complex topics accessible and engaging. I’m constantly impressed by your ability to distill complicated concepts into easy-to-understand language.
Excellent blog here Also your website loads up very fast What web host are you using Can I get your affiliate link to your host I wish my web site loaded up as quickly as yours lol
Usually I do not read article on blogs however I would like to say that this writeup very compelled me to take a look at and do it Your writing style has been amazed me Thank you very nice article
I am not sure where youre getting your info but good topic I needs to spend some time learning much more or understanding more Thanks for magnificent info I was looking for this information for my mission
Ive read several just right stuff here Certainly price bookmarking for revisiting I wonder how a lot effort you place to create this kind of great informative website
Thank you I have just been searching for information approximately this topic for a while and yours is the best I have found out so far However what in regards to the bottom line Are you certain concerning the supply
Hi i think that i saw you visited my web site thus i came to Return the favore Im attempting to find things to enhance my siteI suppose its ok to use a few of your ideas
I just wanted to drop by and say how much I appreciate your blog. Your writing style is both engaging and informative, making it a pleasure to read. Looking forward to your future posts!
you are truly a just right webmaster The site loading speed is incredible It kind of feels that youre doing any distinctive trick In addition The contents are masterwork you have done a great activity in this matter