# Serverless Url Shortener apiGW Lambda dynamoDb

# Architecture

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710933424872/46a870dc-c8fa-4c56-8855-5f3212ed6f45.webp align="center")

<details data-node-type="hn-details-summary"><summary>Introduction</summary><div data-type="detailsContent">We'll walk through the process of building a URL shortener service using (serverless architecture) AWS Lambda (python : boto3) and API Gateway (http). By the end of this tutorial, you'll have a fully functional URL shortener service that you can deploy and use to shorten URLs.</div></details><details data-node-type="hn-details-summary"><summary>Prerequisites</summary><div data-type="detailsContent">Before we begin, ensure that you have an AWS account set up and that you're familiar with basic AWS services like Lambda and API Gateway.</div></details><details data-node-type="hn-details-summary"><summary>Step 1: Create a Lambda Function:</summary><div data-type="detailsContent">The first step is to create a Lambda function that will generate short URLs for long URLs. Here's a Python code snippet for the Lambda function</div></details>

```python
import json
import boto3
import string
import random

dynamodb = boto3.resource('dynamodb')
table_name = 'url-shortener-table'
table = dynamodb.Table(table_name)

def lambda_handler(event, context):
    print(event)
    
    http_method = event['requestContext']['http']['method']
    
    if http_method == 'POST':
        body = json.loads(event['body'])
        long_url = body['long_url']
        short_url = generate_short_url()
        table.put_item(Item={'short_id': short_url, 'long_url': long_url})

        response = {
            'statusCode': 200,
            'body': json.dumps({'short_url': short_url})
        }
    elif http_method == 'GET':
        short_url = event['rawPath'][1:]
        response = table.get_item(Key={'short_id': short_url})
        if 'Item' in response:
            long_url = response['Item']['long_url']
            response = {
                'statusCode': 301,
                'headers': {
                    'Location': long_url
                }
            }
        else:
            response = {
                'statusCode': 404,
                'body': json.dumps({'error': 'Short URL not found'})
            }
    return response

def generate_short_url():
    characters = string.ascii_letters + string.digits
    short_url = ''.join(random.choice(characters) for _ in range(3))
    return short_url
```

NOTE : Replace `table_name` with your dynamoDb table name once we create it later in this steps . and partitionKey should be `short_id`

<details data-node-type="hn-details-summary"><summary>Step 2: Set Up DynamoDB Table:</summary><div data-type="detailsContent">Create a DynamoDB table named <code>url-shortener-table</code> with <code>short_id</code> as the partition key and <code>long_url</code> as an attribute.</div></details>

**Step 3: Create an API Gateway:**

**Lets create api first and later we can do configuration**

Open the API Gateway console.

* Click on "Create API" and select "HTTP API". Review and create api
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710934836045/a45879b4-9a17-4876-b3ed-054d71f406e8.png align="center")
    
* Once we created API Define routes for POST and GET requests.
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710934938437/3c855932-4cd5-4074-a7cf-11966bbbb718.png align="center")
    
    Select `create` and keep route empty and method `POST` then select `create`
    
    ref following image
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710935037986/451758db-5762-41ca-8c1e-f3c7a5ea0c25.png align="center")
    
    once created select `POST` like this
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710935102092/fad76dd3-e844-47c1-b35b-2598224c9019.png align="center")
    
    click on attach integration and go ahead with option
    
    `create and attach integration`
    
* Next select integration type as lambda function and then select lambda function created earlier for this task
    
* Make sure this option is enabled and go ahead with create option
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710935263688/f32126bd-d6e7-45e0-aca8-3795ff3e04d1.png align="center")
    
    Cool we just created our first route , lets go and create second route which is `GET`
    
    for redirecting shorturl we got in previous response
    
* Lets create second route , now go back to Routes and select `create`
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710935836468/af116820-b4ee-4135-a4cf-91ecdaabcccb.png align="center")
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710935975277/57fc5e1b-fe1f-462d-acd5-61f59f09ebed.png align="center")
    
    Make sure its `/{short_id}`
    
* Now select GET Method attach integration and click on attach just right side option
    
* ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710936062697/3f03ca09-bda1-4a67-8823-98b864506acb.png align="center")
    
    From this option you can get your APIGW url to make request
    
* ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1710936161899/878a0ad8-ab50-4086-bfbe-80a3fe0c6590.png align="center")
    
    These are the curls to test Replace url with actual url
    

Create Short Url : POST

```bash
curl --location 'https://4tr7c6bru76e.execute-api.us-east-1.amazonaws.com' \
--header 'Content-Type: application/json' \
--data '{"long_url": "https://cloudcdk.com"}'
```

Access Short Url : GET

```bash
curl --location 'https://4tr7c6bru76e.execute-api.us-east-1.amazonaws.com/{Replace_with_id_u_get_in_response_for_above_post_request}'
```

Follow me on Twitter for more : [Twitter](https://twitter.com/akashpawar72218)
