getChanges Sharepoint rest API - python

I am using Sharepoint 2013 REST api to find out the incremental changes that have happened in the root site. My request is like below:
headers = {"Authorization": 'Bearer ' + access_token, "accept": "application/json", "odata": "verbose"}
headers["content-type"] = "application/json;odata=verbose"
body = { 'query': { '__metadata': { 'type': 'SP.ChangeQuery' },'Web': True, 'Update': True, 'Add': True,
'ChangeTokenStart':{'__metadata':{'type':'SP.ChangeToken'},
'StringValue': '1;1;5b9752ee-f410-4cc6-9ab6-eb18c2ad802f;636252579049500000;89866182'}
}
}
In response I am getting lot of changerequest objects. One of them is as below:
{
'odata.type': 'SP.ChangeWeb',
'ChangeToken': {
'StringValue': '1;1;5b9752ee-f410-4cc6-9ab6-eb18c2ad802f;636252779425600000;89976872'
},
'WebId': '6e21eadd-4155-494d-9a8e-1046865bdd4b',
'ChangeType': 2,
'odata.id': 'https://<site url>/_api/SP.ChangeWeb87f1a9c6-937b-4507-973d-fc2d1b949aed',
'SiteId': '5b9752ee-f410-4cc6-9ab6-eb18c2ad802f',
'odata.editLink': 'SP.ChangeWeb87f1a9c6-937b-4507-973d-fc2d1b949aed',
'Time': '2017-03-16T16:19:02.56Z'
Can somebody help me understand the response? I am facing difficulty to find out the path where the change happened. Also, would this getchanges API capture changes that has happened in subsites within the site?

Yes Lists and Libraries at the end of the day are the same thing. You can get the list title from odata.editLink by stripping off the last segment (Items(1)) in the above case. If you call that path it'll give you the details of the list versus the item/file that was modified. If you want the user's details call /_api/Web/lists/getbytitle('User Information List')/Items(EditorId). If you want the path to the item/file call odata.editlink and the serverrelativeurl parameter returned will have the path to it and title will have the title of the item/file.

Sure, the ChangeType is the main piece of information you need which is an enumerable. You can look up the friendly names for the numbers here: ChangeType Enumeration
So in that case, that looks like an update to the settings of the SPWeb with a guid of '6e21eadd-4155-494d-9a8e-1046865bdd4b'
You may also want to look at using the $expand operator in your REST query to get additional fields back.

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

How to properly use POST in an API request for Earth Explorer

So first of all thanks, I'm really new to python and I am trying to understand APIs, I'm currently trying to log in into /inventory/json/v/1.4.1/<request_code>?jsonRequest=<json_request_content> which is the Earth Explorer API, and the first step is to Login, and according to the documentation I am supposed to use POST instead of GET, so here is what I got so far, and it works but this is what I
import requests
import requests
user = 'xxxxx'
psword = 'xxxxx'
input_data= {'username':user,'password':psword,'catalogId':'EE'}
test=requests.post('https://earthexplorer.usgs.gov/inventory/json/v/1.4.0/login?jsonRequest=input_data)')
print(test.text)
print(test.status_code)
{
"errorCode": "AUTH_ERROR",
"error": "Passing credentials via URL is not permitted - use a POST request",
"data": null,
"api_version": "",
"access_level": "guest",
"executionTime": 0
}
200
I have no idea what to do, thank you so much. This is the documentation for the earth explorer API, thank you so much https://earthexplorer.usgs.gov/inventory/documentation/json-api?version=1.4.1#login
I have encountered the same problem while working with Earth Explorer API and managed to solve it by reading usgs package code. Basically, the problem is that you must send the request body as a string. That is, your request body must look like this when printed
{
"jsonRequest": "{\"username\": \"???\", \"password\": \"???\", \"catalogId\": \"???\"}"
}
You can achieve this using
import json
import requests
req_params = {
'username': '???',
'password': '???',
'catalogId': '???',
}
req_txt = json.dumps(req_params)
req_body = {
'jsonRequest': req_txt,
}
resp = requests.post('<LOGIN URL HERE>', req_body)
This code is actually taken from usgs package I mentioned, so you should refer to it if you have any additional questions.

Magento 2 Rest API youtube video missing values

I have simple question regarding the Magento V1 media API. I'm trying to add a video to a product but it keeps telling me that is missing values.
I'm trying to add the data from Odoo (python) like this:
videoFile = {
"entry": {
'position': position,
'media_type': 'external-video',
'disabled': False,
'label': 'Holassss',
'types': ['image', 'small-image', 'thumbnail'],
'content': {
'base64_encoded_data': base64.b64encode(urllib.request.urlopen("https://img.youtube.com/vi/axwE9q7llEQ/0.jpg").read()).decode('ascii'),
'type': 'image/jpeg',
'name': '0.jpg'
},
'extension_attributes': {
'video_content': {
'media_type': 'external-video',
'video_provider': 'youtube',
'video_url': 'https://www.youtube.com/watch?v=axwE9q7llEQ',
'video_title': 'Titulo',
'video_description': 'Description',
'video_metadata': None,
}
}
}
}
cc = json.dumps(videoFile)
productUrl = url + "/index.php/rest/V1/products/" + productSku + "/media"
Eventually I'll add the content using the https://www.youtube.com/oembed?url=youtubeurl&format=json response.
I'm following the API documentation (http://devdocs.magento.com/swagger/index_20.html) for
catalogProductAttributeMediaGalleryManagementV1 (/V1/products/{sku}/media)
Error:
"message": "Option values that are not specified."
Please advice me on which values I'm missing and which I can leave NULL. Also let me know if there is a way to let Magento automatically get the description and other data (as on the admin panel) instead of providing it myself. last but not least, I think this documentation is missing some data. This already happened to me before with a different call and a couple of "optional" values were actually required. Is there another documentation web page?
Thank you very much.

400 Error while trying to POST to JIRA issue

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"
}
}

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;
}

Categories

Resources