avatarMohamed Gaddour

Summary

The website content provides a step-by-step guide on deploying a Laravel API on AWS using AWS API Gateway and AWS Lambda through AWS CloudFormation.

Abstract

The article outlines the process of hosting a Laravel API on Amazon Web Services (AWS) by leveraging the scalability and cost-effectiveness of AWS API Gateway and AWS Lambda. It emphasizes the low-cost nature of these services, which are billed based on the number of calls and execution time. The guide begins with setting up a new Laravel application and proceeds to install necessary packages like serverless and Bref to facilitate the deployment. It details the configuration of environment variables, the creation of a serverless.yml file, and the adjustment of routing within the Laravel application. The article also instructs on adding AWS credentials securely and modifying the serverless.yml template to specify the handler, environment variables, and other essential settings. The deployment is finalized by executing a Serverless command, which uploads the API to AWS, making it accessible via an endpoint provided by API Gateway.

Opinions

  • The author suggests that AWS API Gateway and AWS Lambda are the cheapest services offered by AWS due to their pay-per-use billing model.
  • The scalability of AWS API Gateway and AWS Lambda is highlighted as a significant advantage, as they can handle a large number of requests without additional developer intervention.
  • The use of AWS CloudFormation is recommended for automating deployment tasks, which involves multiple AWS components such as API Gateway, Lambda, S3, and IAM roles.
  • The author expresses a preference for using the serverless framework and Bref to streamline the deployment process for Laravel applications on AWS.
  • The article implies that the stderr log channel and array driver for sessions and cache are suitable choices for a serverless environment, as they integrate with AWS CloudWatch and avoid stateful operations, respectively.

Deploying Laravel API on AWS using AWS API Gateway and AWS Lambda

In this story I will show you haw you can host your laravel API in AWS using API Gateway and Lambda function.

As you know API Gateway and Lambda services are billed by number of calls and execution time and therefore they are considered to be the cheapest services of Aws. Also the two services are scalables, that mean that they can handle huge number of requests in a transparent way for the developer. You concentrate only in your API development.

Of course, we can not use AWS console to deploy our Laravel API since we must use many aws component to achieve this task (API Gateway, Lambda,S3, IAM roles etc …). The best AWS tool that allow us to automate deployment tasks is AWS CloudFormation by the way of stacks.

Let’s first create a new Laravel Application like below:

composer create-project laravel/laravel my-api

Then install Laravel serveless package using npm and Bref using composer. We will use theses tools to upload our API to CloudFront.

npm install -g serverless
composer require bref/bref
./vendor/bin/bref init
0
rm index.php

The 0 above is to automatically select the option Web application. Bref will then create serverless.yml and index.php. Since we’re using Laravel, we can remove the index.php and just keep the serverless.yml.

Before we move on to Serverless, let’s add a sample routing for our API by editing the routes/api.php file.

Route::get('/hello', fn () => response(['data' => 'Hello from Laravel!']));

Now we should add AWS credentials to .env file. You must first create new aws IMA user with AdministratorAccess.

AWS_ACCESS_KEY_ID=xxxxxxxxx
AWS_SECRET_ACCESS=xxxxxxxxxxxxxxxxxxxxxx

Open now serverless.yml template to apport some modifications. We change the handler from index.php to public/index.php as that’s the entry point for a Laravel application. There are also 3 important environment variables: LOG_CHANNEL, SESSION_DRIVER, and CACHE_DRIVER. The stderr driver will automatically drive log messages into CloudWatch and the array driver will essentially disable Session and Cache.

service: app

provider:
    name: aws
    region: eu-west-3
    runtime: provided.al2
    stackName: my-api
plugins:
    - ./vendor/bref/bref

functions:
    api:
        handler: public/index.php
        environment:
            LOG_CHANNEL: stderr
            SESSION_DRIVER: array
            CACHE_DRIVER: array
        description: ''
        timeout: 28 # in seconds (API Gateway has a timeout of 29 seconds)
        layers:
            - ${bref:layer.php-82-fpm}
        events:
            -   httpApi: '*'

# Exclude files from deployment
package:
    patterns:
        - '!node_modules/**'
        - '!tests/**'

Finally to deploy our Laravel API to AWS, simply execute the command below:

sls deploy

Deploying app to stage dev (eu-west-3)

✔ Service deployed to stack my-api (155s)

endpoint: ANY - https://00000000.execute-api.eu-west-3.amazonaws.com
functions:
  api: app-dev-api (25 MB)

Need a better logging experience than CloudWatch? Try our Dev Mode in console: run "serverless --console"

You can use your endpoint to test the API. It should look like this:

https://your_api_gateway_id.execute-api.eu-west-3.amazonaws.com/api/hello

That is all, Your Laravel API is now available behind AWS API Gateway and Lambda.

AWS Lambda
Laravel
Laravel Api
AWS
Laravel Framework
Recommended from ReadMedium