Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A sample code to invoke GET method of restful API with digest authentication
#Python 2.7.6
#RestfulClient.py
import requests
from requests.auth import HTTPDigestAuth
import json
# Replace with the correct URL
url = "http://api_url"
# It is a good practice not to hardcode the credentials. So ask the user to enter credentials at runtime
myResponse = requests.get(url,auth=HTTPDigestAuth(raw_input("username: "), raw_input("Password: ")), verify=True)
#print (myResponse.status_code)
# For successful API call, response code will be 200 (OK)
if(myResponse.ok):
# Loading the response data into a dict variable
# json.loads takes in only binary or string variables so using content to fetch binary content
# Loads (Load String) takes a Json file and converts into python data structure (dict or list, depending on JSON)
jData = json.loads(myResponse.content)
print("The response contains {0} properties".format(len(jData)))
print("\n")
for key in jData:
print key + " : " + jData[key]
else:
# If response code is not ok (200), print the resulting http error code with description
myResponse.raise_for_status()
@wgsl2005

This comment has been minimized.

Copy link

wgsl2005 commented Nov 1, 2017

got 403 error using above code. i made sure my AD username and password are correct. any idea why?

@vinovator

This comment has been minimized.

Copy link
Owner Author

vinovator commented Jul 10, 2018

@wgsl2005 - the code assumes that the credentials are passed through digest authentication. If that is not the case, you can try out other authentication methods

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.