Support

Expand all | Collapse all

How to upload attachments via REST API -- a step-by-step python script.

Jump to Best Answer
  • 1.  How to upload attachments via REST API -- a step-by-step python script.

    Posted 02-01-2017 15:16
    Sorry for the duplicate post but wanted to create a new thread to make this easier to find by anyone else who might be struggling with the rest API -- but then again, maybe I'm the only one!

    After spending considerable time and effort to figure out how to upload attachments based on limited

    documentation and code examples, I finally got the process to work today. 

    This solution is an amalgamation of using Postman code (Steps 1 and 4) and a python snippet that was posted here in the developer's forum (Step 3). 

    It is my hope that this helps others out there who are relatively new to Jama, Python, and JSON and are struggling to get this to work.

    Disclaimers

        1.  All source code and comments contained here are used at your own risk

        2.  I will attempt to answer questions if you have them but can not guarantee I know the right answer!

        3.  I'm new to python, JSON, and Jama so if this code seems inelegant or ugly, feel free to improve as you see fit.


    There is no error checking here or any attempt to use in a general solution... it is simply to demonstrate as clearly and completely as possible how to use the API calls in a python script to upload a file attachment and associate it with a specific test run.





    # Step 1

    import requests

    import re

    #Change the following variables to reflect your instance

    company_name ='your_company_name'

    # to find the api-id for your project, look at the URL for your instance.  It will be the number right after the word "projects"

    # for example:  https://your_company_name.jamacloud.com/perspective.req#/projects/35/dashboard

    project_api_id = '35'

    # api_id_for_test_run can be found by going to the testPlan perspective and viewing by Test Runs

    # make sure to configure the view to show the API ID for each test case within the Test Plan

    api_id_for_testrun = '12345'

    #----------------------------------------------------------------------------------

    # Step 1:  Generate the hook to hold the attachment item.

    # NOTE:  there are a couple of ways to do authorization and will depend on your preferences

    url = "https://" + company_name + ".jamacloud.com/rest/latest/projects/34/attachments"

    payload = "{\"fields\": {\"name\":\"kitty\"}}"

    headers = {

        'content-type': "application/json",

        'authorization': "***************",

        'cache-control': "no-cache"

        }

    response = requests.request("POST", url, data=payload, headers=headers)

    # Step 2:

    # extract the api_id from the response

    endpoint = response.text.split(":")

    api_id = re.findall('\d+', endpoint[-1])

    print api_id[-1]

    # Step 3:  Upload a file and associate with the API-ID from previous Step.

    url = "https://" + company_name + "jamacloud.com/rest/latest/attachments/" + api_id[-1] + "/file"

    print url

    files={'file':open('/Path/to_your/attachment.jpg','rb')}

    response=requests.put(url,auth=('*******','*******'),files=files)

    # Step 4:  Associate the new attachment with a test run

    url = "https://" + company_name + ".jamacloud.com/rest/latest/testruns/" + api_id_for_testrun + "/attachments"

    payload = "{\"attachment\":" + api_id[-1] + "}"

    headers = {

        'authorization': "***************",

        'content-type': "application/json",

        'cache-control': "no-cache"

        }

    response = requests.request("POST", url, data=payload, headers=headers)

    print(response.text)



    ------------------------------
    Nancy

    ------------------------------


  • 2.  RE: How to upload attachments via REST API -- a step-by-step python script.

    Posted 02-03-2017 09:27
    Thanks for sharing Nancy!

    ------------------------------
    Preston
    Jama Software
    ------------------------------



  • 3.  RE: How to upload attachments via REST API -- a step-by-step python script.

    Posted 03-01-2017 03:11
    Hi Nancy,

    I am new to REST Api , what is the field format of  'authorization': "***************", I mean how to feed usedname and password.

    Cheers
    Sharan


    ------------------------------
    sharan Patil
    Sensata Technologies (Schrader)
    ------------------------------



  • 4.  RE: How to upload attachments via REST API -- a step-by-step python script.

    Posted 03-01-2017 06:42
    in my java code I do


    // encode the userid/pw for basic auth
    Base64 b= new Base64();
    // get the userid and password strings, separated by ':'  (per the basic auth doc)
    String uidandpw=(operations.getOptionValue("u")+":"+ operations.getOptionValue("p"));
    // base 64 encode that string
    encoding = b.encodeAsString(uidandpw.getBytes());

    then in the http request  set the authorization header, with the text of the encoded string

    String x="Basic " + encoding.toString();
    o.setHeader("Authorization", x);

    ------------------------------
    Sam
    ------------------------------



  • 5.  RE: How to upload attachments via REST API -- a step-by-step python script.
    Best Answer

    Posted 03-02-2017 07:53
    HI Sharan,
    I used Postman in order to the code snippets for this solution.  Preston Mitchell — our Jama representative created a couple of training videos that walk you through how to get the code snippets for a REST API call.  
    Once you do that, the authorization format is provided to you directly and you can copy and paste that in to the code.  Postman will provide show you the code (and the corresponding encrypted authorization string) in at over 14 language variants including Python, C, Java, JavaScript, Ruby, and PHP.  So more than likely, Postman will be able to provide you with the information you need in any language you might need it in.  

    Postman code snippets do add a few lines that are unnecessary but it is a very good way to help you get started with how to create the code.
    In case you want/need a crash course on Postman, here are the links to Preston's videos…. I found them to be quite helpful.
    Hope this helps.
    Nancy


    ------------------------------
    Nancy
    UltraLinq
    ------------------------------



  • 6.  RE: How to upload attachments via REST API -- a step-by-step python script.

    Posted 03-03-2017 00:50
    Edited by sharan Patil 03-06-2017 00:57
    Thank you Nancy, I will look into it .. I modified your script as below it is working .. I will look into  authorisation related format

    cheers
    Sharan

    import requests
    import re


    # Enter Project ID
    project_api_id = '***'



    ImageFile ="C:\\Users\\....\\DX_deliver.PNG"

    UserName= "***"
    Password="**"

    #----------------------------------------------------------------------------------
    url = "https://Comanyname.jamacloud.com/rest/latest/projects/175/attachments"
    payload = "{\"fields\": { \"name\": \"covisint3.PNG\"}}" #{\"fields\": { \"name\": \"covisint2.PNG\
    headers = {
    'content-type': "application/json"
    }
    response=requests.post(url, data=payload, auth=(UserName,Password), headers=headers)

    # extract the api_id from the response
    endpoint = response.text.split(":")
    api_id = re.findall('\d+', endpoint[-1])
    #print "rsponse data: {} ".format(endpoint)
    #print api_id[-1]

    url = "https://company_name/rest/latest/attachments/" + api_id[-1] + "/file"

    #print url



    files={'file':open(ImageFile,'rb')}
    response=requests.put(url,auth=('***','***'),files=files)


    url = "https://comanynamet.jamacloud.com/rest/latest/testruns/" + api_id_for_testrun + "/attachments"
    payload = "{\"attachment\":" + api_id[-1] + "}"


    headers = {
    'content-type': "application/json",
    'cache-control': "no-cache"
    }
    response=requests.post(url, data=payload, auth=('8888', '8888'), headers=headers)

    print(response.text)

    if __name__ == "__main__":

    print "Uploading ".format(sys.argv[0])
    TestCase= sys.argv[1] #'test case'
    TestCycle= sys.argv[2]#'testCycle2'
    result = sys.argv[3] # result
    TestCycleId = getTestCycleId(TestCycle)
    api_id_for_testrun = getTestCaseId(TestCycleId,TestCase)
    print "Test case id is {}".format(TestCaseId)
    item_id = TestCaseId

    ------------------------------
    sharan Patil
    Sensata Technologies (Schrader)
    ------------------------------



  • 7.  RE: How to upload attachments via REST API -- a step-by-step python script.

    Posted 03-03-2017 07:34
    Very cool!  Much cleaner!

    Thanks for sharing!

    Cheers...

    Nancy

    ------------------------------
    Nancy
    UltraLinq
    ------------------------------



  • 8.  RE: How to upload attachments via REST API -- a step-by-step python script.

    Posted 03-03-2017 00:42
    Thank You Sam

    ------------------------------
    sharan Patil
    Sensata Technologies (Schrader)
    ------------------------------



  • 9.  RE: How to upload attachments via REST API -- a step-by-step python script.

    Posted 03-03-2017 07:39
    I posted the code the other day. You have to pass an Authorization http header

    ------------------------------
    Sam
    ------------------------------



  • 10.  RE: How to upload attachments via REST API -- a step-by-step python script.

    Posted 03-06-2017 06:14
    Hi Sam/Nancy

    Is there any way to hide the Username/ password or encrypt it. Is Authorization http header   method allows to do so.

    Cheers
    Sharan

    ------------------------------
    sharan Patil
    Sensata Technologies (Schrader)
    ------------------------------



  • 11.  RE: How to upload attachments via REST API -- a step-by-step python script.

    Posted 03-06-2017 06:26

    Well, you cannot encrypt.  You base64 encode it.  The rest protocol does not provide any other mechanism. And all the request are stateless, so auth has to be done on each request

     

    Sam