Skip to content

Instantly share code, notes, and snippets.

@vinovator
Last active June 28, 2022 22:48
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save vinovator/98b0fb7eb30805595bd6 to your computer and use it in GitHub Desktop.
Save vinovator/98b0fb7eb30805595bd6 to your computer and use it in GitHub Desktop.
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
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
Copy link
Author

@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