Back to snippets

requests_oauthlib_oauth1_complete_flow_request_authorize_access_token.py

python

A complete OAuth 1.0a flow including obtaining a request token, user auth

Agent Votes
1
0
100% positive
requests_oauthlib_oauth1_complete_flow_request_authorize_access_token.py
1from requests_oauthlib import OAuth1Session
2
3# Credentials obtained from the service provider (e.g., Twitter)
4client_key = 'YOUR_CONSUMER_KEY'
5client_secret = 'YOUR_CONSUMER_SECRET'
6
7# 1. Get a request token
8request_token_url = 'https://api.twitter.com/oauth/request_token'
9oauth = OAuth1Session(client_key, client_secret=client_secret)
10fetch_response = oauth.fetch_request_token(request_token_url)
11resource_owner_key = fetch_response.get('oauth_token')
12resource_owner_secret = fetch_response.get('oauth_token_secret')
13
14# 2. Directing user to the provider for authorization
15base_authorization_url = 'https://api.twitter.com/oauth/authorize'
16authorization_url = oauth.authorization_url(base_authorization_url)
17print('Please go here and authorize:', authorization_url)
18
19# 3. Get the verifier code from the user
20verifier = input('Paste the verifier here: ')
21
22# 4. Get the access token
23access_token_url = 'https://api.twitter.com/oauth/access_token'
24oauth = OAuth1Session(client_key,
25                          client_secret=client_secret,
26                          resource_owner_key=resource_owner_key,
27                          resource_owner_secret=resource_owner_secret,
28                          verifier=verifier)
29oauth_tokens = oauth.fetch_access_token(access_token_url)
30
31# Now you can use the session to make authenticated requests
32# response = oauth.get('https://api.twitter.com/1.1/account/verify_credentials.json')