DEV Community

Sherif sani
Sherif sani

Posted on

Automating NBA Game Results Delivery with AWS Lambda, EventBridge, and SNS

Introduction

Are you a basketball fan who doesn’t want to miss out on NBA game results? In this blog post, I’ll walk you through how I automated the process of fetching NBA game results using SportsAPI, AWS Lambda, EventBridge, and SNS to deliver the results via email or SMS.

By the end, you’ll learn how to set up a serverless solution with AWS services and schedule it to run daily.


Overview of the Solution

Solution Architecture

Here’s how the system works:

  • Data Source: Fetching NBA game results using SportsAPI.
  • AWS Lambda: Running the Python script to fetch data and send notifications.
  • Amazon EventBridge: Scheduling the script to run daily.
  • Amazon SNS: Delivering the results via email/SMS.

Requirements

  1. An AWS account with access to Lambda, SNS, and EventBridge.
  2. A SportsAPI API key (create one here).

Step-by-step Implementation

Login to your AWS Management Console, and let's begin.


Creating the SNS Topic

  1. Navigate to SNS, then Topics

    SNS Dashboard

  2. Create a Topic

    • Topic type: Standard
    • Name: Any name of your choice
    • Leave other fields blank or default, and click Create Create Topic
  3. Create a Subscription

    • Navigate to the newly created topic and click Create subscription Create Subscription
  • Fill in these details:

     Topic ARN: The ARN of the created topic
     Protocol: Email (or SMS)
     Endpoint: Your email address
    

    Subscription Details

  • A confirmation email will be sent. Open it and hit Confirm.


Creating a Policy and Role for the Lambda Function

  1. Navigate to the IAM Dashboard

    IAM Dashboard

  2. Create a Policy

    • Click PoliciesCreate policy Create Policy
  • Choose Lambda as the service and add the following JSON under Policy Editor. Replace arn:aws:sns:REGION:ACCOUNT_ID:topic-name with your topic ARN:

     {
         "Version": "2012-10-17",
         "Statement": [
             {
                 "Effect": "Allow",
                 "Action": "sns:Publish",
                 "Resource": "arn:aws:sns:REGION:ACCOUNT_ID:topic-name"
             }
         ]
     }
    

Policy Editor

  • Review, name it (e.g., sns_publish), and create it. Policy Created
  1. Create a Role
    • Go to RolesCreate role Create Role
  • Select AWS ServiceLambda as the trusted entity.

    Trusted Entity

  • Attach the previously created policy (sns_publish).

    Attach Policy

  • Name the role (e.g., nba_function_role) and create it.

    Role Created


Creating the Lambda Function

  1. Navigate to LambdaCreate function

    Lambda Dashboard

  2. Function Details

    • Name: nba_function
    • Runtime: Python
    • Execution Role: Select the previously created role (nba_function_role). Create Function
  3. Add the Code

    Replace the default code with the provided Python script.

import json
import urllib.request
import boto3
import datetime
import os
from botocore.config import Config

def lambda_handler(event, context):
    # Configure boto3 with shorter timeout
    config = Config(
        connect_timeout=2,
        read_timeout=2
    )
    sns = boto3.client('sns', config=config)

    # Get environment variables
    API_KEY = os.getenv('API_KEY')
    SNS_TOPIC_ARN = os.getenv('SNS_TOPIC_ARN')

    today_date = datetime.datetime.now().strftime("%Y-%m-%d")
    print(f"fetching games for {today_date}")

    api_url = f"https://v1.basketball.api-sports.io/games?league=12&season=2024-2025&date={today_date}"
    headers = {
        'x-rapidapi-host': "v1.basketball.api-sports.io",
        'x-rapidapi-key': API_KEY
    }

    # Set timeout for the HTTP request
    req = urllib.request.Request(api_url, headers=headers, method="GET")

    try:
        # Send the HTTP request with timeout
        with urllib.request.urlopen(req, timeout=2) as response:
            response_data = response.read().decode('utf-8')
            data = json.loads(response_data)

            # Process games more efficiently using list comprehension
            messages = [
                f"{game['teams']['home']['name']} ({game['scores']['home']['total']}) vs "
                f"{game['teams']['away']['name']} ({game['scores']['away']['total']})"
                for game in data.get('response', [])
            ]

            if messages:
                final_message = "\n".join(messages)
                sns.publish(
                    TopicArn=SNS_TOPIC_ARN,
                    Message=final_message,
                    Subject=f"Games for {today_date}"
                )
                return {
                    'statusCode': 200,
                    'body': json.dumps({'message': 'Successfully processed games'})
                }
            else:
                return {
                    'statusCode': 200,
                    'body': json.dumps({'message': 'No games found for today'})
                }

    except urllib.error.URLError as e:
        error_message = f"Error fetching games: {e.reason}"
        print(error_message)
        return {
            'statusCode': 500,
            'body': json.dumps({'error': error_message})
        }
    except urllib.error.HTTPError as e:
        error_message = f"HTTP error: {e.code} - {e.reason}"
        print(error_message)
        return {
            'statusCode': e.code,
            'body': json.dumps({'error': error_message})
        }
    except Exception as e:
        error_message = f"Unexpected error: {str(e)}"
        print(error_message)
        return {
            'statusCode': 500,
            'body': json.dumps({'error': error_message})
        }
Enter fullscreen mode Exit fullscreen mode
  1. Add Environment Variables

    • API_KEY: Your SportsAPI key
    • SNS_TOPIC_ARN: The ARN of the created topic
  2. Deploy the Function

    • Click Deploy or use the shortcut Ctrl+Shift+U.

Creating the EventBridge Schedule

  1. Navigate to EventBridge

    EventBridge Dashboard

  2. Create a Rule

    • Name: Any name of your choice
    • Rule type: Schedule
    • Cron expression: 0 * * * ? * (runs hourly) Create Rule
  3. Select the Target

    • Target type: Lambda Function
    • Lambda function: nba_function Select Target
  4. Create the Schedule


With these steps, your automated solution will fetch NBA game results daily and send them to you via email or SMS!


Conclusion

This project demonstrates how AWS services like Lambda, EventBridge, and SNS can work seamlessly together to create a fully automated, serverless solution. By leveraging SportsAPI, we automated the process of fetching NBA game results and delivering them directly to your inbox or phone, saving you time and ensuring you never miss a moment.

Whether you’re a sports enthusiast or just exploring serverless architectures, this project showcases the versatility of AWS for building practical, real-world applications. I encourage you to try it out, customize it further, and even extend it to other use cases like weather updates or stock market alerts.

Feel free to share your thoughts or ask questions in the comments! Happy coding! 🏀✨

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more