I'm trying to upload a file to a specific sharepoint site. In this page shows me how to upload a sample file to user's onedrive. But, in my case, I need to upload to sharepoint. I'm trying to use this endpoint:
POST /groups/{groupId}/drive/items/{itemId}/createUploadSession
But show me this error response:
{
"error": {
"code": "itemNotFound",
"message": "Item not found",
"innerError": {
"date": "2022-05-08T23:15:29",
"request-id": "ca4362ca-ff36-488c-80b1-9f82c3448cd5",
"client-request-id": "ca4362ca-ff36-488c-80b1-9f82c3448cd5"
}
}
This is cURL:
curl --request POST \
--url https://graph.microsoft.com/v1.0/groups/{groupId}/drive/items/test.txt/createUploadSession \
--header 'Authorization: Bearer xxxx' \
--header 'Content-Type: application/json' \
--data '{
"#microsoft.graph.conflictBehavior": "rename",
"description": "description",
"fileSize": 4,
"name": "test.txt"
}'
You are trying to call endpoint which requires itemId but you send file name instead of itemId.
POST /groups/{groupId}/drive/items/{itemId}/createUploadSession
Another way is to specify the path to the file. The item-path must contain the name of the item that's specified in the request body.
POST /groups/{groupId}/drive/root:/{item-path}:/createUploadSession
// file system path using /drive/root:/path/to/file
POST /groups/{groupId}/drive/root:/path/to/test.txt:/createUploadSession
Here is an example of uploading a large file to SharePoint using graph API SDK Read more, step-by-step solutions
public async Task<void> Upload()
{
string site = "<YOUR DOMAIN, REPLACE HERE>.sharepoint.com";
string relativePath = "/sites/<YOUR SITE, REPLACE HERE>";
var _authProvider = _SetAuthToken();
GraphServiceClient graphClient = new GraphServiceClient(_authProvider);
Site s = await graphClient
.Sites[site]
.SiteWithPath(relativePath)
.Request()
.GetAsync();
using (var fileStream =
System
.IO
.File
.OpenRead(
#"myfile.txt"
))
{
var uploadSession = await graphClient
.Sites[s.Id]
.Drive
.Root
.ItemWithPath("sometext-1.txt")
.CreateUploadSession()
.Request()
.PostAsync();
// Max slice size must be a multiple of 320 KiB
int maxSliceSize = 320 * 1024;
var fileUploadTask =
new LargeFileUploadTask<DriveItem>(uploadSession, fileStream,
maxSliceSize);
var totalLength = fileStream.Length;
// Create a callback that is invoked after each slice is uploaded
IProgress<long> progress = new Progress<long>(prog => { });
try
{ // Upload the file
var uploadResult = await fileUploadTask.UploadAsync(progress);
//Console.WriteLine(uploadResult.UploadSucceeded ?
// $"Upload complete, item ID: {uploadResult.ItemResponse.Id}" :
// "Upload failed");
}
catch (ServiceException ex)
{
//Console.WriteLine($"Error uploading: {ex.ToString()}");
}
}
}
Related
This question is about receiving POST request from somewhere. I'm looking for a google sheet script function that can take and handle data from the POST request in JSON format. Could you suggest any example?
The POST request is here:
https://script.google.com/macros/s/BOdirjv45Dn6FHrx_4GUguuS6NJxnSEeviMHm3HerJl4UsDBnDgfFPO/
{
"p1": "writeTitle",
"p2": [[URL]],
"p3": [[PIC_A]],
"p4": [[PIC_B]],
"p5": [[TITLE]]
}
application/json
doPost() doesn't work:
doPost(e) {
var json = JSON.parse(e.postData.contents);
Logger.log(json);
}
You want to retrieve the value from the request body as an object.
You have already deployed Web Apps.
If my understanding of your situation is correct, how about this modification?
Post and retrieved object:
As a sample, I used the following curl command to POST to Web Apps.
curl -L \
-H 'Content-Type:application/json' \
-d '{"p1": "writeTitle","p2": "[[URL]]","p3": "[[PIC_A]]","p4": "[[PIC_B]]","p5": "[[TITLE]]"}' \
"https://script.google.com/macros/s/#####/exec"
When above command is run, e of doPost(e) is as follows.
{
"parameter": {},
"contextPath": "",
"contentLength": 90,
"queryString": "",
"parameters": {},
"postData": {
"type": "application/json",
"length": 90,
"contents": "{\"p1\": \"writeTitle\",\"p2\": \"[[URL]]\",\"p3\": \"[[PIC_A]]\",\"p4\": \"[[PIC_B]]\",\"p5\": \"[[TITLE]]\"}",
"name": "postData"
}
}
The posted payload can be retrieved by e.postData. From above response, it is found that the value you want can be retrieved by e.postData.contents. By the way, when the query parameter and the payload are given like as follows,
curl -L \
-H 'Content-Type:application/json' \
-d '{"p1": "writeTitle","p2": "[[URL]]","p3": "[[PIC_A]]","p4": "[[PIC_B]]","p5": "[[TITLE]]"}' \
"https://script.google.com/macros/s/#####/exec?key=value"
value can be retrieved by e.parameter or e.parameters. And the payload can be retrieved by e.postData.contents.
Modified script:
In this modified script, the result can be seen at the Stackdriver, and also the result is returned.
function doPost(e) {
var json = JSON.parse(e.postData.contents);
console.log(json);
return ContentService.createTextOutput(JSON.stringify(json));
}
Note:
When you modified your script of Web Apps, please redeploy it as new version. By this, the latest script is reflected to Web Apps. This is an important point.
Reference:
Web Apps
Stackdriver Logging
If this was not what you want, I'm sorry.
I want to get a list of images in a bucket using REST and axios.
ref: https://cloud.google.com/storage/docs/listing-objects#list-objects-json
The documentation gives this curl request
curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" \
"https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o"
reqConfig: this is a token I use in my REST firestore queries to authenticate the user. I'm using that same token for here. I'm guessing it's the problem but not sure how to fix it.
My result is consistently 404 for a bucket path that I know exists, using the URL from their docs. I should be getting a json list of the files in the bucket.
Error: Request failed with status code 404
Where am I going wrong?
export async function getCompanyStorage(context, apikey, companyId) {
const url = `https://storage.googleapis.com/storage/v1/b/uploads/${companyId}/o?key=${apikey}`;
const cookies = nookies.get(context);
const reqConfig = {
headers: new Headers({
Authorization: "Bearer " + cookies.token,
"Content-Type": "application/json",
}),
};
const result = axios
.get(url, { headers: { Authorization: `Bearer ${reqConfig}` } })
.then((res) => {
return res.data;
})
.catch((error) => {
console.error("error using axios", error);
});
}
Edit: a path to a bucket in the firebase console looks like this
gs://projectname.appspot.com/uploads/WhmDZyQdLVk7n0qR7aTg
I suggest reviewing the documentation you linked to. In particular:
OAUTH2_TOKEN is the access token you generated in Step 1.
BUCKET_NAME is the name of the bucket whose objects you want to list. For example, my-bucket.
You can use a prefix=PREFIX query string parameter to limit results to
objects that have the specified prefix.
Your URL does not contain the name of the bucket as required by the URL pattern. Use the unique name of the bucket where you see "BUCKET_NAME". It looks like, given your example, that it would be "projectname.appspot.com". BUCKET_NAME is not the path of the object within that bucket. If you want to list files under the "uploads" prefix, then you would use the prefix query string parameter to specify that, as documented in the last line of the quoted text.
You can use this function to create Get request with axios for Google Cloud Storage
export const UploadVideo = async (form_data, file, signedurl, asset_uuid) => {
let resultState = { state: '', data: {} };
console.log(signedurl)
/*
const xhr = new XMLHttpRequest();
xhr.open("PUT", signedurl);
xhr.setRequestHeader('Content-Type', "application/octet-stream");
xhr.send(file);
*/
let config = {
headers: {
'Content-Type': 'application/octet-stream',
},
};
await axios.get(signedurl, file, config).then(function (response) {
resultState.state = 'success';
}).catch(function (error) {
resultState.state = 'error';
resultState.data.message = error.message;
window.toastr.error(error.message);
console.log(error)
})
return resultState;
}
I am new to using this Yodlee tool, I created my developer account, and I am wanting to consume the sandbox APIs.
I am not being able to consume by rest with the Talend Api not even the initial method of "auth" (https://sandbox.api.yodlee.com/ysl/auth/token) to obtain the token; I'm passing the loginName, Api-version: 1.1, and content-type in the header as specified, then the clientId and the secret in the body.
The error message it returns is:
{
"errorCode": "Y303",
"errorMessage": "clientId or secret is missing",
"referenceCode": "rrt-8413800343306027303-c-gce-12663 ....."
}
Maybe the sandbox account doesn't allow me to do this, or am I forgetting something?
I just got the same issue. I am using RestSharp.
Finally found out that's a mismatched Content-Type.
It works after adding the header: Content-Type: application/x-www-form-urlencoded
For anyone having this issue with Google Apps Script, this is how I did it:
/************************************************************************************
*
* This function starts the app, replace variables as necessary
*
************************************************************************************/
function primaryFunction() {
// Declare variables
var yodleeToken = {};
var loginName = "ENTER_LOGIN_NAME";
var clientID = "ENTER_CLIENT-ID";
var clientSecret = "ENTER_CLIENT_SECRET";
var yodleeURL = "https://sandbox.api.yodlee.com/ysl/";
// Generate user token
yodleeToken = getUserToken(loginName, clientID, clientSecret, yodleeURL);
}
/************************************************************************************
*
* Creating function to get user token
*
* #params loginName {String} Login name provided by Yodlee API
* #params clientID {String} Client ID provided by Yodlee API
* #params clientSecret {String} Client Secret provided by Yodlee API
* #params yodleeURL {String} Yodlee API Endpoint
*
* References
* https://av.developer.yodlee.com/
*
************************************************************************************/
function getUserToken(loginName, clientID, clientSecret, yodleeURL) {
// Specify headers
var headers = {
'Api-Version': '1.1',
'Content-Type': 'application/x-www-form-urlencoded',
'loginName': encodeURIComponent(loginName)
};
// Build params
var parameters = {
'method': 'POST',
'headers': headers,
'payload': encodeURI("clientId=" + clientID + "&secret=" + clientSecret),
'redirect': 'follow',
'timeout': 0,
// 'muteHttpExceptions': true,
};
// Call API with params
var response = UrlFetchApp.fetch(yodleeURL + "auth/token", parameters);
var responseJSON = JSON.parse(response);
// return JSON response with Link Token
return responseJSON;
}
You need to pass clientId and secret key in data-urlencode and remaining keys in header then it will return token
curl --location --request POST 'https://sandbox.api.yodlee.com/ysl/auth/token' \
--header 'Api-Version: 1.1' \
--header 'loginName: From your dashboard (Sandbox only)' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'clientId=Your clientId' \
--data-urlencode 'secret=Your secret'
I am trying to use one of the Amadeus flight API (flight lowest-fare search) and I think I am having issues with the authorization. The first part of the authorization works fine where I have to input the grant type, API key, and API secret. This returns the access token needed to return the flight API. However, when printing the response body I keep getting null. Could someone help me with this? I am showing my API key and API secret but that's not an issue as I can create a new one. Here's the code:
To first provide context, here's how an Amadeus API gets called after access token is retrieved from the authorization server. This endpoint returns a flight's check-in links.
curl -X GET \
"https://test.api.amadeus.com/v2/reference-data/urls/checkin-links?airlineCode=1X" \
-H "Authorization: Bearer CpjU0sEenniHCgPDrndzOSWFk5mN"
I believe my issue might in my authorization header in the flight low-fare search endpoint. I concatenated the two variables in which the token_type which has a value of 'Bearer' and the access token. In the curl example, 'Bearer' is within the speech marks. In flutter, you cannot do that as 'Authorization is the only header. Below is my code in dart:
getFlights(fromCode, toCode) async {
// getting access token
var response = await http.post(
'https://test.api.amadeus.com/v1/security/oauth2/token',
body: {
"grant_type": "client_credentials",
"client_id": "cxuxBmIvbpbv0JKzKTsJjNqc595uJVYb",
"client_secret": "buhj4SDGVrG1AzzV",
},
);
if (response.statusCode == 200) {
try {
print(response.body);
var code = jsonDecode(response.body);
if (code != null) {
var tokenType = code['token_type'];
print(tokenType);
print(code['access_token']);
var token = code['access_token'];
var bearerToken = '$tokenType ' + '$token';
print(bearerToken);
// flight low-fare search endpoint
var flightApi = await http.get(
'https://test.api.amadeus.com/v1/shopping/flight-offers?origin=LHR&destination=CDG&departureDate=2020-03-19&max=2',
headers: {
"Authorization": bearerToken,
});
var flight = json.decode(response.body);
print(flight['data']);
}
} catch (e) {
print(e.toString());
}
}
}
This the return from the authorization server which provides the access token:
{
"type": "amadeusOAuth2Token",
"username": "I REMOVED THIS",
"application_name": "I REMOVED THIS",
"client_id": "cxuxBmIvbpbv0JKzKTsJjNqc595uJVYb",
"token_type": "Bearer",
"access_token": "z8rVGOAuGaXGNUMIcVPYW76ki5Dl",
"expires_in": 1799,
"state": "approved",
"scope": ""
}
This is the return for the flight low-fare search endpoint
flutter: null
Is it possible to create an issue in jira using REST api? I didn't find this in the documentation (no POST for issues), but I suspect it's possible.
A wget or curl example would be nice.
POST to this URL
https://<JIRA_HOST>/rest/api/2/issue/
This data:
{
"fields": {
"project":
{
"key": "<PROJECT_KEY>"
},
"summary": "REST EXAMPLE",
"description": "Creating an issue via REST API",
"issuetype": {
"name": "Bug"
}
}
}
In received answer will be ID and key of your ISSUE:
{"id":"83336","key":"PROJECT_KEY-4","self":"https://<JIRA_HOST>/rest/api/2/issue/83336"}
Don't forget about authorization. I used HTTP-Basic one.
The REST API in JIRA 5.0 contains methods for creating tasks and subtasks.
(At time of writing, 5.0 is not yet released, although you can access 5.0-m4 from the EAP page. The doco for create-issue in 5.0-m4 is here).
As of the latest released version (4.3.3) it is not possible to do using the REST API. You can create issues remotely using the JIRA SOAP API.
See this page for an example Java client.
This is C# code:
string postUrl = "https://netstarter.jira.com/rest/api/latest/issue";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(postUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("JIRAMMS:JIRAMMS"));
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = #"{""fields"":{""project"":{""key"": ""JAPI""},""summary"": ""REST EXAMPLE"",""description"": ""Creating an issue via REST API 2"",""issuetype"": {""name"": ""Bug""}}}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
To answer the question more direct, i.e. using cURL.
To use cURL to access JIRA REST API in creating a case, use
curl -D- -u <username>:<password> -X POST --data-binary "#<filename>" -H "Content-Type: application/json" http://<jira-host>/rest/api/2/issue/
And save this in your < Filename> (please edit the field per your Jira case) and save in the folder you call the cURL command above.
{
"fields": {
"project":
{
"key": "<PROJECT_KEY>"
},
"summary": "REST EXAMPLE",
"description": "Creating an issue via REST API",
"issuetype": {
"name": "Bug"
}
}
}
This should works. (note sometimes if it errors, possibly your content in the Filename is incorrect).
Now you can use REST + JSON to create issues.
To check which json fields you can set to create the issue use:
https://jira.host.com/rest/api/2/issue/createmeta
For more information please see the JIRA rest documentation:
https://docs.atlassian.com/jira/REST/6.2.4/
To send the issue data with REST API we need to construct a valid JSON string comprising of issue details.
A basic example of JSON string:
{“fields” : { “project” : { “key” : “#KEY#” } , “issuetype” : { “name” : “#IssueType#” } } }
Now, establish connection to JIRA and check for the user authentication.
Once authentication is established, we POST the REST API + JSON string via XMLHTTP method.
Process back the response and intimate user about the success or failure of the response.
So here JiraService being an XMLHTTP object, something like this will add an issue, where EncodeBase64 is a function which returns encrypted string.
Public Function addJIRAIssue() as String
With JiraService
.Open "POST", <YOUR_JIRA_URL> & "/rest/api/2/issue/", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Authorization", "Basic " & EncodeBase64
.send YOUR_JSON_STRING
If .Status <> 401 Then
addJIRAIssue = .responseText
Else
addJIRAIssue = "Error: Invalid Credentials!"
End If
End With
Set JiraService = Nothing
End Sub
You can check out a complete VBA example here
In order to create an issue, set a time estimate and assign it to yourself, use this:
Generate an Atlassian token
Generate & save a base64-encoded auth token:
export b64token="$(echo "<your_email>:<generated_token>" | openssl base64)"
Make a POST request:
curl -X POST \
https://<your_jira_host>.atlassian.net/rest/api/2/issue/ \
-H 'Accept: */*' \
-H 'Authorization: Basic $b64token \
-d '{
"fields":{
"project":{
"key":"<your_project_key (*)>"
},
"issuetype":{
"name":"Task"
},
"timetracking":{
"remainingEstimate":"24h"
},
"assignee":{
"name":"<your_name (**)>"
},
"summary":"Endpoint Development"
}
}'
Remarks:
(*) Usually a short, capitalized version of the project description such as: ...atlassian.net/projects/UP/.
(**) if you don't know your JIRA name, cURL GET with the same Authorization as above to https://<your_jira_host>.atlassian.net/rest/api/2/search?jql=project=<any_project_name> and look for issues.fields.assignee.name.
Just stumbling on this and am having issues creating an issue via the REST API.
issue_dict = {
'project': {'key': "<Key>"},
'summary': 'New issue from jira-python',
'description': 'Look into this one',
'issuetype': {'name': 'Test'},
}
new_issue = jira.create_issue(issue_dict)
new_issue returns an already existing issue and doesn't create one.