Search code examples
jsonpython-2.7basic-authenticationaccess-tokenatlassian-crucible

How to call a REST API using Python using json request/response- Crucible Development


I am a newbie to python and am trying to create a script to login to crucible and use the token to pass to other services. 1) I am able to make a xml request and get a response but as soon as I pass the headers to my conn.request it says HTTP Error 415, unsupported Media Type. I have done quiet a bit of research on this topic and found out that the rest API might not be supporting the json reques, but Crucible says that there API supports json so seems to be some other issue, 2) when trying to pass the args generated using feauth the auth token is not getting used , for now I have appended it to url and it works.

Please help me with the same , below is my script

import httplib
import urllib
import json
from xml.etree.ElementTree import XML 
import xml.dom.minidom



    conn = httplib.HTTPSConnection("fisheye")
    args=urllib.urlencode({'userName':'UNAME', 'password':'PWD'})
    headers={'content-type':'application/json', 'accept':'application/json'}
    #headers={'Authorization' : 'Basic %s' % base64.b64encode("username:password")}

r1 = conn.request("post", "/rest-service/auth-v1/login", args)
#status = r1[u'headers']['status']

#conn.connect()


r2 = conn.getresponse()

print r1,r2.status,r2.reason,r2
r3=r2.read()
print(r3)
r4=str(r3)
print r4
data = XML(r4).find("token").text
print data

# data1=urllib.quote_plus(data, safe=":")
# print data1
args=urllib.urlencode({'FEAUTH':data}).replace("%3A", ":")
print "args is", args
#args={}

req = conn.request("get","/rest-service/reviews-v1")
r3 = conn.getresponse()
status = r3.status
print "the url is"#, r3.getheader('Location')
url=r3.getheader('location', '')
print url
url1=r3.msg#.dict['location']
print url1
#print req.url
#print req.get_method()
print dir(req)  # list lots of other stuff in Request

print "after sending open review request"
print r3

print req,r3.status,r3.reason,r3
r4=r3.read()
print(r4)
r5=str(r4)
print r5
# json_ob=json.loads(r3.read())
# print json_ob

Solution

  • I was able to resolve the issue by

    1) removing the Content-Type from the headers and changed the accept to Accept(sentence cased).

    2) The login request was a get request and hence it supports data transfer by URL append, it is only for post request that we can pass an argument.