Creating Jira issue with REST API - python

Having issues with trying to create an issue with Jira through the APIs, below is a sample of my code. We are using enterprise jira, I have to replace certain sections with so I hope it wont effect your ability to provide help.
from requests.auth import HTTPBasicAuth
import requests
user = '<ID>'
password = '<password>'
url = 'https://<enterprise>jira.<domain>.com/projects/<MYKEY>/rest/api/3/issue'
headers = {
'Content-Type': 'application/json',
}
json_data = {
"fields": {
"project": {
"key": "<MYKEY>"
},
"summary": "Creating From Collection",
"description": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"type": "text",
"text": "This is an autogenerated issue from a demo."
}
]
}
]
},
"issuetype": {
"name": "Task"
}
}
}
response = requests.post(
url,
headers=headers,
json=json_data,
verify=False,
auth=(user, password),
)
I get error code 405 and the following message when running print(response.text):
<!doctype html>HTTP Status 405 – Method Not Allowedbody {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}HTTP Status 405 – Method Not AllowedType Status ReportMessage HTTP method POST is not supported by this URLDescription The method received in the request-line is known by the origin server but not supported by the target resource.Apache Tomcat/8.5.78
Im sure I'm doing something wrong so any help will be appreciated.
Also I have verified I have the right access by manually going to the project and creating an issue.

Your URL is wrong. For creating a Jira issue you want to use the create issue endpoint.
For server/datacenter:
url = 'https://<enterprise>jira.<domain>.com/rest/api/2/issue'
For cloud:
url = 'https://<enterprise>jira.<domain>.com/rest/api/3/issue'
You need to use a POST request to either of these endpoints.

Related

Elastic search Api

Hey Stackoverflow fam,
I am working on an API which pulls requests from elastic search tool and displays it.
I am trying to pull data using get request
import requests
import json
payload = {
"query": {
"match": {
"metric": "metric_name"
}
}
}
url = "https://url_name:9200/siren-kinesis*/_search"
payload = json.dumps(payload)
print(type(payload))
headers = {
'Content-Type': 'application/json',
}
result = requests.get(url=url,data=payload,headers=headers,auth=("test#example.com","*"))
print(result.json())
and getting the following error
{
"error": {
"root_cause": [
{
"type": "security_exception",
"reason": "unable to authenticate user [test#example.com] for REST request [/_search]",
"header": {
"WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
}
}
],
"type": "security_exception",
"reason": "unable to authenticate user [test#example.com] for REST request [/_search]",
"header": {
"WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
}
},
"status": 401
}
I am Basic Auth .i.e. passing username and password for authorization.
Can somebody help me ?
In the case of Basic Auth in any request, if you're requesting via postman you can provide the credentials in the Authentication tab. But In the case of Code/Console/Browser, the certificates must be given in the request URL.
e.g.
https://username:password#URL
https://admin:admin#www.the-internet.herokuapp.com/basic_auth

Invalid Credentials Error when updating file to Google drive API

I have been trying to replace files using google API only with the Python HTTPS module. Can somebody please help me with how I can replace the file only with an HTTPS module?
import sys
import json
import requests
import sys
Acesstoken = ""
params = {
"grant_type": "refresh_token",
"client_id": "xxx",
"client_secret": "xxxx",
"refresh_token": "xxxx"
}
authorization_url = "https://www.googleapis.com/oauth2/v4/token"
r = requests.post(authorization_url, data=params)
if r.ok:
token = str((r.json()['access_token']))
Refreshtoken = Acesstoken + token
else:
print('Failed')
sys.exit()
headers = {
"Authorization": "Bearer " + str(Acesstoken),
}
metadataF= {
'name': "Test",
'parents':["1vXn346cBsarvkPthqtI1OLzsMzeQQlBX"]
}
files = {
'data':('metadata', json.dumps(metadataF), 'application/json; charset=UTF-8'),
'file': open("./credentials.json", "rb"),
}
r2= requests.post(
"https://www.googleapis.com/upload/drive/v3/files/XXXXXXXX?uploadType=multipart",
headers= headers,
files= files
)
print(r2)
I only want to use Python's Https Module only. I don't want to use google client library. Please help me if this is possible.
Error
<Response [401]> with this ` { "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" }
<Response [401]> with this ` { "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" }
Invalid Credentials means that your token has expired. Access tokens are only valid for an hour. Refresh tokens are only valid for seven days if your app is still in testing.
As documented here the error 401 error: Invalid credentials is related to:
... the access token you're using is either expired or invalid. This error can also be caused by missing authorization for the requested scopes ...
If the token works with another type of request you may want to check the scopes.

Python POST requests returns a "bad requests" when using a proxy

I have been testing things out using this proxy to scrape some Yelp pages. Things have been great but I had to use it for a POST request but I kept getting a 400 status code (Bad request). Here is the thing if I try it without the proxy I get the expected results.
Below is the code without using the proxy
import requests
import json
# Build a suitable JSON request for the required information
json_post = [
{
"operationName": "GetBusinessAttributes",
"variables": {
"BizEncId": "1IMivcKgsN8xUL5dFKQK3w"
},
"extensions": {
"documentId": "35e0950cee1029aa00eef5180adb55af33a0217c64f379d778083eb4d1c805e7"
}
},
{
"operationName": "GetBizPageProperties",
"variables": {
"BizEncId": "1IMivcKgsN8xUL5dFKQK3w"
},
"extensions": {
"documentId": "f06d155f02e55e7aadb01d6469e34d4bad301f14b6e0eba92a31e635694ebc21"
}
},
]
r = requests.post("https://www.yelp.com/gql/batch", json=json_post)
and here is the code with the proxy
import requests
import json
# Build a suitable JSON request for the required information
json_post = [
{
"operationName": "GetBusinessAttributes",
"variables": {
"BizEncId": "1IMivcKgsN8xUL5dFKQK3w"
},
"extensions": {
"documentId": "35e0950cee1029aa00eef5180adb55af33a0217c64f379d778083eb4d1c805e7"
}
},
{
"operationName": "GetBizPageProperties",
"variables": {
"BizEncId": "1IMivcKgsN8xUL5dFKQK3w"
},
"extensions": {
"documentId": "f06d155f02e55e7aadb01d6469e34d4bad301f14b6e0eba92a31e635694ebc21"
}
},
]
r = requests.post("http://api.proxiesapi.com/?auth_key=d325db3f85a49b0561aaa0dda5209b15_sr98766_ooPq87&url=https://www.yelp.com/gql/batch", json=json_post)
I've included the auth_key so you can try it out. I have a feeling the problem in how I am passing the json. Any help will be much appreciated.

Python flask API POST request - JSON data after key

I'm very new to development, I'm writing a Python Flask app which is executing a POST request to log a new ticket on a system, I just need someone to verify how I structure this request as I'm really not sure.
The documentation says, for example:
curl api/v3/requests
-X POST
-H "Accept: application/vnd.manageengine.sdp.v3+json"
-H "Authorization: Zoho-Oauthtoken 1000.7xxx98976ab0xxxxxx19901e7551be57.bxxxx921ed64c04f79622bebcfxxxxxx"
-H "Content-Type: application/x-www-form-urlencoded"
-d input_data= '{
"request": {
"subject": "Need an External Monitor",
"resolution": {
"add_to_linked_requests": false,
"content": "The following is the resolution to the above request"
}
}
It's expecting input_data key, followed by the JSON array of info to submit.
The documentation is (here)
My code:
#app.route("/log", methods=["GET"])
def log():
"""Fetching a protected resource using an OAuth 2 token.
"""
servicedesk = OAuth2Session(client_id, token=session['oauth_token'])
headers = {"Authorization": "Bearer " + token, "Accept": "application/vnd.manageengine.sdp.v3+json", "Content-Type": "application/x-www-form-urlencoded"}
data = {
"request": {
"subject": "New Incident",
"mode": {
"name": "E-Mail",
},
"group": {
"name": "Incident"
},
"requester": {
"name": "Sarah Curtis Test"
},
"status": {
"name": "Open",
},
"template": {
"name": "Report an Incident"
},
"request_type": {
"name": "Incident",
},
"description": "This is a test. please ignore",
"category": {
"name": "Incident"
}
}
}
requests.post('https://sdpondemand.manageengine.eu/api/v3/requests?input_data=', data=data, headers=headers)
I don't have access to logs on the server to see what it is receiving either as it's a cloud service (unless there's a way to echo back the original raw POST request?)
The ticket isn't being logged when I try and do so via my app. It does work through Postman app to test the API request, when I add the JSON above into the x-www-form-urlencoded section on the body tab and put input_data into the key.
I need to know how to structure the POST request in my code. Any help appreciated! Thanks

Microsoft Graph API Nest JSON Request is failed

I am developing App leveraging Microsoft Graph using Python 3.6.
I am getting very strange behavior when requesting Graph API which uses request data as nested JSON.
This is a successful request:
url = f "https://graph.microsoft.com/v1.0/users/{user_id}"
headers = {
'Authorization': f 'Bearer {office365_access_token}',
'Content-Type': 'application/json'
}
data = {
"city": "Tokyo"
}
req = urllib.request.Request(url, json.dumps(data).encode("utf-8"), headers = headers, method = 'PATCH')
urllib.request.urlopen(req)
The next snipped fails with an HTTP Error 400 error. The documentation states that the skills property is a String Collection, so I used an Array of String values:
url = f "https://graph.microsoft.com/v1.0/users/{user_principal_name}"
headers = {
'Authorization': f 'Bearer {office365_access_token}',
'Content-Type': 'application/json'
}
data = {
"skills": ["swift", "python"]
}
req = urllib.request.Request(url, json.dumps(data).encode("utf-8"), headers = headers, method = 'PATCH')
urllib.request.urlopen(req)
The only difference is whether the value is a string or not. I can dump the data dictionary to a JSON string, so I don't think the code is wrong but I do not know why this error occurres.
It appears to be a bug related with Microsoft Graph itself, specifically with User update operation. For example the following query:
PATCH https://graph.microsoft.com/v1.0/me
Content-type: application/json
{
"skills": [
"Fortran",
"Cobol"
],
"city": "Helsinki"
}
indeed fails and returns the following error:
{
"error": {
"code": "BadRequest",
"message": "The request is currently not supported on the targeted entity set"
}
}
At the same time updating another User properties, for example User.otherMails property which has the same Collection(Edm.String) type as User.skills:
PATCH https://graph.microsoft.com/v1.0/me
Content-type: application/json
{
"otherMails": [
"office365admin#gmail.com",
"office365admin#yahoo.com"
],
"city": "Helsinki"
}
completes successfully.
Workaround
It appears it fails when skills property of User resource is getting updated along with another properties. But if only a skills property is getting updated
PATCH https://graph.microsoft.com/v1.0/me
Content-type: application/json
{
"skills": [
"Fortran",
"Cobol",
"C"
]
}
no error occurs and the operation successfully completes.

Categories