I am using this API to get user emails for every member of a team. The teams are taken from a mongo database. I want to get this API to run for every team in the database and to return a list of emails for every member of every team. Right now, the API is only retrieving emails for members of the first team in the database.
with open('config/config.json') as f:
config = json.load(f)
API_KEY = config['API_KEY'] # loads API key
# Database info
client = MongoClient(config['HOST'], config['PORT'])
db = client[config['DATABASE']]
teams = list(db.teams.find()) # gets all the teams from the database
def list_users():
url = 'https://api.pagerduty.com/users'
headers = {
'Accept': 'application/vnd.pagerduty+json;version=2',
'Authorization': 'Token token={token}'.format(token=API_KEY)
}
result = []
for team in teams:
payload = {
'team_ids[]': team['team_id'],
'limit': 100,
'offset': 0
}
r = requests.get(url, headers=headers, params=payload)
users = r.json()['users']
emails = []
# loops for each user and retrieves their email
for user in users:
if r.status_code == 200:
emails.append(user['email'])
else:
return None
return emails
return result
How can I get this to run for every team from the database?
It looks like you're prematurely returning from your loop on teams. If you collect the emails in the result list instead, your issue is resolved.
def list_users():
url = 'https://api.pagerduty.com/users'
headers = {
'Accept': 'application/vnd.pagerduty+json;version=2',
'Authorization': 'Token token={token}'.format(token=API_KEY)
}
result = []
for team in teams:
payload = {
'team_ids[]': team['team_id'],
'limit': 100,
'offset': 0
}
r = requests.get(url, headers=headers, params=payload)
users = r.json()['users']
emails = []
# loops for each user and retrieves their email
for user in users:
if r.status_code == 200:
emails.append(user['email'])
result.append(emails)
return result
Related
Having some trouble with this. I know that I have to use the offset value to pull more than 100 records, here is what I currently have:
AIRTABLE_BASE_ID = 'airtablebaseid'
AIRTABLE_API_KEY = 'airtableapikey'
AIRTABLE_TABLE_NAME = 'airtablename'
endpoint = f'https://api.airtable.com/v0/{AIRTABLE_BASE_ID}/{AIRTABLE_TABLE_NAME}?filterByFormula=AND(NOT(%7BSent+to+Payroll%7D+%3D+%22Sent%22)%2CNOT(%7BSent+to+Payroll%7D+%3D+%22Skipped%22))'
def get_airtable():
headers = {
"Authorization": f"Bearer {AIRTABLE_API_KEY}"
}
response = requests.get(endpoint, headers=headers)
return response
recordList = []
recordIDs = []
recordTimeStamp = []
response = get_airtable()
data = response.json()
for record in data['records']:
recordList.append(record['fields'])
recordIDs.append(record['id'])
recordTimeStamp.append(record['createdTime'])
print(record)
Airtable can't give you more than 100 records per request, it works, as you said it, with pagination and offset.
The first request you made without offset parameter will return you a payload with a offset field set to n, you have to pass that offset to your next request to get the n next records, and so on...
response = get_airtable()
data = response.json()
OFFSET = data['offset'] #not sur if "offset" is at root of the response
endpoint = f'https://api.airtable.com/v0/{AIRTABLE_BASE_ID}/{AIRTABLE_TABLE_NAME}?offset={OFFSET}&filterByFormula=AND(NOT(%7BSent+to+Payroll%7D+%3D+%22Sent%22)%2CNOT(%7BSent+to+Payroll%7D+%3D+%22Skipped%22))'
I have the following csv file 1 which contains the features of the songs that have been listened to by a spotify user. The features I extracted with the following code block [2]. I would now like to add the information relating to the genre of the song, what can I do? Or is there a way to go back to the genre of the song starting from the bpm?
[2]
def get_id(track_name: str,artist:str, token: str) -> str:
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': f'Bearer ' + token,
}
track_artist = track_name+ " " + artist
params = [
('q',track_artist ),#q is the search query parameter
('type', 'track'),
]
try:
response = requests.get('https://api.spotify.com/v1/search',
headers = headers, params = params, timeout = 10)
json = response.json()
first_result = json['tracks']['items'][0]
track_id = first_result['id']
return track_id
except:
return None
# Get track_id for streaming history
spotify_data["track_id"] = spotify_data.apply(lambda x: get_id(x["track_name"],
x["artist_name"],
token),axis=1)
# get track's feature
my_feature = pd.DataFrame(columns=["song_id","energy", "liveness","tempo","speechiness",
"acousticness","instrumentalness","danceability",
"duration_ms","loudness","valence",
"mode","key","genre"])
In case you need it I can show you all the code I use, I didn't do it just to avoid pasting useless code.
I'm brand new to python and api as well.
I'm trying to use a endpoint we have at work.
We have an API we are using a lot, we also have an UI. But using the UI we can only extract 10.000 records at the time.
There is no limit on the api.
I have found a small piece of code - but i need to add a nextpagetoken.
My code looks like this:
login_url = 'https://api.ubsend.io/v1/auth/login'
username = 'xxxxx'
password = 'xxxxx'
omitClaims = "true"
session = requests.Session()
session.headers['Accept'] = "application/json; charset=UTF-8"
response = session.post(
login_url,
json={'username': username, 'password': password},
headers={'VERSION': '3'},
)
response.raise_for_status()
response_data = response.json()
print(response_data)
This gives me the AccessToken.
Then I call:
getevents = 'https://api.ubsend.io/v1/reporting/shipments?'
data ={'client_id': 13490, 'created_after': '2020-05-01T00:00', 'created_before': '2021-05-02T00:00'} req.prepare_url(getevents, data)
events = requests.get(req.url, headers={'Authorization' : 'Bearer ' + response_data['accessToken'], Content-Type': 'application/json'})
events.json()
Which returns:
'nextPageToken': 'NjA4ZDc3YzNkMjBjODgyYjBhMWVkMTVkLDE2MTk4ODM5NzA3MDE='}
So I want to loop my script - until nextPageToken is blank ....
Any thoughts?
Edit thanks for the update. I think this might be the solution we're looking for. You might have to do some poking around to figure out exactly what the name of the page_token URL parameter should be.
has_next = True
getevents = 'https://api.ubsend.io/v1/reporting/shipments?'
token = None
while has_next:
data ={'client_id': 13490, 'created_after': '2020-05-01T00:00', 'created_before': '2021-05-02T00:00'}
if token:
# I don't know the proper name for this URL parameter.
data['page_token'] = token
req.prepare_url(getevents, data)
events = requests.get(req.url, headers={'Authorization' : 'Bearer ' + response_data['accessToken'], Content-Type: 'application/json'})
token = events.json().get('nextPageToken')
if not token:
has_next = False
I made a slight typo. It should be events.json().get('nextPageToken') I believe.
Let me know if this works.
We managed to connect to our dynamics 365 cloud instance with token auth. However, we were hoping to find package like "pydynamics".
The package "https://libraries.io/pypi/dynamics365crm-python" seems newer, but it seems only to be able to handle standard objects, not custom objects.
Our current solution works with REST only.
import requests
import json
#set these values to retrieve the oauth token
crmorg = 'https://org.crm4.dynamics.com' #base url for crm org
clientid = '<id>' #application client id
client_secret = '<secret>'
username = 'dynamics-api#org.com' #username
userpassword = 'pw' #password
tokenendpoint = 'https://login.microsoftonline.com/bb23defa-be1d-4137-969b-324f8468f15a/oauth2/token' #oauth token endpoint
authorizationendpoint = 'https://login.microsoftonline.com/bb23defa-be1d-4137-969b-324f8468f15a/oauth2/authorize'
#build the authorization token request
tokenpost = {
'client_id':clientid,
'resource':crmorg,
'client_secret':client_secret,
'username':username,
'password':userpassword,
'grant_type':'password',
'oauthUrl':authorizationendpoint
}
#make the token request
tokenres = requests.post(tokenendpoint, data=tokenpost)
#set accesstoken variable to empty string
accesstoken = ''
#extract the access token
try:
accesstoken = tokenres.json()['access_token']
except(KeyError):
#handle any missing key errors
print('Could not get access token')
#set these values to query your crm data
crmwebapi = 'https://<org>.crm4.dynamics.com/api/data/v9.1' #full path to web api endpoint
crmwebapiquery = '/new_households' #web api query (include leading /)
#prepare the crm request headers
crmrequestheaders = {
'Authorization': 'Bearer ' + accesstoken,
'OData-MaxVersion': '4.0',
'OData-Version': '4.0',
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
'Prefer': 'odata.maxpagesize=500',
'Prefer': 'odata.include-annotations=OData.Community.Display.V1.FormattedValue'
}
#make the crm request
crmres = requests.get(crmwebapi+crmwebapiquery, headers=crmrequestheaders)
try:
#get the response json
crmresults = crmres.json()['value'][0]
#loop through it
for key,value in crmresults.items():
print (key, value)
except KeyError:
#handle any missing key errors
print('Could not parse CRM results')
Anyone know a package?
REST API is the way to go.
We use them every time with JavaScript and parase the response as Json.
Below is sample call which I perform within crm, you will see the response been transformed into Json
Don't worry much about details, for you important is this line var results = JSON.parse(this.response);
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/accounts?$select=accountcategorycode,accountclassificationcode,accountid,accountnumber,accountratingcode", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\",odata.maxpagesize=10");
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
for (var i = 0; i < results.value.length; i++) {
var accountcategorycode = results.value[i]["accountcategorycode"];
var accountcategorycode_formatted = results.value[i]["accountcategorycode#OData.Community.Display.V1.FormattedValue"];
var accountclassificationcode = results.value[i]["accountclassificationcode"];
var accountclassificationcode_formatted = results.value[i]["accountclassificationcode#OData.Community.Display.V1.FormattedValue"];
var accountid = results.value[i]["accountid"];
var accountnumber = results.value[i]["accountnumber"];
var accountratingcode = results.value[i]["accountratingcode"];
var accountratingcode_formatted = results.value[i]["accountratingcode#OData.Community.Display.V1.FormattedValue"];
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
I write a python script to do GET and PUT method in zendesk API and successfully get the data I wanted and do some updates to the tickets.
below method resulting this ticket number "6442" and put method is intended to remove the tags
from urllib.parse import urlencode
import json
import requests
# Set the credentials
credentials = 'some email', 'some password'
session = requests.Session()
session.auth = credentials
# Set the GET parameters
params_noreply_window = {
'query': 'type:ticket tags:test status<closed',
}
params_oustide_businesshour = {
'query': 'type:ticket tags:send_whatsapp_obh status:new',
}
url_search1 = 'https://propertypro.zendesk.com/api/v2/search.json?' + \
urlencode(params_noreply_window)
url_search2 = 'https://propertypro.zendesk.com/api/v2/search.json?' + \
urlencode(params_oustide_businesshour)
response_noreply_window = session.get(url_search1)
response_oustide_businesshour = session.get(url_search2)
# -----------------------------------------------------------------------------
if response_noreply_window.status_code != 200 | response_oustide_businesshour.status_code != 200:
print('Status 1:', response_noreply_window.status_code + 'Status 2:', response_oustide_businesshour.status_code,
'Problem with the request. Exiting.')
exit()
# Print the subject of each ticket in the results
data_noreply_window = response_noreply_window.json()
data_oustide_businesshour = response_oustide_businesshour.json()
# Ticket to update
# Create a list containing the values of the id field
# for each dictionary that is an element of the list data
id_merged1 = [result['id'] for result in data_noreply_window['results']]
print(type(id_merged1))
print(id_merged1)
id_merged2 = [result['id'] for result in data_oustide_businesshour['results']]
print(type(id_merged2))
print(id_merged2)
# Join value of list by using comma separated
id_merged1_joined = ','.join(map(str, id_merged1))
print(id_merged1_joined)
id_merged2_joined = ','.join(map(str, id_merged2))
print(id_merged2_joined)
# Package the data in a dictionary matching the expected JSON
data_comment1 = {"ticket":
{
"remove_tags": ["test"]
}
}
data_comment2 = {"ticket":
{
"remove_tags": ["send_whatsapp_obh"]
}
}
# Encode the data to create a JSON payload
payload1 = json.dumps(data_comment1)
payload2 = json.dumps(data_comment2)
print("**Start**")
# Set the request parameters
url_put_comments1 = 'https://propertypro.zendesk.com/api/v2/tickets/update_many.json?' +\
'ids=' + id_merged1_joined
url_put_comments2 = 'https://propertypro.zendesk.com/api/v2/tickets/update_many.json?' +\
'ids=' + id_merged2_joined
user = 'some email'
pwd = 'some password'
headers = {'content-type': 'application/json'}
# Do the HTTP put request
response_request_noreply = requests.put(url_put_comments1, data=payload1,
auth=(user, pwd), headers=headers)
response_request_obh = requests.put(url_put_comments2, data=payload2,
auth=(user, pwd), headers=headers)
# Check for HTTP codes other than 200
if response_request_noreply.status_code != 200 | response_request_obh.status_code != 200:
print('Status 1:', response_request_noreply.status_code +
'Status 1:', response_request_obh.status_code,
'Problem with the request. Exiting.')
exit()
# Report success
print('Successfully added comment to tickets')
However, after running my python code and do another GET method, the same ticket number still appears and I need to wait in random time to get the result I intend which is return 'null' since I have updated the ticket by using PUT method.
Can anyone explain me how does the Zendesk API works? and my apology for my incorrect sentences in explaining my concern.