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
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
- An AWS account with access to Lambda, SNS, and EventBridge.
- 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
-
Create a Topic
- Topic type: Standard
- Name: Any name of your choice
- Leave other fields blank or default, and click Create
-
Create a Subscription
- Navigate to the newly created topic and click Create subscription
- Navigate to the newly created topic and click Create subscription
-
Fill in these details:
Topic ARN: The ARN of the created topic Protocol: Email (or SMS) Endpoint: Your email address
A confirmation email will be sent. Open it and hit Confirm.
Creating a Policy and Role for the Lambda Function
-
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" } ] }
- Review, name it (e.g.,
sns_publish
), and create it.
-
Create a Role
- Go to Roles → Create role
- Go to Roles → Create role
Creating the Lambda Function
-
Function Details
- Name:
nba_function
- Runtime: Python
- Execution Role: Select the previously created role (
nba_function_role
).
- Name:
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})
}
-
Add Environment Variables
- API_KEY: Your SportsAPI key
- SNS_TOPIC_ARN: The ARN of the created topic
-
Deploy the Function
- Click Deploy or use the shortcut
Ctrl+Shift+U
.
- Click Deploy or use the shortcut
Creating the EventBridge Schedule
-
Create a Rule
- Name: Any name of your choice
- Rule type: Schedule
- Cron expression:
0 * * * ? *
(runs hourly)
-
Select the Target
- Target type: Lambda Function
- Lambda function:
nba_function
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! 🏀✨
Top comments (0)