Created
May 20, 2021 08:37
-
-
Save gspncr/72b92ebb4eea2c546ec1e43250a6c568 to your computer and use it in GitHub Desktop.
Multiple NR Queries to CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests, json, csv, re, os.path | |
graphQLEndpoint = 'https://api.newrelic.com/graphql' | |
#graphQLEndpoint = 'https://api.eu.newrelic.com/graphql' | |
APIKey = 'NRAK-xxxx' | |
headers = {"Content-Type": 'application/json',"API-Key": APIKey} | |
def getAccounts(): | |
query = """ | |
{ | |
actor { | |
accounts { | |
id | |
} | |
} | |
} | |
""" | |
request = requests.post(graphQLEndpoint, json={'query': query}, headers=headers) | |
jsonpayload = json.loads(request.text) | |
entries = len(jsonpayload["data"]["actor"]["accounts"]) | |
for x in range(entries): | |
runQuery(jsonpayload["data"]["actor"]["accounts"][x]["id"]) | |
return 0 | |
def makeCSV(request): | |
filename = 'apdex.csv' | |
file_exists = os.path.isfile(filename) | |
with open(filename, 'a') as csvfile: | |
fieldnames = ['Name', 'Score'] | |
writer = csv.DictWriter(csvfile, fieldnames=fieldnames) | |
if not file_exists: | |
writer.writeheader() | |
jsonpayload = json.loads(request.text) | |
entries = len(jsonpayload["data"]["actor"]["account"]["nrql"]["results"]) | |
for x in range(entries): | |
print(jsonpayload["data"]["actor"]["account"]["nrql"]["results"][x]["facet"], jsonpayload["data"]["actor"]["account"]["nrql"]["results"][x]["score"]) | |
if jsonpayload["data"]["actor"]["account"]["nrql"]["results"][x]["score"] > 0: | |
writer.writerow({'Name': jsonpayload["data"]["actor"]["account"]["nrql"]["results"][x]["facet"], 'Score': jsonpayload["data"]["actor"]["account"]["nrql"]["results"][x]["score"]}) | |
def runQuery(accountId): | |
query = """ | |
{ | |
actor { | |
account(id: ACCOUNT_ID) { | |
nrql(query: "FROM PageView SELECT apdex(duration) facet appName since 7 days ago") { | |
results | |
} | |
} | |
} | |
} | |
""" | |
queryId = re.sub('ACCOUNT_ID', str(accountId), query) | |
request = requests.post(graphQLEndpoint, json={'query': queryId}, headers=headers) | |
makeCSV(request) | |
getAccounts() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment