I am want to use the Microsoft Graph API to get data from my outlook mailbox.
Using https://github.com/O365/python-o365#authentication and help from SO I have managed to connect to the Microsoft Graph API using the On behalf of a user (public) auth method.
This method returns a URL into the console which then needs to be copied into a browser to Authorize.
Surely I don't have to do this every time I call the Graph API??, and if im reading the above DOC correctly, I don't.
I believe I need to store the AUTH token given back from the URL and then use that when calling the Graph API? But I am having trouble implementing this into my code. Possibly using connection.request_token to store the token and then account.is_authenticated?
This is my first go at working with an API with this type of Auth method
Here is what I have so far.. Hoping someone can point me in the right direction
from O365 import Account, FileSystemTokenBackend
credentials = ('my_client_ID',)
token_backend = FileSystemTokenBackend(token_path=(r'C:\Users\Desktop', token_filename = 'my_token.txt')
account = Account(credentials, auth_flow_type = 'public', token_backend = token_backend)
account.authenticate(scopes = ['Mail.Read', 'offline_access'])
Related
i am trying to create a bot in python and i want it to sum up the info in google sheets but when i am using api key i can only read and cant edit is there something like api key that will work all the time and will do that i dont need to log in manually? (the error it gives me is error 401)
def main():
key = My_API_Key
discoveryUrl = 'https://sheets.googleapis.com/$discovery/rest?version=v4'
service = discovery.build('sheets', 'v4', http=httplib2.Http(), discoveryServiceUrl=discoveryUrl, developerKey=key)
spreadsheetId = '1z0jzLs0-OXu0I2Cw2BIPEdVzjgGZ_BPx0OcKimmfAhY'
clear_values_request_body = {}
service.spreadsheets().values().update(spreadsheetId=spreadsheetId, range='Sheet1', body=clear_values_request_body).execute()
this is what i have done before and it didnt work
Yes, you can use Google Credentials to create an Service Account. Here are some instructions on how to use Service Accounts. When you create one, you also get an email address. Simply share your sheet with that address, and it will be able to authenticate using the key.
EDIT: Scroll to the bottom of this page for more detailed API info.
In a django application, I try to have RW access to a google calendar which I own myself.
Tried several ways with a service account & client secrets, but all resulting in authentication errors.
The API explorer works, but it requests consent in a popup window, which is obviously not acceptable.
Documentation on google OAuth2 describes several scenarios. Probably "web server application" applies here? It says:
"The authorization sequence begins when your application redirects a
browser to a Google URL; the URL includes query parameters that
indicate the type of access being requested. Google handles the user
authentication, session selection, and user consent. The result is an
authorization code, which the application can exchange for an access
token and a refresh token."
Again, we do not want a browser redirection, we want direct access to the google calendar.
So question is: how can a django server access a google calendar, on which I have full rights, view events and add events using a simple server stored key or similar mechanism?
With help of DalmTo and this great article, I got RW access to a google calendar working from python code. I will summarize the solution here.
Here are the steps:
First of all register for a google service account: Service accounts are pre-authorized accounts that avoid you need to get consent or refresh keys every time:
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
(The part on G-suite can be ignored)
Download the service account credentials and store them safely. Your python code will need access to this file.
Go to your google calendar you want to get access to.
e.g. https://calendar.google.com/calendar/r/month
On the right side you see your calendars. Create an additional one for testing (since we'll write to it soon). Then point to this new calendar: click the 3 dots next to it and edit the sharing settings. Add the service account email address to the share under "share with specific people". (you can find the service account email address in the file downloaded previously under "client_email")
In the same screen, note the "calendar ID", you'll need it in below code.
Now you service account has the RW rights to the calendar.
Add at least one event to the calendar using the web UI (https://calendar.google.com/calendar/r/month) so we can read and change it from below code.
Then use following python code to read the calendar and change an event.
from google.oauth2 import service_account
import googleapiclient.discovery
SCOPES = ['https://www.googleapis.com/auth/calendar']
SERVICE_ACCOUNT_FILE = '<path to your service account file>'
CAL_ID = '<your calendar ID>'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = googleapiclient.discovery.build('calendar', 'v3', credentials=credentials)
events_result = service.events().list(calendarId=CAL_ID).execute()
events = events_result.get('items', [])
event_id = events[0]['id']
event = events[0]
service.events().update(calendarId=CAL_ID, eventId=event_id, body={"end":{"date":"2018-03-25"},"start":{"date":"2018-03-25"},"summary":"Kilroy was here"}).execute()
And there you go... read an event and updated the event.
How can i call Google+ API using access token in python, currently i am using the flow method which first exchanges the authentication url then it exchange credentials.
My code is this:
FLOW = OAuth2WebServerFlow(
client_id=client id,
client_secret=secret,
scope=scope,
user_agent=user_agent,redirect_uri=redirect_uri)
auth_uri = FLOW.step1_get_authorize_url()
credentials=FLOW.step2_exchange(code)
people_service = apiclient.discovery.build('people', 'v1',credentials=credentials)
connections = people_service.people().connections().list(resourceName='people/me').execute()
You need to actually visit the auth_uri web page, the user would log in and get an authentication code and it would redirect back to your application.
In a non-browser application you would do this out-of-band (OOB) and with redirect_uri='urn:ietf:wg:oauth:2.0:oob' and you could print(auth_uri), cut & paste it into a browser address bar and enter your user credentials.
When you get the authentication code you need to assign it to code in your script above, e.g. (for OOB):
code = input("Code: ") # raw_input() in Py2
Then the rest of your code would work fine.
I would consider looking at the oauthclient.<type>.Storage modules to store the credentials received from FLOW.step2_exchange(). So you don't necessarily need to do this exchange each time.
I have used the Python Starter project, and I can add time line cards that then show up on my Glass.
What I would like to do is call the endpoints from a standalone application running on my Mac to trigger the Python logic to insert entries into the timeline.
Any ideas on where I should start?
Edit: Not sure why this was down voted. I basically wanted to insert cards to my time line from Objective C. After digging around for a while, I was able to figure this out using the Objective C libraries that Google provides for interacting with their services.
Your code which inserts the timeline items will be largely the same, but you will need to use a different flow to acquire your access token. You probably want to use the OAuth 2.0 flow for installed applications which is also document in the Python API Client Library docs.
Your Glassware might work something like this:
Create a new flow
from oauth2client.client import OAuth2WebServerFlow
...
flow = OAuth2WebServerFlow(client_id='your_client_id',
client_secret='your_client_secret',
scope='https://www.googleapis.com/auth/glass.timeline',
redirect_uri='urn:ietf:wg:oauth:2.0:oob')
Create an Auth URL and instruct the user to access it in a web browser
auth_uri = flow.step1_get_authorize_url()
print 'Please navigate here ' + auth_uri
This will yield a code. Have the user paste that code to you.
Exchange the code for a credentials
credentials = flow.step2_exchange(code)
Store those credentials for later use in a file, database, or some other persistent storage. This is how you'll insert items into your user's timeline.
Using the credentials, insert an item into their timeline
http = httplib2.Http()
http = credentials.authorize(http)
mirror_service = build("mirror", "v1", http=http)
body = {
'notification': {'level': 'DEFAULT'},
'text':'Hello world!'
}
timeline_item = mirror_service.timeline().insert(body=body).execute()
I'm trying to use the Google Docs API with Python+Django and OAuth 2. I've got the OAuth access token, etc. via google-api-python-client, with the code essentially copied from http://code.google.com/p/google-api-python-client/source/browse/samples/django_sample/plus/views.py
Now, I assume I should be using the google gdata API, v 2.0.17. If so, I'm unable to find exactly how to authorize queries made using the gdata client. The docs at http://packages.python.org/gdata/docs/auth.html#upgrading-to-an-access-token (which appear outdated anyway), say to set the auth_token attribute on the client to an instance of gdata.oauth.OAuthToken. If that's the case, what parameters should I pass to OAuthToken?
In short, I'm looking for a brief example on how to authorize queries made using the gdata API, given an OAuth access token.
The OAuth 2.0 sequence is something like the following (given suitably defined application constants for your registered app).
Generate the request token.
token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=" ".join(SCOPES),
user_agent=USER_AGENT)
Authorise the request token. For a simple command-line app, you can do something like:
print 'Visit the following URL in your browser to authorise this app:'
print str(token.generate_authorize_url(redirect_url=REDIRECT_URI))
print 'After agreeing to authorise the app, copy the verification code from the browser.'
access_code = raw_input('Please enter the verification code: ')
Get the access token.
token.get_access_token(access_code)
Create a gdata client.
client = gdata.docs.client.DocsClient(source=APP_NAME)
Authorize the client.
client = token.authorize(client)
You can save the access token for later use (and so avoid having to do the manual auth step until the token expires again) by doing:
f = open(tokenfile, 'w')
blob = gdata.gauth.token_to_blob(token)
f.write(blob)
f.close()
The next time you start, you can reuse the saved token by doing:
f = open(tokenfile, 'r')
blob = f.read()
f.close()
if blob:
token = gdata.gauth.token_from_blob(blob)
Then, the only change to the authentication sequence is that you pass this token to OAuth2Token by specifying a refresh_token argument:
token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=" ".join(SCOPES),
user_agent=USER_AGENT,
refresh_token=token.refresh_token)
Hope this helps. It took a while to work it out :-).
This is from https://developers.google.com/gdata/docs/auth/overview:
Warning: Most newer Google APIs are not Google Data APIs. The Google Data APIs documentation applies only to the older APIs that are listed in the Google Data APIs directory. For information about a specific new API, see that API's documentation. For information about authorizing requests with a newer API, see Google Accounts Authentication and Authorization.
You should either use OAuth for both authorization and access or OAuth 2.0 for both.
For OAuth 2.0 API are now at https://developers.google.com/gdata/docs/directory.