Skip to content

Instantly share code, notes, and snippets.

@snyk-omar
Created April 29, 2022 20:02
Show Gist options
  • Save snyk-omar/5510321c5403e067f24e875072265e8a to your computer and use it in GitHub Desktop.
Save snyk-omar/5510321c5403e067f24e875072265e8a to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
Requires a .env file in the directory where this file is run.
.env file should contain these:
SNYK_TOKEN=TOKEN
ORG_ID=ORG_ID_GUID
Output will be displayed in a log file: main.log.
"""
import logging
import urllib
import requests
logging.basicConfig(
format="%(levelname)s: %(message)s",
filename='main.log',
filemode='w',
encoding="utf-8",
level=logging.DEBUG,
)
def create_session(token: str) -> requests.Session:
"""
Create a session with the given token.
:return: a requests.Session object
"""
session = requests.Session()
session.headers.update({"Authorization": f"token {token}"})
logging.info(f"Created session with token.")
return session
def make_get_request(session: requests.Session, url: str) -> requests.Response:
"""
Make a request to the given URL.
:param session: a requests.Session object
:param url: the URL to make the request to
:return: a requests.Response object
"""
try:
logging.info(f"Making GET request to {url}")
response = session.get(url=url)
except requests.exceptions.RequestException as e:
logging.error(f"Error making GET request to {url}. Error: {e}")
finally:
logging.debug(f"Response: {response.json()}")
return response
def make_post_request(
session: requests.Session, url: str, data: dict
) -> requests.Response:
"""
Make a POST request to the given URL.
:param session: a requests.Session object
:param url: the URL to make the request to
:param data: the data to send in the request
:return: a requests.Response object
"""
try:
logging.info(f"Making POST request to {url}")
response = session.post(url, data=data)
logging.debug(f"Response: {response.json()}")
except requests.exceptions.RequestException as e:
logging.error(f"Error making POST request to {url}. Error: {e}")
finally:
return response
def get_secrets() -> dict:
"""
Get the secrets from the file.
:return: a dictionary of secrets
"""
secrets = {}
with open(".env", "r") as file:
for line in file:
key, value = line.strip().split("=")
secrets[key] = value
return secrets
def filter_project_ids(response: dict) -> list:
"""
Filter the project IDs from the response.
:param response: a dictionary of the response
:return: a list of project IDs
"""
data = response["data"]
logging.debug(f"Filtering project IDs from response. Response: {data}")
project_ids = []
for project in data:
project_ids.append(project["id"])
logging.debug(f"Project IDs: {project_ids}")
return project_ids
def main() -> None:
"""
Main function.
:return: None
"""
# Need to URL encode the strings because they contain special characters.
api_version = urllib.parse.quote("2022-04-06~experimental")
# Get the secrets.
secrets = get_secrets()
# Create a session with the token.
session = create_session(secrets["SNYK_TOKEN"])
# Make a GET request to the URL.
project_ids_response = make_get_request(
session=session,
url=f"https://api.snyk.io/v3/orgs/{secrets['ORG_ID']}/projects?version={api_version}",
)
# Filter the project IDs.
project_ids = filter_project_ids(response=project_ids_response.json())
responses = []
for id in project_ids:
project_issues_response = make_get_request(
session=session,
url=f"https://api.snyk.io/v3/orgs/{secrets['ORG_ID']}/issues?version={api_version}&project_id={id}",
)
responses.append(project_issues_response.json())
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment