Skip to content

Instantly share code, notes, and snippets.

@MrMikeFloyd
Last active June 29, 2021 13:07
Show Gist options
  • Save MrMikeFloyd/76db50a58ceda1773da9d79a5cb95372 to your computer and use it in GitHub Desktop.
Save MrMikeFloyd/76db50a58ceda1773da9d79a5cb95372 to your computer and use it in GitHub Desktop.
Sample AWS Lambda (Python) to authenticate against a GraphQL db, printing the result, and storing the query duration in a S3 bucket. The credentials are taken from SSM parameter store. In order to make external libraries such as requests available at execution time, these need to be packaged beforehand (using virtualenv and the like).
import json
import urllib.parse
import boto3
import requests
import time
import datetime
ALBUM_ID = "REPLACE_ME_ALBUM_ID"
S3_BUCKET = "REPLACE_ME_BUCKET_NAME"
S3_KEY = "REPLACE_ME_BUCKET_OBJECT_NAME"
GRAPHQL_AUTH_URL = "REPLACE_ME_AUTH_URL"
GRAPHQL_QUERY_URL = "REPLACE_ME_QUERY_URL"
SSM_GRAPHQL_USERNAME = "REPLACE_ME_PARAMETERSTORE_USERNAME_PARAM"
SSM_GRAPHQL_PASSWORD = "REPLACE_ME_PARAMETERSTORE_PASSWORD_PARAM"
s3 = boto3.client("s3")
ssm = boto3.client("ssm")
def get_password():
return ssm.get_parameter(
Name=SSM_GRAPHQL_PASSWORD,
WithDecryption=True)["Parameter"]["Value"]
def get_username():
return ssm.get_parameter(
Name=SSM_GRAPHQL_USERNAME)["Parameter"]["Value"]
def get_credentials():
credentials = {
"email": get_username(),
"password": get_password()
}
return credentials
query = """
query {
album(albumId: "REPLACE_ME_ALBUM_ID"){
displayTitle,
id
}
}
"""
query = query.replace("REPLACE_ME_ALBUM_ID", ALBUM_ID)
def get_login_headers():
login_response = requests.post(GRAPHQL_AUTH_URL, json=get_credentials())
print(login_response)
login_token = login_response.json()["jwt"]
return {"Authorization": "Bearer {}".format(login_token)}
def run_query(query):
login_header = get_login_headers()
start = time.perf_counter_ns()
request = requests.post(GRAPHQL_QUERY_URL, json={"query": query}, headers=login_header)
end = time.perf_counter_ns()
exec_duration = (end - start) / 1_000_000
print("Request took {} ms.".format(exec_duration))
if request.status_code == 200:
process_result(request.json())
return exec_duration
else:
raise Exception("Ran into an error performing the query: {}. Query: {}".format(request.status_code, query))
def process_result(result):
album_metadata = result["data"]["album"]
print("Retrieved album metadata: {}".format(album_metadata))
def write_result(result):
response = s3.get_object(Bucket=S3_BUCKET, Key=S3_KEY)
content = response['Body'].read().decode('utf-8')
content += "\n"
content += "{}|{}".format(result, datetime.datetime.now())
s3.put_object(Bucket=S3_BUCKET, Key=S3_KEY, Body=content)
print("Updated S3 bucket")
# Call handling
def lambda_handler(event, context):
duration = run_query(query)
write_result(duration)
@MrMikeFloyd
Copy link
Author

MrMikeFloyd commented Jun 29, 2021

Prerequisites for this to work:

  • Access credentials to a public GraphQL API (and knowledge about its schema)
  • Access privileges for writing and reading from the specified S3 bucket
  • Access privileges for SSM parameter store
  • The Lambda function needs to be packaged with the requests package (and its transitive dependencies - that would be certify, chardet, idna, and urllib3). Information on how to do that can be found in the AWS developer guide.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment