400 Error while trying to POST to JIRA issue - python

I am trying to set the 'transition' property in a JIRA issue from whatever it is, to completed(which according to the doc is 10000). According to the documentation, this error is 'If there is no transition specified.'
Also I have used ?expand=transitions.fields to verify that 10000 is for complete.
using these docs
https://docs.atlassian.com/jira/REST/latest/#api/2/issue-doTransition
https://jira.atlassian.com/plugins/servlet/restbrowser#/resource/api-2-issue-issueidorkey-transitions/POST
Here is my request
url = 'http://MYURL/rest/api/2/issue/ISSUE-ID/transitions'
payload1 = open('data3.json', 'r').read()
payload = json.loads(payload1)
textFile = requests.post(url, auth=('username', 'password'), json=payload)
The contents on my data3.json file are
{
"transition": 10000
}
edit: I also changed my JSON to this and I get a 500 error
{
"transition": {
"id": "10000"
}
}
The error I get
{"errorMessages":["Can not instantiate value of type [simple type,classcom.atlassian.jira.rest.v2.issue.TransitionBean] from JSON integral number;no single-int-arg constructor/factory method (through reference chain:com.atlassian.jira.rest.v2.issue.IssueUpdateBean[\"transition\"])"]}400
I'm pretty confident that my issue is in my json file since I have used GET in the code above this snippit multiple times, but I could be wrong.
Possible cause - https://jira.atlassian.com/browse/JRA-32132

I believe the issue I was having was a process flow one. I cannot jump right from my issue being opened, to 'completed'. However, I can go from the issue being created to 'Done'.
{
"transition": {
"name": "Done",
"id": "151"
}
}
As this does what I need, I will use it. If I find how to make ticket complete I will post back.
Also, I think the fact we customize our JIRA lead to my getting 'Completed' as a valid transition even though it wasn't.

Yes, you're right that the JSON is wrong, it's not even a valid json since the value is not a number, string, object, or array. The doc says:
The fields that can be set on transtion, in either the fields
parameter or the update parameter can be determined using the
/rest/api/2/issue/{issueIdOrKey}/transitions?expand=transitions.fields
resource.
So you need to do a get request on /rest/api/2/issue/{issueIdOrKey}/transitions?expand=transitions.fields to get the list of possible values and then set that in the json
{
"transition": {
"id" : "an_id_from_response"
}
}

Related

How can I have only one api value?

everyone
I started programming in python yesterday to create a project. This consists of taking data from an API using the "Requests" library
So far I had no trouble getting familiar with the library, but I can't get results for what I'm specifically looking for.
My idea is just to get the name of the account.
Here the code
import requests
user = 'example'
payload = {'data': 'username'}
r = requests.get('https://api.imvu.com/user/user-'+user, params=payload)
json = r.json()
print(json)
My idea is that, within all the data that can be obtained, only obtain the name of the account. just the name
The code works perfectly, but it throws me all the account data.
For example:
{
"https://api.imvu.com/user/user-x?data=created": {
"data": {
"created": "2020-11-30T17:56:31Z",
"registered": "x",
"gender": "f",
"display_name": "‏‏‎ ‎",
"age": "None",
"country": "None",
"state": "None",
"avatar_image": "x",
"avatar_portrait_image": "https://......",
"is_vip": false,
"is_ap": true,
"is_creator": false,
"is_adult": true,
"is_ageverified": true,
"is_staff": false,
"is_greeter": false,
"greeter_score": 0,
"badge_level": 0,
"username": "=== ONLY THIS I NEED ==="
}
}
}
As you can see, I only need one thing from all that data.
Sorry for bothering and I hope I can learn from your answers. Thanks so much for reading
Unless API allows you to specify exactly what data to return (some does) then you got no control about the API behavior nor what data (and how) given endpoint returns. Publicly exposed API is all you can have in hand and sometimes you may get tons of useless data and there's basically nothing you can do about that.
To get specific item from json, you can simply make few changes in your code.
r = requests.get('https://api.imvu.com/user/user-'+user, params=payload)
json = r.json()
username = json["https://api.imvu.com/user/user-x?data=created"]["data"]["username"]
print(username)
you might check whether there is an alternative REST method that only provides you with the username.
The REST response you cannot modify as it is sent from the server, so you need to parse the response e.g. like here
Extract value from json response python?
python

Jira API : when using PUT call getting "no single-String constructor/factory method"

I was trying to update a custom field on a Jira ticket using Jira API, following this Jira Documentation. however, I am getting the below error.
{'errorMessages': ['Can not instantiate value of type [simple type, class com.atlassian.jira.rest.v2.issue.IssueUpdateBean] from JSON String; no single-String constructor/factory method']}
this is my code:
data = {'update': {'customfield_25305': [{'set': [{'value': '1c1a07d49af1b1cde8a1a7bd93cbbeef8efd50c9'}, {'value': 'c6f1e31ce0138cba658f769accaac729bebc42d6'}]}]}}
data = json.dumps(json.dumps(data)) #because the API accepts only strings enclosed in double quotes
upload = requests.put(url, headers=headers, data=data)
print(upload.json())
as per the documentation, I tried "/editmeta" the custom field I am trying to update is editable and has the following attributes.
{'required': False, 'schema': {'type': 'string', 'custom': 'com.atlassian.jira.plugin.system.customfieldtypes:textfield', 'customId': 25305}, 'name': 'Commit ID(s)', 'fieldId': 'customfield_25305', 'operations': ['set']}
Not sure what I am doing wrong here, any help would be appreciated!
Tried jira documentation
and searched through the Jira community none of the answers helped, everything points to malformed data but the data that I am passing is as per documentation.
the end result would be a 204 status code.
I think is a matter of single quotes.
As far as I remember, for valid JSON it should be double quotes.
{
"update": {
"customfield_25305": [{
"set": [{
"value": "1c1a07d49af1b1cde8a1a7bd93cbbeef8efd50c9"
}, {
"value": "c6f1e31ce0138cba658f769accaac729bebc42d6"
}]
}]
}
}
I use to do a online validator tool to my JSON strings when I got stuck.
E.g. https://jsonlint.com/ (first result on google)
I was able to resolve the issue, the proper formatting for data is as below:
{"fields": {"customfield_25305": "\"1c1a07d49af1b1cde8a1a7bd93cbbeef8efd50c9\", \"c6f1e31ce0138cba658f769accaac729bebc42d6\", \"1c1a07d49af1b1cde8a1a7bd93cbbeef8efd50c9\""}}

Azure TimeSeries API call issue python requests

I need help making a time series api call using python requests.
My header and body look like the following :
header = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
body = {
"getSeries": {
"timeSeriesId": idstring.split(','),
"searchSpan": {
"from": timefrom,
"to": timeto,
}
}
}
My request command is :
data = requests.post(f"https://{fqdn}/timeseries/query?api-version=2018-11-01-preview&storeType=warmstore",
headers=header,
data=body)
If i send the header and body as are, I get "Unexpected character encountered while parsing value: g. Path '', line 0, position 0.\r\n"
If i send them as body = json.dumps(json), there is no unexpected character problem, but I get the error message "'str' object has no attribute 'items'".
I have also tried a solution i found with a custom dictionary that has double quotes instead of the standard single but that didn't work either. Bit stumped as to what to do.
Can anyone help?
Thanks
I solved it. Very annoying as spent a good few hours googling random stuff trying to work it out. I even started implementing it in Julia!
Simple correction : json=body instead of data=body in the request call
data = requests.post(f"https://{fqdn}/timeseries/query?api-version=2018-11-01-preview&storeType=warmstore",
headers=header,
json=body)

Need Example of passing Jasper Reports Parameters for REST v2 API using JSON

When I look at the documentation for passing parameters to the Jasper Report REST 2 API here: http://community.jaspersoft.com/documentation/jasperreports-server-web-services-guide/v550/running-report-asynchronously I see that I need to have a "parameters" dict. The example in the link shows the XML which is not all that useful since it's unclear exactly what the equivalent JSON should look like. The closest I could find is in this link: http://community.jaspersoft.com/documentation/jasperreports-server-web-services-guide/v56/modifying-report-parameters. Now, I am sending the equivalent of that to the server (and every other permutation I can think of), and I continue to get a "400 Client Error: Bad Request" back. I could really use an exact example of the python code to generate the required "parameters" parameter for say "my_parameter_1="test_value_1".
Here is my current POST data (with a few params missing for brevity). I know this is correct since the report works fine if I omit the "parameters" parameter:
{
'outputFormat': 'pdf',
'parameters': [{'name': 'ReportID', 'value': ['my_value_1']}],
'async': 'true',
'pages': '',
'interactive': 'false'
}
Nice Job there Staggart. I got it now. Because I wasn't reading with max. scrutinity, I wasted some additional time. So the interested coder is not only advised to be aware of the nested, syntactictally interesting reportParameter-property, but especially that the value-property inside that is an array. I suppose one could pass some form of Lists/Arrays/Collections here?
What irritated me was, if I should construct more than one "reportParameter" property, but that would be nonsense according to
Does JSON syntax allow duplicate keys in an object.
So just for the record, how to post multiple parameters:
{
"reportUnitUri": "/reports/Top10/Top10Customers",
"async": true,
"freshData": true,
"saveDataSnapshot": false,
"outputFormat": "pdf",
"interactive": false,
"ignorePagination": true,
"parameters": {
"reportParameter": [
{
"name": "DATE_START_STRING",
"value": ["14.07.2014"]
},
{
"name": "DATE_END_STRING",
"value": ["14.10.2014"]
}
]
}
}
If someone accidently is struggling with communicating with jasper via REST and PHP. Do yourself a favour and use the Requests for PHP instead of pure CURL. It even has a fallback for internally using Sockets instead of CURL, when latter isn't available.
Upvote for you Staggart.
OK, thanks to rafkacz1 # http://community.jaspersoft.com/questions/825719/json-equivalent-xml-post-reportexecutions-rest-service who posted an answer, I figured it out. As he report there, the required format is:
"parameters":{
"reportParameter":[
{"name":"my_parameter_1","value":["my_value_1"]}
]
}
Pay particular attention to the plurality of "reportParameter".
Here is an example that worked for me. Im using Python 2.7, and the community edition of Jaspersoft. Like the C# example above, this example also uses the rest v2 which made it very simple for me to download a pdf report quickly
import requests
sess = requests.Session()
auth = ('username', 'password')
res = sess.get(url='http://your.jasper.domain:8080/jasperserver/', auth=auth)
res.raise_for_status()
url = 'http://your.jasper.domain:8080/jasperserver/rest_v2/reports/report_folder/sub_folder/report_name.pdf'
params = {'Month':'2', 'Year':'2017','Project': 'ProjectName'}
res = sess.get(url=url, params=params, stream=True)
res.raise_for_status()
path = '/path/to/Downloads/report_name.pdf'
with open(path, "wb") as f:
f.write(res.content)
Here's a full example about generate a report using Rest V2, in my case it's running on C#:
try {
var server = "http://localhost:8080/jasperserver";
var login = server + "/rest/login";
var report = "/rest_v2/reports/organization/Reports/report_name.pdf";
var client = new WebClient();
//Set the content type of the request
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
//Set the username and password
NameValueCollection parametros = new NameValueCollection();
parametros.Add("j_username", "jasperadmin");
parametros.Add("j_password", "123456");
//Request to login
client.UploadValues(login, "POST", parametros);
//Get session cookie
string session = client.ResponseHeaders.Get("Set-Cookie");
//Set session cookie to the next request
client.Headers.Add("Cookie", session);
//Generate report with parameters: "start" and "end"
var reporte = client.DownloadData(server + report + "?start=2015-10-01&end=2015-10-10");
//Returns the report as response
return File(reporte, "application/pdf", "test.pdf");
}catch(WebException e){
//return Content("There was a problem, status code: " + ((HttpWebResponse)e.Response).StatusCode);
return null;
}

Error while getting degree connection between two users

I am facing a problem while fetching degree connection between two LinkedIn users. I am sending a request at
https://api.linkedin.com/v1/people::(~,id=<other person's linkedin id>):(relation-to-viewer:(distance))?format=json&oauth2_access_token=<user's access token>.
Sometimes I get a correct response:
{
"_total": 2,
"values": [
{
"_key": "~",
"relationToViewer": {"distance": 0}
},
{
"_key": "id=x1XPVjdXkb",
"relationToViewer": {"distance": 2}
}
]
}
while most of the time I get an erroneous response:
{
"_total": 1,
"values": [{
"_key": "~",
"relationToViewer": {"distance": 0}
}]
}
I have gone through LinkdIn api's profile fields and I believe that I am using the api correctly. I am not sure what's wrong here. Please help.
After posting it on LinkedIn forum, I got the response
The behavior you're seeing where you only get yourself back from your
call falls in line with what I'd expect to see if the member ID you're
asking for isn't legitimate. If the member ID exists, but isn't in ~'s
network, you should get a -1 distance back, not nothing at all, as you
are seeing. However if you put in a completely invalid member ID, only
information about ~ will be returned from the call.
This was indeed the problem. The client on Android and the client on iOS had different API keys and both were using the same backend to access the degree connection. By using the same API key for both the clients resolved the issue.

Categories

Resources