How to create folders on SharePoint 2019 using REST calls via postman? Getting 403: Forbidden error - rest

I am using the below call to create a folder on SharePoint2019:
POST http://<site>/_api/web/folders
{
"__metadata": {
"type": "SP.Folder"
},
"ServerRelativeUrl": "/Shared Documents/Folder"
}
But I am getting the following error:
403 Forbidden: The security validation for this page is invalid and might be corrupted. Please use your web browser's Back button to try your operation again.

Please check if you have got the valid form digest value in your side.
For example, if the site url is http://sp/sites/dev/
Then do a Post Request to this url http://sp/sites/dev/_api/contextinfo
Then use this form digest value in Request Header:
Here is a sample request to create folder using Rest:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});
function bindButtonClick() {
$("#btnSubmit").on("click", function () {
createFolder();
});
}
function createFolder() {
var folderName = $("#txtFolderName").val();
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/_api/web/folders";
$.ajax({
url: fullUrl,
type: "POST",
data: JSON.stringify({
'__metadata': { 'type': 'SP.Folder' },
'ServerRelativeUrl': 'Shared Documents/' + folderName
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onQuerySucceeded,
error: onQueryFailed
});
}
function onQuerySucceeded() {
$("#divResults").html("Folder created successfully !!!");
}
function onQueryFailed() {
alert('Error!');
}
</script>
<div>
<strong>Enter FolderName:</strong><br />
<input type="text" id="txtFolderName" /><br />
<input type="button" id="btnSubmit" value="Create Folder" />
</div>
<div id="divResults"></div>
Reference:
Some Help for Authorization Problems in SharePoint 2013 REST API

Related

When we pass the Object using fetch api in Fakeapi , obj doesn't add in 101 id

I am a trying to pass the object using fetch api in JsonPacehoder Post api and print the value of then method but then methods returns blank object . this object only carry id not holdes my values. so i am dont understand what kind of problem in this code please help me....
<body>
<h1>i am a heading</h1>
<input type="text" id="title" title="title" >
<input type="text" id="body">
<input type="text" id="userId">
<button onclick="myFunction()">ok</button>
<script>
async function myFunction(){
let title_Value = document.getElementById("title").value;
let body_Value = document.getElementById("body").value;
let userId_Value = document.getElementById("userId").value;
let obj = {
title: "title_Value",
body: "body_Value",
userId: "userId_Value",
}
await fetch('https://jsonplaceholder.typicode.com/posts' ,
{
method: "POST",
body : JSON.stringify(obj),
headers: {
'Accept': 'application/json',
"contentType" : "application/json; charset=UTF-8",
},
})
.then((resolve)=> resolve.json())
.then((result)=> console.log(result))
}
Here the output
>{id: 101}
id: 101
>[[Prototype]]: Object

how to access specific team site in share-point using rest apis

goal: I'm trying to access a specific team site which created in my share-point account using REST APIs and create a folder inside there (Documents folder - default location)
actual results: I'm getting 403 error code. following is the response body which I'm getting.
{
"error": {
"code": "-2147024891, System.UnauthorizedAccessException",
"message": {
"lang": "en-US",
"value": "Access denied. You do not have permission to perform this action or access this resource."
}
}
}
expected result: specified folder should be created and response code should be 201 or 200
what I've tried:
first registered the app in both share-point as well as Azure
get the bearer token calling share-point rest api
tested get apis for share-point and all are worked as expected.
before each request I set the bearer token in the request header
following are the other request headers which I'm setting
Content-Type : application/json;odata=verbose
X-RequestDigest : some random string
Accept : application/json;odata=verbose
following is the share-point REST API, I used POST method for creating a folder
https://***.sharepoint.com/sites/TeamSite_ForB/_api/web/folders
following is the request body which I'm sending
{
"__metadata":{
"type":"SP.Folder"
},
"ServerRelativeUrl":"/Shared Documents/buddhika-test-folder-03"
}
In the share-point documentation site they've provided the API format.
I tried with that format , but couldn't get the result as well.
following is from share-point documentation.
To access a specific site, use the following construction:
http://server/site/_api/web
in that case I have tried as following
https://***.sharepoint.com/TeamSite_ForB/_api/web/folders
I'm getting response as 404 Not found with no response message.
I have searched through many documents but couldn't find how to access a specific team site.
Any help would be appreciated.
The request REST API URL as below.
https://***.sharepoint.com/sites/TeamSite_ForB/_api/web/folders
The request body as following.
{
"__metadata":{
"type":"SP.Folder"
},
"ServerRelativeUrl":"Shared Documents/buddhika-test-folder-03"
}
Example code:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getFormDigest() {
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo",
method: "POST",
headers: { "Accept": "application/json; odata=verbose" }
});
}
function createFolderTest() {
var documentLibraryName = "Shared Documents";
var folderName="buddhika-test-folder-03";
if(folderName!=""){
createfolder(documentLibraryName,folderName).done(function (data) {
console.log('Folder creted succesfully');
}).fail(function (error) {
console.log(JSON.stringify(error));
});
}
return true;
}
function createfolder(documentLibraryName,folderName){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/folders";
return getFormDigest().then(function (data) {
return $.ajax({
url: requestUri,
type: "POST",
contentType: "application/json;odata=verbose",
data:JSON.stringify({'__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': documentLibraryName+'/'+folderName}),
headers: {
"accept":"application/json;odata=verbose",
"X-RequestDigest":data.d.GetContextWebInformation.FormDigestValue
}
});
});
}
</script>
<input type="button" onclick="createFolderTest()" value="Create Folder"/>

How to get all survey answer by current user with REST Api Sharepoint?

In sharepoint survey API:
Get all question: https://site/_api/Web/Lists/getByTitle('Survey')/fields?$filter=(CanBeDeleted eq true)
Get all answer: https://site/_api/Web/Lists/getByTitle('Recognition%20Awards%202019')/items
Get all answer by current user login: ???
Please help me.
We can use _spPageContextInfo.userId to get the current login user Id, then using $filter=AuthorId eq UserId to get all the answer by current user login.
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getItems() {
var listTitle="Recognition Awards 2019";
var currentUserId=_spPageContextInfo.userId;
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listTitle+"')/items?$filter=AuthorId eq "+currentUserId,
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
//
},
error: function (err) {
//alert(err);
}
});
}
</script>
<input id="Button1" type="button" value="Get Items" onclick="getItems()" />

Nodejs POST request multipart/form-data

I am trying to upload a photo via a POST request with the request module
According to the readme I should just be able to do this
var r = request.post("http://posttestserver.com/post.php", requestCallback)
var form = r.form()
form.append("folder_id", "0");
form.append("filename", fs.createReadStream(path.join(__dirname, "image.png")));
function requestCallback(err, res, body) {
console.log(body);
}
The problem is, this doesn't work. I get a reply from the test server saying it dumped 0 post variables.
I have confirmed that the server is in working condition with this little html page
<html>
<body>
<form action="http://posttestserver.com/post.php?dir=example" method="post" enctype="multipart/form-data">
File: <input type="file" name="submitted">
<input type="hidden" name="someParam" value="someValue"/>
<input type="submit" value="send">
</form>
</body>
</html>
So the question is, what am I doing wrong with the request module? Is there a better way to send multipart/form-data with node?
After some more research, I decided to use the restler module. It makes the multipart upload really easy.
fs.stat("image.jpg", function(err, stats) {
restler.post("http://posttestserver.com/post.php", {
multipart: true,
data: {
"folder_id": "0",
"filename": restler.file("image.jpg", null, stats.size, null, "image/jpg")
}
}).on("complete", function(data) {
console.log(data);
});
});
So I just got done wrestling with this myself and here is what I learned:
It turns out that neither request or form-data are setting the content-length header for the generated body stream.
Here is the reported issue: https://github.com/mikeal/request/issues/316
The solution posted by #lildemon gets around this by:
Generating the FormData object
Getting it's length
Making the request and setting the form object and content-length header explicitly
Here is a modified version of your example:
var request = require('request');
var FormData = require('form-data');
var form = new FormData();
form.append("folder_id", "0");
form.append("filename", fs.createReadStream(path.join(__dirname, "image.png")));
form.getLength(function(err, length){
if (err) {
return requestCallback(err);
}
var r = request.post("http://posttestserver.com/post.php", requestCallback);
r._form = form;
r.setHeader('content-length', length);
});
function requestCallback(err, res, body) {
console.log(body);
}
I have working code that does exactly what your question states, with one exception. My file content is appended this way:
form.append('file', new Buffer(...),
{contentType: 'image/jpeg', filename: 'x.jpg'});
To discover the final options argument I had to drill down into the source of form-data. But this gives me a working configuration. (Maybe it was what you were missing, but of course that will depend on the server.)
I tried also request and form-data modules and was unable to upload a file.
You can use superagent which works:
http://visionmedia.github.io/superagent/#multipart-requests.
var request = require('superagent');
var agent1 = request.agent();
agent1.post('url/fileUpload')
.attach('file',__dirname + "/test.png")
.end(function(err, res) {
if (err) {
console.log(err)
}
});
Try request module. It works like any other normal post request
var jsonUpload = { };
var formData = {
'file': fs.createReadStream(fileName),
'jsonUpload': JSON.stringify(jsonUpload)
};
var uploadOptions = {
"url": "https://upload/url",
"method": "POST",
"headers": {
"Authorization": "Bearer " + accessToken
},
"formData": formData
}
var req = request(uploadOptions, function(err, resp, body) {
if (err) {
console.log('Error ', err);
} else {
console.log('upload successful', body)
}
});

how to handle multipart/form-data in node.js

I am uploading image file from client side using multipart form data. I want to receieve and write it as a file in the server side using node.js.
<html>
<body>
<form action="url" method="post" enctype="multipart/form-data">
<input type="text" name="imageName">
<input type="file" name="sam">
</form>
</body>
</html>
This is my client side code. How to handle this file in server side.
It is repeated question below link.
Uploading images using Node.js, Express, and Mongoose
Here is example:
// Expose modules in ./support for demo purposes
require.paths.unshift(__dirname + '/../../support');
/**
* Module dependencies.
*/
var express = require('../../lib/express')
, form = require('connect-form');
var app = express.createServer(
// connect-form (http://github.com/visionmedia/connect-form)
// middleware uses the formidable middleware to parse urlencoded
// and multipart form data
form({ keepExtensions: true })
);
app.get('/', function(req, res){
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Image: <input type="file" name="image" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.post('/', function(req, res, next){
// connect-form adds the req.form object
// we can (optionally) define onComplete, passing
// the exception (if any) fields parsed, and files parsed
req.form.complete(function(err, fields, files){
if (err) {
next(err);
} else {
console.log('\nuploaded %s to %s'
, files.image.filename
, files.image.path);
res.redirect('back');
}
});
// We can add listeners for several form
// events such as "progress"
req.form.on('progress', function(bytesReceived, bytesExpected){
var percent = (bytesReceived / bytesExpected * 100) | 0;
process.stdout.write('Uploading: %' + percent + '\r');
});
});
app.listen(3000);
console.log('Express app started on port 3000');
If your question is not solve then please visit this link . This is a nice article about file uploading.
You can use request module for sending a multipart request. Here is the sample code:
var jsonUpload = { };
var formData = {
'file': fs.createReadStream(fileName),
'jsonUpload': JSON.stringify(jsonUpload)
};
var uploadOptions = {
"url": "https://upload/url",
"method": "POST",
"headers": {
"Authorization": "Bearer " + accessToken
},
"formData": formData
}
var req = request(uploadOptions, function(err, resp, body) {
if (err) {
console.log('Error ', err);
} else {
console.log('upload successful', body)
}
});