Attempting to create a wiki page on an Atlassian wiki. I previously was using a python script and this code worked no problem:
data = json.dumps({"type":"page", "data":"testData", "title":postTitle,"space":{"key":"EB"}, "body":{"storage":{"value": content,"representation":"storage"}}})
r = requests.post("https://estech.atlassian.net/wiki/rest/api/content/", data=data, headers=headers, auth=(confluenceLogin['username'], confluenceLogin['password']))
Now I'm trying to use the following grunt task configuration:
http: {
atlassianwiki: {
options: {
uri: atlassianURL + "/wiki/rest/api/content/",
headers: {"Content-Type": "application/json"},
auth: {
"user": confluencelogin,
"pass": confluencepass
},
method:"POST",
body: JSON.stringify(wikijson)
}
}
}
with wikijson looking like:
wikijson = {
"type": "page",
"data": "testData",
"title": "testtitle",
"space": {key:"EB"},
"body": {
"storage": {
"value": "<p>testing posting</p>",
"representation": "storage"
}
}
}
And I get the following error when this task runs:
Fatal error: 500 {"statusCode":500, "message":"java.io.EOFException: No content to map to Object due to end of input"}
Upon a bit of google-fu, I found that some people claim they fixed this by adding "--post302" to their curl command line. But I don't really know or understand how that applies here.
i was fighting with confluence REST API and in my case the problem was in content-type header, but you seem to have it already.
I didn't try to create new page but to update existing one
Confluence API seemed a little bit magic to me, so i just leave here all steps i had to make before it started working, maybe one of them will help you.
function composeRequest(method) {
var auth = new Buffer(user + ':' + pass).toString('base64');
var request = {
host: 'confluence.myserver.com',
port: 443,
contentType: "application/json; charset=utf-8",
'path': path,
method: method || "GET",
headers: {
'Authorization': 'Basic ' + auth,
'Content-Type': 'application/json'
},
rejectUnauthorized: false,
requestCert: true,
agent: false
};
return request;
}
And it appeared that page update request JSON MUST contain
pageId (even it is inside path, you need to repeat it)
type
title
version (it's weird, but you should set it. 0 or 1, i don't remember)
And when your data if filled, you should convert it to string and fill content-type field in your request!
data = JSON.stringify(data);
request.headers['Content-Length'] = data.length;
https.request(request, respondHandler)
Related
I'm using axios to perform get and post requests to an external api,
i have finally succeed to achieve get request (problem with the ssl certificate, i avoid it by adding this :
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
now i would like to post the api,
to get the request working in postman, i put in
headers content-type : application/json
and in the body : {}
like here
when trying with a google chrome extention, to make it work, i put nothing in the headers but in params, i select customer : application/json and i put inside this {} instead of the default choice which is x-www-form-urlencoded;charset=UTF-8
chrome extention
in my javascript app i tried this
var url = https://10.11.31.100:9440/api/nutanix/v3/images/list;
axios({
method:'post',
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
url,
auth: {
username: '******',
password: '********'
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
},
params: {},
data: {}
})
.then(function (response) {
res.send(JSON.stringify(response.data));
console.log(response);
})
.catch(function (error) {
console.log(error);
});
I get this problem :
TypeError : UTF-8 is not a function
Specifically with regards to the Nutanix v3 REST API - this is probably because the POST request above doesn't have an appropriate JSON payload i.e. the "data" parameter is empty.
When sending Nutanix v3 API POST requests, specifically to "list" entities, you'll need to specify the "kind" of entity being listed. In your example, the JSON payload below will work.
{"kind":"image"}
See here: https://nutanix.dev/reference/prism_central/v3/api/images/postimageslist
HTH. :)
What I'm trying to do is use the OctoPrint Rest API. I keep running into an error though when I'm trying to do POST requests that require a command. Here's an example of that in the docs.
POST /api/connection HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "connect",
"port": "/dev/ttyACM0",
"baudrate": 115200,
"printerProfile": "my_printer_profile",
"save": true,
"autoconnect": true
}
What I'm most confused about is where I include the command or the port values. Here's what I'm currently doing.
var self = this;
request({
url: OCTOIP + "/api/connection",
method: "POST",
"content-type": "application/json",
headers: {
"X-Api-Key": KEY
},
body: JSON.stringify({"command": "connect"})
}, function(error, response, body) {
//var info = JSON.parse(body);
if (error) {
console.log(error);
self.tell("Could Not Connect");
}
else {
console.log(body);
self.tell("Connected to printer.");
}
});
What happens is I keep getting this error message.
Expected content-type JSON
I've tried changing content-type to just json, I've tried getting rid of the JSON.stringify and just putting it as {"command": "connect"}. Or even dropping the curly brackets altogether. Another thing I tried was using form and instead of the body. None of those have worked. What am I doing wrong here?
Fixed the issue. It turns out it wasn't working because I didn't put the content-type in the header.
I'm trying to hit one of the mailchimp's api, but for somehow I always get
{
"type": "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
"title": "Resource Not Found",
"status": 404,
"detail": "The requested resource could not be found.",
"instance": ""
}
I'm using request library to make the request and see the code below
var uniqueListId = "XXXX";
var apiKey = "XXX";
.post(function(req, res) {
var email = req.body.email;
var status = "subscribed";
request({
url: 'https://usX.api.mailchimp.com/3.0/lists/' + uniqueListId + '/members',
headers: {
'Authorization': 'randomUser ' + apiKey,
'Content-Type': 'application/json',
},
method: 'POST',
json: {
email_address: email,
status: status
}
}, function(err, response, body) {
if (err) {
res.json(err);
} else {
res.json(response.statusCode, body);
}
});
});
For the sake of clarity, this is the documentation that I'm referring to http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/
Is it because of my req.body data?
I agree with #TooMuchPete, The same issue happened with me and scratched my head for a whole day to solve that issue, and finally, I've found that Audience Idlist_id is wrong.
we need to pick the one which is located under the AudienceTab > ViewContacts > Settings > Audience and Defaults > Audience ID, but unfortunately, I have picked the one which is showing in the URL.
If you're getting a 404 it's because the URL you're hitting doesn't refer to an actual resource. Probably uniqueListId is either empty or not the right ID.
I would suggest using the Postman chrome add-on app to play with the requests and posts - you could also use it to generate sample code, in most languages. It is great for debugging.
After using it, I found that your request options should look something like:
let requestOptions = {
hostname: 'us14.api.mailchimp.com',
method: 'GET',
path: '/3.0/lists' + listId,
headers: {
'Authorization': 'User ' + config.mailChimp.apiKey,
'Content-Type': 'application/json',
},
}
You're almost certainly confusing mailchimp's web_id with list_id. The list_id is the one you need for the API, the web_id is the one you see in the url when you open your list.
I have absolutely no idea why mailchimp uses 2 different ids, nor why they don't seem to put it forward in any of their developer documentation.
Below is an article which explains how to find it - basically you go to your list -> settings tab -> list name and defaults.
https://3by400.com/get-support/3by400-knowledgebase?view=kb&kbartid=6
I'm using NodeJS to call the new MailChimp 3.0 API in order to add an email to a list. While I can get it working via POSTman, I'm having a hard time with Node's http:
var http = require('http');
var subscriber = JSON.stringify({
"email_address": "test#test.com",
"status": "subscribed",
"merge_fields": {
"FNAME": "Tester",
"LNAME": "Testerson"
}
});
var options = {
host: 'https://us11.api.mailchimp.com',
path: '/3.0/lists/<myListID>/members',
method: 'POST',
headers: {
'Authorization': 'randomUser myApiKey',
'Content-Type': 'application/json',
'Content-Length': subscriber.length
}
}
var hreq = http.request(options, function (hres) {
console.log('STATUS CODE: ' + hres.statusCode);
console.log('HEADERS: ' + JSON.stringify(hres.headers));
hres.setEncoding('utf8');
hres.on('data', function (chunk) {
console.log('\n\n===========CHUNK===============')
console.log(chunk);
res.send(chunk);
});
hres.on('end', function(res) {
console.log('\n\n=========RESPONSE END===============');
});
hres.on('error', function (e) {
console.log('ERROR: ' + e.message);
});
});
hreq.write(subscriber);
hreq.end();
Rather than getting even some sort of JSON error from Mailchimp, however, I'm getting HTML:
400 Bad Request
400 Bad Request
nginx
Is it clear at all what I"m doing wrong here? It seems pretty simple, yet nothing I've tried seems to work.
A few additional thoughts:
While http's options have an "auth" property, I'm using the headers instead to ensure the authorization is sent without the encoding (as mentioned here). Still, I've also tried with the "auth" property, and I get the same result.
I'm actually making this call from inside an ExpressJS API (my client calls the Express API, that calls the above code - I've edited all that out of this example for simplicity). That's why my variables are "hres" and "hreq", to distinguish them from the "res" and "req" in Express. Is there any reason that could be the issue?
As mentioned above, I am able to get successful results when using POSTman, so I at least know my host, path, list ID, and API key are correct.
It turns out this had a very simple solution: the "host" property of the options object needed to have only the domain name. IE, remove the "https://" protocol:
var options = {
host: 'us11.api.mailchimp.com',
path: '/3.0/lists/<myListID>/members',
method: 'POST',
headers: {
'Authorization': 'randomUser myApiKey',
'Content-Type': 'application/json',
'Content-Length': subscriber.length
}
}
Try this , its working fine for Me.
var request = require('request');
function mailchimpAddListCall(email, cb){
var subscriber = JSON.stringify({
"email_address": email,
"status": "subscribed"
});
request({
method: 'POST',
url: 'https://us13.api.mailchimp.com/3.0/lists/<Your list id>/members',
body: subscriber,
headers:
{
Authorization: 'apikey <your Mailchimp API key>',
'Content-Type': 'application/json'
}
},
function(error, response, body){
if(error) {
cb(err, null)
} else {
var bodyObj = JSON.parse(body);
console.log(bodyObj.status);
if(bodyObj.status === 400){
cb(bodyObj.detail, null);
}
var bodyObj = JSON.parse(body);
cb(null, bodyObj.email_address +" added to list.");
}
});
}
request is a node module, that you'll need to install into your package.json. npm install --save request
You can use the auth properties just fine with API v3, but if you're getting a 400, that's not the problem. The body of the 400 Error should provide more detailed information, but one thing that jumps out immediately: MailChimp doesn't allow fake or fake-looking emails to be added to lists (like test#test.com), so I'd try a real address and see if that works for you.
Can anyone explain or point me to a link with samples of doing Update, Delete using Jquery with the SharePoint 2010 Rest API?
I have the insert working and of course queries since the MSDN documentation explains and every tutorial on the net explains queries but just wondering if anyone ever inserts, updates, deletes data instead of only samples and tutorials on querying? Yes I know I can use the CSOM but I want to learn how this is done via jquery and sharepoint rest?
Also I want to use Merge for updating.
Here's the working insert code:
function insertMilestone() {
var mileStonesListUrl = "/_vti_bin/listdata.svc/Milestones";
var milestone = {};
milestone.Title = "Testing from REST";
var entry = JSON.stringify(milestone);
$.ajax({
type: "POST",
url: mileStonesListUrl,
data: entry,
contentType: "application/json; charset=utf-8",
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText);
},
success: function () {
getAll();
}
});
}
How to perform CRUD operations using SharePoint 2010 REST Interface
Create
In order to perform a Create operation via REST, you must perform the following actions:
Create an HTTP request using the POST verb.
Use the service URL of the list to which you want to add an entity as
the target for the POST.
Set the content type to application/json.
Serialize the JSON objects that represent your new list items as a
string, and add this value to the request body
JavaScript example:
function createListItem(webUrl,listName, itemProperties, success, failure) {
$.ajax({
url: webUrl + "/_vti_bin/listdata.svc/" + listName,
type: "POST",
processData: false,
contentType: "application/json;odata=verbose",
data: JSON.stringify(itemProperties),
headers: {
"Accept": "application/json;odata=verbose"
},
success: function (data) {
success(data.d);
},
error: function (data) {
failure(data.responseJSON.error);
}
});
}
Usage
var taskProperties = {
'TaskName': 'Order Approval',
'AssignedToId': 12
};
createListItem('https://contoso.sharepoint.com/project/','Tasks',taskProperties,function(task){
console.log('Task' + task.TaskName + ' has been created');
},
function(error){
console.log(JSON.stringify(error));
}
);
Read
In order to perform a Read operation via REST, you must perform the following actions:
Create an HTTP request using the GET verb.
Use the service URL of the list item to which you want to add an
entity as the target for the GET.
Set the content type to application/json.
JavaScript example:
function getListItemById(webUrl,listName, itemId, success, failure) {
var url = webUrl + "/_vti_bin/listdata.svc/" + listName + "(" + itemId + ")";
$.ajax({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data.d);
},
error: function (data) {
failure(data.responseJSON.error);
}
});
}
Usage
getListItemById('https://contoso.sharepoint.com/project/','Tasks',2,function(taskItem){
console.log(taskItem.TaskName);
},
function(error){
console.log(JSON.stringify(error));
}
);
Update
To update an existing entity, you must perform the following actions:
Create an HTTP request using the POST verb.
Add an X-HTTP-Method header with a value of MERGE.
Use the service URL of the list item you want to update as the target
for the POST
Add an If-Match header with a value of the entity’s original ETag.
JavaScript example:
function updateListItem(webUrl,listName,itemId,itemProperties,success, failure)
{
getListItemById(webUrl,listName,itemId,function(item){
$.ajax({
type: 'POST',
url: item.__metadata.uri,
contentType: 'application/json',
processData: false,
headers: {
"Accept": "application/json;odata=verbose",
"X-HTTP-Method": "MERGE",
"If-Match": item.__metadata.etag
},
data: Sys.Serialization.JavaScriptSerializer.serialize(itemProperties),
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
},
function(error){
failure(error);
});
}
Usage
var taskProperties = {
'TaskName': 'Approval',
'AssignedToId': 12
};
updateListItem('https://contoso.sharepoint.com/project/','Tasks',2,taskProperties,function(item){
console.log('Task has been updated');
},
function(error){
console.log(JSON.stringify(error));
}
);
Delete
To delete an entity, you must perform the following actions:
Create an HTTP request using the POST verb.
Add an X-HTTP-Method header with a value of DELETE.
Use the service URL of the list item you want to update as the target
for the POST
Add an If-Match header with a value of the entity’s original ETag.
JavaScript example:
function deleteListItem(webUrl, listName, itemId, success, failure) {
getListItemById(webUrl,listName,itemId,function(item){
$.ajax({
url: item.__metadata.uri,
type: "POST",
headers: {
"Accept": "application/json;odata=verbose",
"X-Http-Method": "DELETE",
"If-Match": item.__metadata.etag
},
success: function (data) {
success();
},
error: function (data) {
failure(data.responseJSON.error);
}
});
},
function (error) {
failure(error);
});
}
Usage
deleteListItem('https://contoso.sharepoint.com/project/','Tasks',3,function(){
console.log('Task has been deleted');
},
function(error){
console.log(JSON.stringify(error));
}
);
Please follow List Items manipulation via REST API in SharePoint 2010 article for a more details.
Here is the update and delete, it wasn't as hard as I thought it was going to be and it works.
Hopefully this will help someone out because there is so much bogus information on using the REST API and I see a zillion posts on querying but none on Insert, Update, Delete.
//update
function updateMilestone(id) {
var mileStonesUrl = "/_vti_bin/listdata.svc/Milestones";
mileStonesUrl = mileStonesUrl + "(" + id+ ")";
var beforeSendFunction;
var milestoneModifications = {};
milestoneModifications.Title = "Updated from REST";
var updatedMilestoneData = JSON.stringify(milestoneModifications);
//update exsiting milestone
beforeSendFunction = function (xhr) {
xhr.setRequestHeader("If-Match", "*");
// Using MERGE so that the entire entity doesn't need to be sent over the wire.
xhr.setRequestHeader("X-HTTP-Method", 'MERGE');
}
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
processData: false,
beforeSend: beforeSendFunction,
url: mileStonesUrl,
data: updatedMilestoneData,
dataType: "json",
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText);
},
success: function () {
alert("Updated");
getAll();
}
});
function deleteMilestone(id) {
var mileStonesUrl = "/_vti_bin/listdata.svc/Milestones";
mileStonesUrl = mileStonesUrl + "(" + id+ ")";
$.ajax({
type: "DELETE",
contentType: "application/json; charset=utf-8",
processData: false,
url: mileStonesUrl,
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText);
},
success: function () {
alert("deleted");
getAll();
}
});
}
}
I recently worked with the REST API for SP 2013, as a Example POC that can be used for any call implementation i.e. JQuery, C# etc.
Using POSTMAN
First get your digest token:
A method was found on this site : http://tech.bool.se/basic-rest-request-sharepoint-using-postman/
[Credit where credit is due]
POST
http://<SharePoint Domain Url>/sites/<Site name>/_api/contextinfo
Header:
Accept : application/json;odata=verbose
Body:
Clear the body
From the payload use "FormDigestValue" value and put it into your headers with the key : X-RequestDigest when making actions that alter items in SharePoint.
Reading data:
GET
http://<SharePoint Domain Url>/sites/<Site name>/_api/web/getfolderbyserverrelativeurl('/Sites/<Site Name>/Shared Documents/My Folder')/files?$select=Name
Headers:
Accept : application/json;odata=verbose
When it comes to create, update , delete you need the digest token or an authorization token to perform these actions, this token is highlighted at the begining to to retrieve.
Creating Data
POST
http://<SharePoint Domain Url>/sites/<Site Name>/_api/web/folders
Headers:
Accept : application/json;odata=verbose
X-RequestDigest : 'GUID looking toking'
Content-Type : application/json;odata=verbose
Body:
{ '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '/Sites/<Site Name>/Shared Documents/Some Folder/POC3'}
Note:
'ServerRelativeUrl' the folder on the end POC3 is the folder that I want to create
Related resources:
http://msdn.microsoft.com/en-us/library/office/fp142380(v=office.15).aspx
Note: PostMan was used for this example and other application may need you to url encode the endpoint.
The above Request Structure can be used for all requests, the related resource highlights some of the standard methods that can be used with the REST Api