How i can perform a POST request using fireFox RESTClient add-in - rest

I have this function to perform a POST request to a SharePoint Online site collection:-
function SetListColumnReadOnly() {
$.ajax
({
// _spPageContextInfo.webAbsoluteUrl - will give absolute URL of the site where you are running the code.
// You can replace this with other site URL where you want to apply the function
url: "https://****.sharepoint.com/_api/web/lists/getByTitle('tickets')/fields/getbytitle('defineFields')",
method: "POST",
data: JSON.stringify({
'__metadata': {
// Type that you are modifying.
'type': 'SP.FieldText'
},
'ReadOnlyField': true
}),
headers:
{
// IF-MATCH header: Provides a way to verify that the object being changed has not been changed since it was last retrieved.
// "IF-MATCH":"*", will overwrite any modification in the object, since it was last retrieved.
"IF-MATCH": "*",
"X-HTTP-Method": "PATCH",
// Accept header: Specifies the format for response data from the server.
"Accept": "application/json;odata=verbose",
//Content-Type header: Specifies the format of the data that the client is sending to the server
"Content-Type": "application/json;odata=verbose",
// X-RequestDigest header: When you send a POST request, it must include the form digest value in X-RequestDigest header
//"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data, status, xhr) {
console.log("Success");
},
error: function (xhr, status, error) {
console.log("Failed");
}
});}
Now how we can run this POST inside the FireFox's RESTClient addin or anyother tool using the browser credentials?
when i tried this >> i got forbidden error:-
Also with those headers:-

Related

'Access-Control-Allow-Origin' header value not equal to the supplied origin, POST method

I get the following message in the Chrome dev tools console when submitting a contact form (making a POST request) on the /about.html section my portfolio web site:
Access to XMLHttpRequest at 'https://123abc.execute-api.us-east-1.amazonaws.com/prod/contact' from origin 'https://example.net' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'https://example.net/' that is not equal to the supplied origin.
I don't know how to troubleshoot this properly, any help is appreciated.Essentially, this is happening (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSAllowOriginNotMatchingOrigin) and I don't know where within my AWS assets to fix it. This person had same problem, but i'm unsure of how to apply their fix (CORS header 'Access-Control-Allow-Origin' does not match... but it does‼)
Here is a description of the AWS stack:
Context, I am using an S3 bucket as static website using CloudFront and Route 53, this stuff works fine, has for years. When I added the form, I did the following to allow the HTTP POST request:
Cloudfront, On the site's distribution I added a behavior with all settings default except:
Path pattern: /contact (I am using this bc this is the API Gateway resource path ending)
Origin and origin groups: S3-Website-example.net.s3-website... (Selected correct origin)
Viewer protocol policy: HTTP and HTTPS
Allowed HTTP methods: GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE
Cache HTTP methods GET and HEAD methods are cached by default: Checked OPTIONS box
Origin request policy - optional: CORS-S3Origin
Response headers policy - optional: CORS-With-Preflight
API Gateway, Created a REST API with all default settings except:
Created a resource: /contact
Created a method: POST
For /contact, Resource Actions > Enable CORS:
Methods: OPTIONS and POST both checked
Access-Control-Allow-Origin: 'https://example.net' (no ending slash)
Clicked "Enable CORS and Replace existing headers"
Results are all checked green:
✔ Add Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin Method Response Headers to OPTIONS method
✔ Add Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin Integration Response Header Mappings to OPTIONS method
✔ Add Access-Control-Allow-Origin Method Response Header to POST method
✔ Add Access-Control-Allow-Origin Integration Response Header Mapping to POST method
Created a stage called "prod", ensured it had the /contact resource, and deployed.
At the /contact - POST - Method Execution, The test works as expected (triggers Lambda func that uses SES to send email, which I do actually receive).
The only thing I feel unsure about with API Gateway is after I enable the CORS, I can't seem to find a place where that setting has been saved, and if I click again on enable CORS, it is back to the default form ( with Access-Control-Allow-Origin: '')*
Amazon SES, set up 2 verified identities for sending/receiving emails via lamda.
Lamda, set up a basic javascript function with default settings, the REST API is listed as a trigger, and does actually work as previously mentioned. The function code is:
var AWS = require('aws-sdk');
var ses = new AWS.SES({ region: "us-east-1" });
var RECEIVER = 'myemail#email.com';
var SENDER = 'me#example.net';
var response = {
"statusCode": 200,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
"isBase64Encoded": false,
"body": "{ \"result\": \"Success\"\n}"
}
exports.handler = async function (event, context) {
console.log('Received event:', event);
var params = {
Destination: {
ToAddresses: [
RECEIVER
]
},
Message: {
Body: {
Text: {
Data: 'first name: ' + event.fname + 'last name: ' + event.lname + '\nemail: ' + event.email + '\nmessage: ' + event.message,
Charset: 'UTF-8'
}
},
Subject: {
Data: 'Website Query Form: ' + event.name,
Charset: 'UTF-8'
}
},
Source: SENDER
};
return ses.sendEmail(params).promise();
};
The only thing i can think of here is to maybe update the response to have "headers": {"Access-Control-Allow-Origin": "https://example.net"}
S3 bucket that holds the site contents, in permissions > CORS, I have the following JSON to allow a post of the contact form (notice no slash):
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"POST"
],
"AllowedOrigins": [
"https://example.net"
],
"ExposeHeaders": []
}
]
Permissions/Roles, Established Roles and permissions per
AWS guide: create dynamic contact forms for s3 static websites using aws lambda amazon api gateway and amazon ses
video titled: "Webinar: Dynamic Contact Forms for S3 Static Websites Using AWS Lambda, API Gateway & Amazon SES"
Client code, this is a very milk toast function being called to post the form on click.
function submitToAPI(event) {
event.preventDefault();
URL = "https://123abc.execute-api.us-east-1.amazonaws.com/prod/contact";
const namere = /[A-Za-z]{1}[A-Za-z]/;
const emailre = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,6})?$/;
let fname = document.getElementById('first-name-input').value;
let lname = document.getElementById('last-name-input').value;
let email = document.getElementById('email-input').value;
let message = document.getElementById('message-input').value;
console.log(`first name: ${fname}, last name: ${lname}, email: ${email}\nmessage: ${message}`);
if (!namere.test(fname) || !namere.test(lname)) {
alert ("Name can not be less than 2 characters");
return;
}
if (email == "" || !emailre.test(email)) {
alert ("Please enter valid email address");
return;
}
if (message == "") {
alert ("Please enter a message");
return;
}
let data = {
fname : fname,
lname: lname,
email : email,
message : message
};
$.ajax(
{
type: "POST",
url : URL,
dataType: "json",
crossDomain: "true",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function () {
alert("Successful");
document.getElementById("contact-form").reset();
location.reload();
},
error: function () {
alert("Unsuccessful");
}
});
}
The problem was that the response in the lambda function had "Access-Control-Allow-Origin" set to "*".
This should have been set to the exact origin (no trailing slash), so if the origin is 'https://example.net', then the response in the lamda function should have "Access-Control-Allow-Origin" set to 'https://example.net' as shown below:
var response = {
"statusCode": 200,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "https://example.net"
},
"isBase64Encoded": false,
"body": "{ \"result\": \"Success\"\n}"
}```

SharePoint Rest API - Set Lookup field when [Lookup Name]Id value is already in use

I have a SharePoint list with a number field that has an internal name of [ProjectId]. I later created a lookup column with an internal name of [Project]. I need to use a REST API to update the lookup column value. However, when I use
"ProjectId": 403
It sets the number field. I know SharePoint will append a 0 to a duplicate internal name. However, in this case it was created by the system. I can expand the Lookup column using "Project/Id" in a GET call. I just can't set it.
Does anyone know how to reference the lookup id in this case?
Here is the full code:
// basic patch items
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/lists/GetByTitle('My List')/items(1)",
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"IF-MATCH": "*",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
},
data: JSON.stringify({
"__metadata": {
"type": "SP.Data.MyListListItem"
},
"ProjectId": 403
}),
method: 'PATCH',
success: function (data) {
console.log("success");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
});
I've tried these as well:
"Project0Id": 403
"ProjectId0": 403
It just returns an error saying the column doesn't exist.

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 do I add metadata to a file when uploading via a GCS signedUploadURL?

I'm using a signed URL (generated via the GCS PHP API) to upload a file to a bucket. I POST the signed URL, which returns a Location header which, in turn, I do a PUT of to do the actual upload. This basic upload process is working fine. Now, I need to pass some metadata (uploader name, uploader email, notes, etc.) along with the file.
According to the documentation, I add headers to the PUT request, of the form 'x-goog-meta-<name>': 'value', which are supposed to become the metadata. However, if I don't add them to the signed URL and the POST request, I get a spurious CORS error (No 'Access-Control-Allow-Origin' header is present on the requested resource).
The upload succeeds, and I can see in the Network tab of Chrome that these headers are getting added to the POST and PUT requests, but when the file hits the bucket, there is no metadata.
Here's my code, somewhat simplified:
var metadata, headers;
metadata =
{
'sender-name': "bob dobbs",
'sender-email': "bobdobbs#zynyz.com",
};
headers = { 'x-goog-resumable': 'start' };
for (var i in metadata)
{
headers['x-goog-meta-' + i] = metadata[i];
}
// Start the upload
$.ajax(
{
type: POST,
url: signed_upload_url,
success: on_init_success,
contentType: file.type,
headers: headers,
processData: false
});
// Do the actual upload
var on_init_success = function(result, status, xhr)
{
var loc;
loc = xhr.getResponseHeader('Location');
if (loc)
{
$.ajax(
{
type: 'PUT',
url: loc,
data: file,
contentType: file.type,
headers: headers,
processData: false
});
}
}

403 forbidden and 400 bad request errors while adding and deleting items to SharePoint list using REST

I'm new to SharePoint development. I'm Trying to develop simple SharePoint App using SharePoint online. I have a List named 'Products' in my site collection. In my app I wrote the following code to add and delete items to that list
function addProduct(product) {
var executor;
executor = new SP.RequestExecutor(appwebUrl);
var url = appwebUrl +"/_api/SP.AppContextSite(#target)/web/lists/getbytitle('Products')/items/?#target='" + hostwebUrl+"'";
executor.executeAsync({
url: url,
method: "POST",
body: JSON.stringify({__metadata: { type: 'SP.Data.ProductsListItem' },
Title: product.ProductName(),
ProductId: product.ProductId(),
ProductName: product.ProductName(),
Price:product.Price()
}),
headers: {
"Accept": "application/json; odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: successProductAddHandler,
error: errorProductAddHandler
});
}
function successProductAddHandler(data) {alert('added successfully') }
function errorProductAddHandler(data, errorCode, errorMessage) { alert('cannot perform action') }
function deleteProduct(product) {
var executor;
executor = new SP.RequestExecutor(appwebUrl);
var url=appwebUrl+"/_api/SP.AppContextSite(#target)/web/lists/getbytitle('Products')/items('" + product.ID() + "')/?#target='" + hostwebUrl + "'";
executor.executeAsync({
url: url,
method: "POST",
headers: {
"IF-MATCH": "*",
"X-HTTP-Method": "DELETE"
},
success: successProductAddHandler,
error: errorProductAddHandler
});`
Im getting 403 error code when I call addProduct,
and 400 error code when I call deleteProduct.
I'm able to get the list items and display.
I tried adding X-RequestDigest": $("#__REQUESTDIGEST").val() but it did not work
If I include "Accept": "application/json; odata=verbose" in a request header for deleteProduct(), and when I call deleteProduct, two requests are going to server
/sites/productsdev/productsapp/_api/contextinfo (getting digest value)
/sites/ProductsDev/ProductsApp/_api/SP.AppContextSite(#target)/web/lists/getbytitle('Products')/items(itemid)/?#target='mysitecollectionurl' (using the digest value returned by the above call for X-RequestDigest)
Whenever you are doing any POST operation in SharePoint 2013 using REST API you have to pass below snippet in header
"X-RequestDigest": $("#__REQUESTDIGEST").val()
eg
headers: { "Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val() }