Jira api to search all issues in Jira using python - python

I want to list/search all the issues in Jira. I have a code like :
url = 'https://company.com/rest/api/2/search'
auth = HTTPBasicAuth("username", "password") // I tries token as well
headers = {
'Accept': 'application/json'
}
query = {
'jql': 'project=PRKJECTKEY',
'startAt': 0
}
response = requests.request(
"GET",
url,
headers=headers,
auth=auth,
params=query
)
I am not sure if the password should be token or the actual password and the url should be should be starting from companyname.com. This gives me <Response [401]> but i have all the permissions with the account.
Can someone help me with the authentication is supposed to be used this way.

I can only describe my way of accessing the JIRA-API:
1. I am using an API-key for this which one can easily create online, if one has the necessary permissions
(https://developer.atlassian.com/cloud/jira/platform/basic-auth-for-rest-apis/)
2. You need to set up the Jira-object to query issues first
user = 'firstname.familyname#account.xx'
apikey = 'xxxxxxxxxxxxxxxxx'
server = 'https://companypage.atlassian.net'
options = {
'server': server
}
jira = JIRA(options, basic_auth=(user, apikey))
3. Now, you can use the Jira-object to query with
tickets = jira.search_issues('text ~ "my search text" ORDER BY updated DESC')
Now, you can look what you got back and play with the results
for ticket in tickets:
print(ticket)
For Packages, you only need to import JIRA at the top (obviously, need to install jira first):
from jira import JIRA

Well, why don't you use atlassian-python-api?
https://community.atlassian.com/t5/Jira-articles/Atlassian-Python-API-s/ba-p/2091355
It's much easier to work with Jira via their own library. I have been working with Confluence via this and it's pretty simple. Take a look it may solve your problem.
EDIT: here is documentation. https://atlassian-python-api.readthedocs.io/

Related

How to implement Auth0's Direct Password Change feature using Management API in Django?

I have a Django App, and I am trying to use Auth0 for my Django App's authentication. I have successfully integrated Login and Logout using social-auth-app-django library. But I am facing a lot of hurdles in implementing Auth0's Management API to use direct password change feature in Django? I tried to follow what this Auth0's official documentation's link says to implement Auth0's Management API for direct password change feature, but it is throwing Error Code 500, and I am not understanding what I did wrong.
The link shows the following example to implement Auth0 Management API for firect password change feature in Django:
import http.client
conn = http.client.HTTPSConnection("")
payload = "{\"password\": \"NEW_PASSWORD\",\"connection\": \"CONNECTION_NAME\"}"
headers = { 'content-type': "application/json" }
conn.request("PATCH", "/dev-9fj5kydc.us.auth0.com/api/v2/users/USER_ID", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
And my implementation for the same is:
import http.client
user = self.request.user
NEW_PASSWORD = form.cleaned_data["new_password1"]
CONNECTION_NAME = settings.AUTH0_CONNECTION_NAME
DOMAIN = settings.SOCIAL_AUTH_AUTH0_DOMAIN
USER_ID = user.auth0_id
URL = f"/{DOMAIN}/api/v2/users/{USER_ID}"
conn = http.client.HTTPSConnection("")
payload = f"{{\"password\": \"{NEW_PASSWORD}\",\"connection\": \"{CONNECTION_NAME}\"}}" # Here I am using 'Username-Password-Authentication' as Connection Name
headers = { 'content-type': "application/json" }
conn.request("PATCH", URL, payload, headers)
res = conn.getresponse()
data = res.read()
I have double checked that everything is fine by printing values in console and all variables hold correct values. Can someone help me and tell what wrong I am doing?

Import cucumber test result with XRay API using Python

I'm trying to perform an import of a cucumber test with the Xray API on Python, to be more specific I'm trying to translate this curl on Python side (it's a multipart form) :
curl -u usr:pass -F info=#$xrayResultFilePath -F result=#$pathToCucumberJson $jiraUrl/rest/raven/1.0/import/execution/cucumber/multipart
I tried in many different ways the python code I'm stucked on looks something like this:
response = requests.post(
atc_xray_url,
auth=(creds.username, creds.password),
files={"info": open("cucumber.result.json", "rb"),
"result": open("xray_result.json", "rb")},
)
response.raise_for_status()
I also tried to change the tags, to add them in a tuple like I found on the internet, solutions found here, but no result everytime I get this error:
<status><status-code>404</status-code><message>null for uri:
The curl is working, but the Python code is not. I could use the subprocess library but this shoud be a multiplatform solution so if this could be done with a thing in Python, it would be nice.
This repository that I made available some time ago provides several code snippets, including one precisely for that use case.
Your code is similar to the following one though; you may use basic auth or personal auth tokens, if you have a Jira DC version >= 8.14.
Given the result code you obtain, the problem may be on the URL that you use, which is not clear whether it's the same or not that you have on your curl. Note that you can also use v2 of the endpoint, as I show ahead.
import requests
import json
jira_base_url = "http://192.168.56.102"
jira_username = "admin"
jira_password = "admin"
personal_access_token = "OTE0ODc2NDE2NTgxOnrhigwOreFoyNIA9lXTZaOcgbNY"
...
files = {
'result': ('cucumber.json', open(r'cucumber.json', 'rb')),
'info': ('info.json', json.dumps(info_json) )
}
# importing results using HTTP basic authentication
# response = requests.post(f'{jira_base_url}/rest/raven/2.0/import/execution/cucumber/multipart', params=params, files=files, auth=(jira_username, jira_password))
# importing results using Personal Access Tokens
headers = {'Authorization': 'Bearer ' + personal_access_token}
response = requests.post(f'{jira_base_url}/rest/raven/2.0/import/execution/cucumber/multipart', files=files, headers=headers)

Accomplishing Oauth2.0 authorization with refresh token through Python (Google API service creation)

I'm trying to access Google API services through a headless Linux server using Oauth2. I read through all the answers on this post: How do I authorise an app (web or installed) without user intervention? but none of them showed how to use the refresh token to generate an access token in python. pinnoyyid had a javascript example (https://stackoverflow.com/a/19766913/15713034) that went something like this:
function get_access_token_using_saved_refresh_token() {
// from the oauth playgroundfunction get_access_token_using_saved_refresh_token() {
// from the oauth playground
const refresh_token = "1/0PvMAoF9GaJFqbNsLZQg-f9NXEljQclmRP4Gwfdo_0";
// from the API console
const client_id = "559798723558-amtjh114mvtpiqis80lkl3kdo4gfm5k.apps.googleusercontent.com";
// from the API console
const client_secret = "WnGC6KJ91H40mg6H9r1eF9L";
// from https://developers.google.com/identity/protocols/OAuth2WebServer#offline
const refresh_url = "https://www.googleapis.com/oauth2/v4/token";
let refresh_request = {
body:`grant_type=refresh_token&client_id=${encodeURIComponent(client_id)}&client_secret=${encodeURIComponent(client_secret)}& refresh_token=${encodeURIComponent(refresh_token)}`;,
method: "POST",
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
})
}
JavaScript isn't really my best language, but I could decipher they were sending a POST request to the google server. So I tried to recreate the request in Python with the requests package:
import requests
result = requests.post("https://www.googleapis.com/oauth2/v4/token", body={'grant_type':'refresh-token', 'client_id':client_id, 'client_secret':client_secret, 'refresh_token': refresh_token}, headers={'Content-Type': 'application/x-www-form-urlencoded'})
And when I look at result it shows it has a 200 status code (success) but when I try to examine the response, there's nothing easy to read and I can't parse the result in JSON to get the access token. The other approach I tried was to spin up a Flask server using Google's suggested code: https://developers.google.com/identity/protocols/oauth2/web-server#python_5 but that doesn't work either because when I try to return the credentials from one of the functions (object that contains the access code) that won't return JSON no matter what. I'd prefer the post request method since it is cleaner and uses less code. Thanks!
In Python, one approach is to use requests-oauthlib to perform the Backend Application Flow. This is useful when you don't have a front-end to redirect someone to, in order to approve fetching a token.
This website (https://community.atlassian.com/t5/Bitbucket-questions/Refresh-Tokens-using-Python-requests/qaq-p/1213162) says solution could be something like this:
import requests
auth = ("<consumer_id>", "<consumer_secret>")
params = {
"grant_type":"refresh_token",
"refresh_token":"<your_refresh_token_here>"
}
url = "https://www.googleapis.com/oauth2/v4/token"
ret = requests.post(url, auth=auth, data=params) #note data=params, not params=params
Since none of the solutions above worked, I had to finally just give up and use a service account.

How to fix my code to be able to create new repositories

I can't create new repositoies in bitbucket cloud with code below.
I'm able to delete repositiries (with change form 'post' to 'delete' requests method). When I'm using code below I've got http 400 which means according to api docs - If the input document was invalid, or if the caller lacks the privilege to create repositories under the targeted account.
import requests
username = 'user#mail.com'
password = 'password'
headers = {"Content-Type": 'application/json'}
auth = (username, password)
bb_base_url = f"https://api.bitbucket.org/2.0/repositories/username/reponame"
res = requests.post(bb_base_url, headers=headers, auth=auth)
print(res)
So would like to ask for help to refactor code in way I will be able to do two things

Amazon Alexa Proactive Events request in Python flask-ask

I am trying to make a request to the Proactive Events API by using the requests module of Python.
However I always receive a response that the scope is invalid.
Can anyone help? What am I doing wrong? My code looks like this:
#ask.launch
def launch():
content_type = "application/x-www-form-urlencoded;charset=utf-8"
client_id = "amzn1.application-oa2-client.6a48XXXXXXX408"
client_secret = "592XXXXxxxxxxx6"
scope = "alexa::proactive_events"
grant_type = "client_credentials"
data = {"grant_type": grant_type, "client_id": client_id, "client_secret": client_secret, "scope": scope}
r = requests.post("https://api.amazon.com/auth/O2/token", data=data, headers={"content-type": content_type})
speech = render_template("welcome")
reprompt = render_template("welcome_reprompt")
return question(speech).reprompt(reprompt)
That is the response I get:
{'error_description': 'The request has an invalid parameter : scope', 'error': 'invalid_scope'}
Since one of the reason you get the invalid scope is that you dont have the events included in your skill manifest I include some steps here. I found quite cumbersome to use the SMAPI to update the skill manifest so instead I used ask cli.
install ask-cli: get authorization code for your amazon acount. In my case the backend is not an AWS lambda function but an external web server
get the skill manifest in json format:
ask api get-skill -s "amzn1.ask.skill.ZZZYYYZZ" --stage development > skill.json
Add the notifications permission and the events elements to the manifest:
{
"name": "alexa::devices:all:notifications:write"
}
and
"events": {
"publications": [
{
"eventName": "AMAZON.AAABBBCC"
}
],
"endpoint": {
"uri": "https://XXXYYYZZ:443/whatevercontext"
}
}
update the manifest:
ask api update-skill -s "amzn1.ask.skill.ZZZYYYZZ" --stage development -f skill.json
enable the notifications in the alexa app for your specific skill
Now you should be able to get the token and next step is to send the notification to the device
Have you tried making the API call via any other method? I just tried that with Postman and it worked for me.
My Python's a bit rusty, but here's the self generated code from Postman for Python. May be this should help?
import http.client
conn = http.client.HTTPConnection("api,amazon,com")
payload = "grant_type=client_credentials&client_id=amzn1.application-oa2-client.whatever-value&client_secret=client-secret&scope=alexa%3A%3Aproactive_events&undefined="
headers = {
'Content-Type': "application/x-www-form-urlencoded"
}
conn.request("POST", "auth,O2,token", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
As Karthik asked previously have you tried the call via postman? I first suggest trying to via postman before you trying to code it.
If the issue still persists its most likely because you haven't included the necessary permissions required for Proactive Events in your Skill Manifest.
To add the necessary permissions to Skill Manifest you need to use the Skill Management API & ASK Cli.
Follow this section of the documentation and visit the links referenced there to correctly add the required permissions to your skill - https://developer.amazon.com/docs/smapi/proactive-events-api.html#onboard-smapi
Once you have successfully added the events and publications with a skill schema you should be able to successfully generate a token.
Please feel to ask if you want me to elaborate more on the exact steps.
Cheers!
This is what I have tried and it worked:
amazon_token_url = "https://api.amazon.com/auth/O2/token"
headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}
body = "grant_type=client_credentials&client_id=amzn1.application-oa2-client.XXXYYYZZ&client_secret=ZZZYYYXXX&scope=alexa::proactive_events"
log.debug("Sending token request with body: %s", body)
resp = requests.post(amazon_token_url, data=body, headers=headers)
resp_json = json.loads(resp.content.decode('utf-8'))
if (resp.status_code < 299) and (resp.status_code > 199):
log.debug("token received from Amazon")
log.debug("Content : %s", resp.content)
token = resp_json["access_token"]
return token

Categories