Search code examples
pythonjirajira-rest-api

How to use credentials when using API to fetch custom field Id


I'm a newbie and I am still in the learning phase.

Environment: JIRA Server.

I tried writing this simple program to fetch custom field ID using Python.

Code :

import requests


def custom_fields():
    response = requests.get("https://"JIRA URL"/rest/api/2/field")

#  # To test the response is working you need to get an output : 200
# print(response)
#
# # This will give you the output in String
# print(response.text)
# print(type(response.text))
#
# If you want to get the output in JSON format then try the
# following which will give you the output in list format.
#
# print (response.json())
# print(type(response.json()))

my_fields = response.json()

for field in my_fields:
    print(" Field Name :  {} Field Id : {}".format(field['name'], field['id']))


custom_fields()

and getting an sample output as:

Field Name : Key Field Id : issuekey
Field Name : Time Spent Field Id : timespent
Field Name : Original Estimate Field Id : timeoriginalestimate
Field Name : Project Field Id : project
Field Name : Σ Time Spent Field Id : aggregatetimespent

I believe this is because I am not using credentials to authenticate in the code. I tried following the link:
https://developer.atlassian.com/server/jira/platform/basic-authentication/
and tried updating the variable as:

response = requests.get ("curl -u username:password -X GET -H 'Content-Type: application/json' https://"JIRA URL"/rest/api/2/field")

and getting an error:

"No connection adapters were found for {!r}".format(url))
requests.exceptions.InvalidSchema: No connection adapters were found for "curl -u username:password -X GET -H 'Content-Type: application/json' https://"JIR URL"rest/api/2/field"

Could you please guide me.


Solution

  • Yes, you're absolutely right. You've missed the authentication to send a request to the API endpoint.

    It can be done in two ways:

    • Using Basic Auth
    headers = {
          'Authorization': '<Basic Auth Token>',
          'Content-Type': 'application/json',
    }
    response = requests.request("GET", JIRA_ENDPOINT, headers=headers)
    
    
    • Using JIRA-Token-Based Authentication
    auth = HTTPBasicAuth("demo_email@demo.com", "<JIRA_api_token>")
    
    headers = {
       "Accept": "application/json"
    }
    
    response = requests.request(
       "GET",
       url,
       headers=headers,
       auth=auth
    )
    

    For more details, you can always refer to their documentation