Microsoft outlook graph events api: how to get different timezone? - python

I'm trying to GET Microsoft calendar events. Default timezone of my outlook account is US Eastern Time Zone. But the response I'm getting from rest api call is all in UTC. How can I get my default time zone i.e. US Eastern Time?
Here is my code:
def make_api_call(method, url, token, payload = None, parameters = None):
headers = { 'User-Agent' : 'python_tutorial/1.0',
'Authorization' : 'Bearer {0}'.format(token),
'Accept' : 'application/json'}
request_id = str(uuid.uuid4())
instrumentation = { 'client-request-id' : request_id,
'return-client-request-id' : 'true' }
headers.update(instrumentation)
response = None
if (method.upper() == 'GET'):
response = requests.get(url, headers = headers, params = parameters)
elif (method.upper() == 'POST'):
headers.update({ 'Content-Type' : 'application/json' })
response = requests.post(url, headers = headers, data = json.dumps(payload), params = parameters)
return response
def get_my_events(access_token, start_date_time, end_date_time):
get_events_url = graph_endpoint.format('/me/calendarView')
query_parameters = {'$top': '10',
'$select': 'subject,start,end,location',
'$orderby': 'start/dateTime ASC',
'startDateTime': start_date_time,
'endDateTime': end_date_time}
r = make_api_call('GET', get_events_url, access_token, parameters = query_parameters)
if (r.status_code == requests.codes.ok):
return r.json()
else:
return "{0}: {1}".format(r.status_code, r.text)
UPDATE:
Anyone else coming here for this kind of question, you need to update the headers to send any specific time zone. Here are the update headers, make sure you surround timezone in double quotes:
headers = { 'User-Agent' : 'python_tutorial/1.0',
'Authorization' : 'Bearer {0}'.format(token),
'Accept' : 'application/json',
'Prefer': 'outlook.timezone="Eastern Standard Time"'}

You need to specify the time zone using the Prefer: outlook.timezone header.
From the documentation:
Prefer: outlook.timezone
Use this to specify the time zone for start and end times in the response. If not specified, those time values are returned in UTC.
For example, to set it to US Eastern you would send
Prefer: outlook.timezone="Eastern Standard Time"

Related

Pinterest API 'bookmark' always returning the same string and data

I am trying to use pagination the way it is instructed in the Pinterest API Documentation, by passing 'bookmark' as a parameter to the next GET request in order to get the next batch of data.
However, the data returned is the EXACT same as the initial data I had received (without passing 'bookmark') and the value of 'bookmark' is also the same!
With this issue present, I keep receiving the same data over and over and can't get the entirety of the data. In my case I'm trying to list all campaigns.
Here is my python code:
url = f'https://api.pinterest.com/v5/ad_accounts/{ad_account_id}/campaigns'
payload = f"page_size=25"
headers = {
"Accept": "text/plain",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": f"Bearer {access_token}"
}
response = requests.request("GET", url, data=payload, headers=headers)
print(response)
feed = response.json()
print(feed)
bookmark=''
if 'bookmark' in feed:
bookmark = feed['bookmark']
print(bookmark)
while(bookmark != '' and bookmark != None and bookmark != 'null'):
url = f'https://api.pinterest.com/v5/ad_accounts/{ad_account_id}/{level}s'
payload = f"page_size=25&bookmark={bookmark}"
headers = {
"Accept": "text/plain",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": f"Bearer {access_token}"
}
response = requests.request("GET", url, data=payload, headers=headers)
print(response)
feed = response.json()
print(feed)
bookmark = feed['bookmark']
print(bookmark)
I think your condition in while is wrong, therefore you end up in the same loop. I'm currently also working with Pinterest API and below is my modified implementation how to get a list of ad accounts.
Basically you're testing if the bookmark is None. If yes, then you can return the result, otherwise you append the bookmark into query parameters and call the endpoint again.
from app.api.http_client import HttpClient
class PinterestAccountsClient():
def get_accounts(self, credentials) -> list[dict]:
headers = {
'Authorization': f"Bearer {credentials('access_token')}"
}
params = {
'page_size': 25
}
accounts = []
found_last_page = False
while not found_last_page:
try:
response = HttpClient.get(self.listing_url, headers=headers, params=params)
items = response.get('items', [])
bookmark = response.get('bookmark')
if bookmark is None:
found_last_page = True
else:
params['bookmark'] = bookmark
accounts.extend([{
'id': account['id'],
'name': account['name']
} for account in items])
return accounts

Spotify API refresh token

I am trying to use Spotify's API to get song details. My programming language is python and the code I am trying to execute is this:
def spotifysearch(searchterm):
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer OAUTH TOKEN',
}
params = (
('q', searchterm),
('type', 'track'),
('limit', '10'),
)
response = requests.get('https://api.spotify.com/v1/search', headers=headers, params=params)
a=response.json()
return a
However, my OAUTH TOKEN expires after every hour and I can't just manually get a new token every hour. I couldn't understand how to get my refresh token automatically.
Please provide me answer in either python or on curl (Both are fine with me)
Your first step will be to record:
when you got the token
when the token will expire
You can use dataclasses for this. Dataclasses have a post_init func, which is executed
after initialization. You should compute the expiry as a datetime there.
import dataclasses
#dataclasses.dataclass
class TToken:
access_token: str
refresh_token: str
created: datetime.datetime
expires: datetime.datetime
def __init_post__(self, data):
if data: # Not required
self.access_token = data['access_token']
self.created = datetime.datetime.utcnow()
self.expires = self.created + datetime.timedelta(minutes=59)
self.refresh_token = data['refresh_token']
def is_expired(self):
return datetime.datetime.utcnow() > self.expires
def as_header(self):
return {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': f'Bearer self.access_token',
}
For your tokens.
BASE64_CID_CSEC = <base64 encoded clientid:clientsecret>
def token_get(authorization_code: str):
data = {'form':{'grant_type': 'authorization_code',
'code': authorization_code,
'redirect_uri': <your redirect uri>},
'header':{'Authorization': f'Basic {BASE64_CID_CSEC}'}}
resp = requests.get('https://accounts.spotify.com/api/token', data=data['form'], headers=data['header'])
return TToken(resp)
def token_refresh(refresh_token: str):
data = {'form': {'grant_type': 'refresh_token', 'refresh_token': refresh_token},
'header': {'Authorization': f'Basic {BASE64_CID_CSEC}'}}
resp = requests.get('https://accounts.spotify.com/api/token', data=data['form'], headers=data['header'])
return TToken(resp)
Finally
token = token_get(authorization_code)
def spotify_search(searchterm: str):
if token.is_expired():
token = token_refresh(token.refresh_token)
params = (('q', searchterm),('type', 'track'),('limit', '10'))
resp = requests.get('https://api.spotify.com/v1/search', headers=token.as_header(), params=params)
return resp.json()

How to pass the customer id dynamically in the tap payment method to save the card value

I am sending the post request to the TAP PAYMENT GATEWAY in order to save the card, the url is expecting two parameters like one is the source (the recently generated token) and inside the url the {customer_id}, I am trying the string concatenation, but it is showing the error like Invalid JSON request.
views.py:
ifCustomerExits = CustomerIds.objects.filter(email=email)
totalData = ifCustomerExits.count()
if totalData > 1:
for data in ifCustomerExits:
customerId = data.customer_id
print("CUSTOMER_ID CREATED ONE:", customerId)
tokenId = request.session.get('generatedTokenId')
payload = {
"source": tokenId
}
headers = {
'authorization': "Bearer sk_test_**********************",
'content-type': "application/json"
}
# HERE DOWN IS THE url of TAP COMPANY'S API:
url = "https://api.tap.company/v2/card/%7B"+customerId+"%7D"
response = requests.request("POST", url, data=payload, headers=headers)
json_data3 = json.loads(response.text)
card_id = json_data3["id"]
return sponsorParticularPerson(request, sponsorProjectId)
Their expected url = https://api.tap.company/v2/card/{customer_id}
Their documentation link: https://tappayments.api-docs.io/2.0/cards/create-a-card
Try this..
First convert dict. into JSON and send post request with request.post:
import json
...
customerId = str(data.customer_id)
print("CUSTOMER_ID CREATED ONE:", customerId)
tokenId = request.session.get('generatedTokenId')
payload = {
'source': tokenId
}
headers = {
'authorization': "Bearer sk_test_**************************",
'content-type': "application/json"
}
pd = json.dumps(payload)
# HERE DOWN IS THE url of TAP COMPANY'S API:
url = "https://api.tap.company/v2/card/%7B"+customerId+"%7D"
response = requests.post(url, data=pd, headers=headers)
json_data3 = json.loads(response.text)
card_id = json_data3["id"]
return sponsorParticularPerson(request, card_id)
Please tell me this works or not...

Automate access token generation

In order to extract data from a private API, I need to generate access tokens using my auth key and credentials. My current code is split in two parts. The first generates the access token:
import requests
url = "https://api.abcdef.com/AuthorizationServer/Token"
payload = "{\r\n \"grant_type\" : \"password\",\r\n \"username\" : \"user#aldfh.com\",\r\n \"password\" : \"kajshdgfkuyb\",\r\n \"scope\" : \"API\"\r\n}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Basic VGFibGVhdV9DaW94QFRhYmxlYXVfQ2lveDo0Ix '
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
The response looks like this:
{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpY0JVSWQiOjQ1OTg0MjEsIm5hbWUiOiJyYW15YS5nb3RldHlAY2lveGhlYWx0aC5jb20iLCJpc3MiOiJodHRwczovL2FwaS5pbmNvbnRhY3QuY29tIiwic3ViIjoidXNlcjoxNTMyMDI2MiIsImF1ZCI6IlRhYmxlYXVfQ2lveEBUYWJsZWF1X0Npb3giLCJleHAiOjE1Nzk2Mjg1NzcsImlhdCI6MTU3OTYyNDk3OCwiaWNTY29wZSI6IjgiLCJpY0NsdXN0ZXJJZCI6IkMzMSIsImljQWdlbnRJZCI6MTUzMjAyNjIsImljU1BJZCI6MTQ5NiwibmJmIjoxNTc5NjI0OTc4fQ.rEZiMHPsE1inwuWFME1oV_oD54TqkU00-uml3NjCkClW3R-_bVC7A3PxI4zGlJms1rvsZkgO3XX8-1coeV6_jtI-l3nCHixVk2nboepqAspoxT3o9w4vhBhZzvs-TAsqyk4fCrSwwHFXwn8xOMdfrqZqknXHLlVtKlGJg_Uy3bmwEiioocMN3BRZE_269_v5Ez4b94_juUHLPDWye7kS5-8cs4Izsk7HePn-Sm_-FLEqEeb2C09NUGWU8SdyA3EtQhMAiHkU-wN8uQ8wKcWoUfO7WtrSO4zbicFZHgA9Cw",
"token_type":"bearer",
"expires_in":3600,
"refresh_token":"pDYllH2UsVIYq3Pn3Dg==",
"scope":"Api",
"resource_server_base_uri":"https://api-c31.it.com/itAPI/",
"refresh_token_server_uri":"https://api-c31.it.com/AuthorizationServer/Token",
"agent_id":162,
"team_id":24355,
"bus_no":4421}'
The access token is part of the output and I paste this into the following code to generate the response:
def getPerformance():
# api-endpoint
#Give the specified url ,accessToken
BASEURL = 'https://api-c31.ict.com/tAPI/'
accessToken = "{eyJ0eXAiOiJKV1QiLCJhbGciSUzI1NiJ9.eyJpY0JVSWQiOjQ1OTgyYW15YS5nb3RldHlAY2lveGhlYWx0aC5jb20iLCJpc3MiOiJodHRwczovL2FwaS5pbmNvbnRhY3QuY29tIiwic3ViIjoidXNlcjoxNTMyMDI2MiIsImF1ZCI6IlRhYmxlYXVfQ2lveEBUYWJsZWF1X0Npb3giLCJleHAiOjE1Nzk1NjA0MjYsImlhdCI6MTU3OTU1NjgyNywiaWNTY29wZSI6IjgiLCJpY0NsdXN0ZXJJZCI6IkMzMSIsImljQWdlbnRJZCI6MTUzMjAyNjIsImljU1BJZCI6MTQ5NiwibmJmIjoxNTc5NTU2ODI2fQ.JIzsPLK8kg8Zqq_uITeNp6b24xuglcmtjVbD9Ll-ooq943gIILvr_SQ8cTKNl50YMyiX_mu48pupf-D0b-Ntbmb7hYOTNY7tjp8skM8uBDmuSzG1GnVQh3ZotdlofhiEDU9_U4sQsovqdDtXyi5inaoJ95TeBS_YQp_3LSv3pjfXQNWdt1bcn7arHWdIdl6qD5qXm0DhXQArhTr35mViZn-ZxITW4nvEi-gwZz6DdLWuWcW5kTbbzvucroVUPM-dZvzNJvMEruJvriUGl3Y2DSlB5qTLo3JqbLwujsoZfhaxfJ1eAFKd13t6mMenQ5TOwVV3Rg_yp7DfeBbnWcmwtA}"
#Check if accessToken is empty or null
if accessToken != "":
#Give necessary parameters for http request
payload={'startDate':'1/1/2020',
'endDate':'1/6/2020',
'fields':'"teamId","calls"'}
#add all necessary headers
header_param = {'Authorization': 'bearer ' + '{accessToken}','content-Type': 'application/x-www-form-urlencoded','Accept': 'application/json, text/javascript, */*'}
# Make get http request
answer = requests.get(BASEURL + 'services/{version}/g/h' , headers = header_param, params=payload)
#print response appropriately
print (answer)
else: print('error')
My issue is that I need to be able to merge both scripts in order to be able to automate the process.
Try adding the following changes to the first part of your code, then with the access token at the bottom, pass it into the getPerformance() function:
#Added json import here
import json
import requests
url = "https://api.abcdef.com/AuthorizationServer/Token"
payload = "{\r\n \"grant_type\" : \"password\",\r\n \"username\" : \"user#aldfh.com\",\r\n \"password\" : \"kajshdgfkuyb\",\r\n \"scope\" : \"API\"\r\n}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Basic VGFibGVhdV9DaW94QFRhYmxlYXVfQ2lveDo0Ix '
}
response = requests.request("POST", url, headers=headers, data = payload)
#Note the changes here
json = response.read()
data = json.loads(json)
accessToken = data['access_token']
Then wherever you call the getPerformanceFunction(), you want to change it to getPerformance(accessToken). You'll need to change the function definition to this too.
Based on #Cutter's response above, making the following changes worked for me:
import requests
import json
url = "https://api.abcdef.com/AuthorizationServer/Token"
payload = "{\r\n \"grant_type\" : \"password\",\r\n \"username\" : \"user#aldfh.com\",\r\n \"password\" : \"kajshdgfkuyb\",\r\n \"scope\" : \"API\"\r\n}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Basic VGFibGVhdV9DaW94QFRhYmxlYXVfQ2lveDo0Ix '
}
response = requests.request("POST", url, headers=headers, data = payload)
testresp = response.text
data = json.loads(testresp)
#Change function definition to :
def getPerformance(data):
# api-endpoint
#Give the specified url ,accessToken
# =============================================================================
BASEURL = 'https://api-c31.ict.com/API/'
accessToken = (data["access_token"])

Outlook Calendar API - Python

I am trying to retrieve events from the Outlook Calendar using the API. I only want to retrieve events after today. I'm using the following code (which is basically a cut and paste from Microsoft's tutorial):
def make_api_call(method, url, token, user_email, payload = None, parameters = None):
# Send these headers with all API calls
headers = { 'User-Agent' : 'python_tutorial/1.0',
'Authorization' : 'Bearer {0}'.format(token),
'Accept' : 'application/json',
'X-AnchorMailbox' : user_email }
# Use these headers to instrument calls. Makes it easier
# to correlate requests and responses in case of problems
# and is a recommended best practice.
request_id = str(uuid.uuid4())
instrumentation = { 'client-request-id' : request_id,
'return-client-request-id' : 'true' }
headers.update(instrumentation)
response = None
if (method.upper() == 'GET'):
response = requests.get(url, headers = headers, params = parameters)
print response.url
elif (method.upper() == 'DELETE'):
response = requests.delete(url, headers = headers, params = parameters)
elif (method.upper() == 'PATCH'):
headers.update({ 'Content-Type' : 'application/json' })
response = requests.patch(url, headers = headers, data = json.dumps(payload), params = parameters)
elif (method.upper() == 'POST'):
headers.update({ 'Content-Type' : 'application/json' })
response = requests.post(url, headers = headers, data = json.dumps(payload), params = parameters)
return response
This function gets called from the following:
get_events_url = outlook_api_endpoint.format('/Me/Events')
query_parameters = {'$select': 'Subject,Start,End',
'$orderby': 'Start/DateTime ASC',
'startDateTime' : datetime.datetime.now().isoformat(),}
r = make_api_call('GET', get_events_url, access_token, user_email, parameters = query_parameters)
It simply returns the first 10 entries in the calendar rather than entries from today onwards. How do I get back entries for specific dates?
I've found a solution that works for me. First I've changed events to calendarview, I've capitalised StartDateTime and added EndDateTime so it looks like this:
get_events_url = outlook_api_endpoint.format('/Me/calendarview')
query_parameters = {'$select': 'Subject,Start,End',
'$orderby': 'Start/DateTime ASC',
'StartDateTime' : datetime.datetime.now().isoformat(),
'EndDateTime' : datetime.datetime(2100,12,31),}
r = make_api_call('GET', get_events_url, access_token, user_email, parameters = query_parameters)
It works so I'm happy

Categories