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

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

Related

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

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:-

error 403 url shortener with bitly and js

I have searched for the answer but nothing helped. Please suggest me with a solution, when I try to shorten the url with bitly and vue js I get 403 error.
axios api:
const headers = {
'Authorization': `Bearer ${myToken}`,
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
'Access-Control-Allow-Credentials':true
};
const dataString =
'{ "long_url": "https://dev.bitly.com", "domain": "bit.ly", "group_guid": "Ba1bc23dE4F" }';
axios
.post("https://api-ssl.bitly.com/v4/shorten", {
headers: headers,
body: dataString,
})
.then(function (response) {
if (response.status == 200) {
console.log(response);
} else {
console.log("Opps dude, status code != 200 :( ");
}
})
.catch(function (error) {
console.log("Error! " + error);
});
I have changed code according proposal in the comments. But the same 403 error.
I have just received bitly support email that it is not working because I use group_id. "... "Ba1bc23dE4F" is a placeholder value in our documentation to show where your group GUID would be passed if you have an account with multiple groups. In your case, you can remove this whole value and simply pass a body with:
{ "long_url": "https://dev.bitly.com", "domain": "bit.ly" }"

GraphQL query to GitHub failing with HTTP 422 Unprocessable Entity

I am currently working on a simple GitHub GraphQL client in NodeJS.
Given that GitHub GraphQL API is accessible only with an access token, I set up an OAuth2 request to grab the access token and then tried to fire a simple GraphQL query.
OAuth2 flow gives me the token, but when I send the query, I get HTTP 422.
Here below simplified snippets from my own code:
Prepare the URL to display on UI side, to let user click it and perform login with GitHub
getGitHubAuthenticationURL(): string {
const searchParams = new URLSearchParams({
client_id,
state,
login,
scope,
});
return `https://github.com/login/oauth/authorize?${searchParams}`;
}
My ExpressJs server listening to GitHub OAuth2 responses
httpServer.get("/from-github/oauth-callback", async (req, res) => {
const {
query: { code, state },
} = req;
const accessToken = await requestGitHubAccessToken(code as string);
[...]
});
Requesting access token
async requestToken(code: string): Promise<string> {
const { data } = await axios.post(
"https://github.com/login/oauth/access_token",
{
client_id,
client_secret,
code
},
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
}
);
return data.access_token;
}
Firing simple graphql query
const data = await axios.post(
"https://graphql.github.com/graphql/proxy",
{ query: "{ viewer { login } }"},
{
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
}
);
Do you guys have any clue?
Perhaps I am doing something wrong with the OAuth2 flow? As in most of the examples I found on the web, a personal token is used for this purpose, generated on GitHub, but I would like to use OAuth2 instead.
Thanks in advance for any help, I really appreciate it!
EDIT
I changed the query from { query: "query { viewer { login } }"} to { query: "{ viewer { login } }"}, nonetheless, the issue is still present.
I finally found the solution:
Change the URL from https://graphql.github.com/graphql/proxy to https://api.github.com/graphql, see here
Add the following HTTP headers
"Content-Type": "application/json"
"Content-Length"
"User-Agent"
Hope this will help others out there.

Creating JIRA issue through angular form

Trying to create an issue from angularjs using rest api throwing 403 forbidden error. New to this, any help would be appreciated.
error:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8080' is therefore not allowed
access. The response had HTTP status code 403.
$http({
method: "POST",
url: 'https://jira.ab.com/rest/api/2/search',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " +
btoa('abc#ab.com' + ":" + '***'));
},
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify({
jql: {
project: "JQR",
maxResults: 20,
}
})
}).then(function successCallback(response) {
return response.data;
}, function errorCallback() {
console.log("Error calling API")
});

Bad request when trying to post to wcf rest 4 service

I am playing with the wcf 4.0 rest template and trying to get it to work with jquery.
I have created a new rest template project and added a webform into the same project just to get things simple.
I have slightly modfied the Create Method to look like this
[WebInvoke(UriTemplate = "", Method = "POST")]
public string Create(SampleItem instance)
{
// TODO: Add the new instance of SampleItem to the collection
return (instance.Id == 1) ? "1 was returned" : "something else was returned";
}
Then from my webform I am using this.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
url: "/service1/",
data: { "Id": 1,"StringValue": "String content"
},
success: function (data) {
$('.result').html(data);
},
error: function (error) {
$('.result').html(error)
},
dataType: "json",
contentType: "application/json; charset=utf-8"
});
});
</script>
<div class="result"></div>
However fiddler is returning a 400 error telling me there is a request error. Have I done something wrong?
400 can also mean something in your service went wrong. Did you try to attach a debugger to the Rest-service?
Tried to create a .Net-console application (create the request using HttpClient) and communicate with your service?
I ran into same error, after half hour of testing I saw just some error occured in the REST-service.