Running a Serverless Lumen REST API on AWS Lambda

Part I: PHP Runtime

Layers:
- !Sub arn:aws:lambda:${AWS::Region}:887080169480:layer:php73:2
  1. use a pre-built PHP runtime that I have created;
  2. build the PHP runtime using Docker.

1. Use a pre-built runtime

2. Build the PHP runtime

git config --global core.autocrlf false
git clone https://github.com/code-runner-2017/php-lambda-layer.git
cd php-lambda-layer
make
C:\Program Files\Git\mingw64\bin

Creating a new Layer

arn:aws:lambda:eu-west-1:5320652344506:layer:php7_1-stackery_mbstring:1

Part II: Creating the Sample Lumen REST API

git clone https://github.com/code-runner-2017/lambda-lumen-test.git
cd lambda-lumen-test/src/php/lumen
composer update
extension=curl.so
extension=json.so
extension=mbstring.so
extension=pdo.so
extension=pdo_pgsql.so
  • the composer.json file already contains the AWS SDK, as it is very likely that your Lambda is going to interact with the rest of the AWS ecosystem (DynamoDB, S3, …). If you don’t need it, you can remove that entry.
  • I have configured Monolog to not write on the file system, as the Lambda function would fail. You must create your own .env file copying the .env.example file. It is important that you have this configuration in it: LOG_CHANNEL=errorlog
  • /hello that returns “hello world!”;
  • /test that returns a JSON object. You can optionally pass a name parameter on the URL (eg. ?name=Pietro). It will be returned in the JSON response, just to test that you can read URL params.
# Run this from the lambda-lumen-test/src/php/lumen folder
php -S localhost:8000 -t public

Creating the AWS Lambda

  • the latest version of AWS CLI (Windows users can download it here)
  • AWS SAM (available here)
$ sam package --template-file template.yaml --output-template-file serverless-output.yaml --s3-bucket yourbucketname
$ sam deploy --template-file serverless-output.yaml --stack-name my-first-serverless-lumen-api --capabilities CAPABILITY_IAM

Testing the AWS Lambda

AWS Lambda Designer
https://ua12345ai.execute-api.eu-west-1.amazonaws.com/Prod/{proxy+}
https://yourhostname/Prod/hello

Next Steps

  • DynamoDB (NoSQL)
  • ElastiCache (Redis/Memcache)
  • ElasticSearch
  • Aurora

Querying an RDS Postgresql instance

CREATE TABLE users (
user_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
login_name VARCHAR(64) NOT NULL,
email VARCHAR(64) NOT NULL
)

insert into users (login_name, email) values (‘pietro.iglio’, ‘igliop@gmail.com’);
$router->get('/testdb', function (Request $request) use ($router) {
$users = app('db')->select("SELECT * FROM users");
return response()->json($users);
});
https://yourhostname/Prod/testdb
[
{
"user_id": 1,
"login_name": "pietro.iglio",
"email": "igliop@gmail.com"
}
]

Final Considerations

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store