Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialShezan Kazi
10,807 PointsPython Login to Rest API
Hi, at work we use a crm system that allows rest calls. I am trying to get the rest credentials with the following script. However the returned credentials are always empty, therefore I suspect some mistake in my code.
Could someone please proofread this? Thanks!
import requests
import re
import json
import datetime
class Login():
# defining CONSTANTS for xyz credentials
CLIENT_ID = 'XXXXXXXXXXXXXXXX'
CLIENT_SECRET = 'XXXXXXXXXXXXXXXX'
USER = 'xxxxxxx'
PASS = 'xxxxxxxxxxxx'
URL = 'https://auth.xyz.com/oauth/authorize?client_id='
# defining global variables
today = datetime.datetime.now()
today_morning = today.strftime('%Y%m%d') + "000000"
today_evening = today.strftime('%Y%m%d') + "235959"
# create url that gets forwarded to the token_url
def get_login(self):
get_auth_code = ("{}{}&response_type=code&action=Login&username={}&password={}".format(
URL, CLIENT_ID, USER, PASS))
# url that includes the token
auth_code_url = requests.get(get_auth_code).url
# extract token from token_url
auth_code = re.search('code=(.*)&', auth_code_url).group(1)
# get an access token
get_access_token = "https://auth.xyz.com/oauth/token?grant_type=authorization_code&code={}&client_id={}&client_secret={}".format(auth_code,CLIENT_ID, CLIENT_SECRET)
access_token = json.loads(requests.post(get_access_token).text)
login_url = "https://rest.xyz.com/rest-services/login?version=*&access_token=" + access_token["access_token"]
# capture RestToken & restUrl
rest_credentials = json.loads(requests.get(login_url).text)
print(rest_credentials)
def __init__(self):
get_login(self)
2 Answers
Shezan Kazi
10,807 PointsI solved it.. had to add Login() to the end.. :-)
Shezan Kazi
10,807 PointsHowever, I'm sure this code is not very well written, so any input is much appreciated!