I am currently following the prepare the file for viewer tutorial on autodesk forge. This is the link:
https://forge.autodesk.com/en/docs/model-derivative/v2/tutorials/prep-file4viewer/
Rather than making the requests using cURL, I have made javascript code using jquery ajax to make the requests. I have made each request a function, with a button to trigger each request, as the code shows below. Currently, each request works fine except for the translate to svf request. When I attempt to make that request and check the status of my request the following message is printed:
{
"urn": "dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6cHJvamVjdGZpbGVzMTIzNC9fTUMtMTQwMDYlMjBGT0xERVIlMjBBU1NZJTIwLSUyMEhTQ0YtMTIuaWFtLmR3Zg",
"derivatives": [{
"hasThumbnail": "false",
"name": "_MC-14006 FOLDER ASSY - HSCF-12.iam.dwf",
"progress": "complete",
"messages": [{
"type": "error",
"code": "DWF2D-Not_A_DWF_Error",
"message": "Unable to open, not a DWF/DWFx file."
}, {
"type": "error",
"message": "Extractor error code -11",
"code": "TranslationWorker-InternalFailure"
}],
"outputType": "svf",
"status": "failed"
}],
"hasThumbnail": "false",
"progress": "complete",
"type": "manifest",
"region": "US",
"version": "1.0",
"status": "failed"
Using postman, I can make the same request and everything will work fine. Then when I attempt to translate the file again, it will work as long as it's from the same bucket. I need files to be able to be uploaded and translated right away from the code, without having to translate it first in postman. I even attempted to copy the postman code for the translation request, but am getting the same error when the file is not already in my bucket. Below is my code for the simple webpage.
<html>
<title>Viewer</title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.7/jstree.min.js"></script>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=no" />
<meta charset="utf-8">
<link rel="stylesheet" href="https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/style.min.css" type="text/css">
<script src="https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/viewer3D.min.js"></script>
<style>
body {
margin: 0;
}
#forgeViewer {
width: 100%;
height: 100%;
margin: 40px;
background-color: #F0F8FF;
}
</style>
</head>
<script>
//variable declaration
var access_token='';
const bucketKey = 'projectfiles123874';
const policyKey = 'transient';
var urn1 = '';
var urn2 = '';
var urn3 = '';
//var fileName = '_MC-14006 FOLDER ASSY - HSCF-12.iam.dwf';
var fileName = '';
if(access_token == ''){
getToken();
}
function getToken(){
$.ajax({
method: 'POST',
url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
data: 'client_id=lAOwCkVLo307t4fxWdEriDrPs1CAhdMl&client_secret=AhWJ5cIrm6Lh65AB&grant_type=client_credentials&scope=data:read data:write bucket:read viewables:read bucket:create data:create',
success:function(response){
access_token=response.access_token;
console.log(response);
console.log(access_token);
},
error:function(error){
console.log(error);
}
})
}
function createBucket(){
$.ajax({
method: 'POST',
url: "https://developer.api.autodesk.com/oss/v2/buckets",
headers:{
"content-type": "application/json",
// "x-ads-force":true,
Authorization: "Bearer " + access_token
},
data: JSON.stringify({
'bucketKey': bucketKey,
'policyKey': policyKey
}),
success:function(response){
console.log(response);
//window.location.href = "http://team/www/upload.html";
},
error:function(error){
if (error.response && error.response.status == 409){
console.log("bucket alrready exists, skipping creation.");
}
else{
console.log("failed to create new bucket.");
}
}
})
}
function uploadFile(){
$.ajax({
method: 'PUT',
url:"https://developer.api.autodesk.com/oss/v2/buckets/"+encodeURIComponent(bucketKey)+"/objects/"+encodeURIComponent(fileName)+"",
data: 'C:\Users\matthew_vidovic\Desktop\DWGs\_MC-7251 CLOROX CARTON FORMER.iam.dwf',
headers:{
Authorization: "Bearer " + access_token
},
success:function(response){
console.log(response);
urn1 = response.objectId;
console.log(urn1);
urn2 = btoa(urn1);
console.log(urn2);
},
error:function(error){
console.log(error);
}
})
}
function translateToSVF(){
$.ajax({
method: 'POST',
url:"https://developer.api.autodesk.com/modelderivative/v2/designdata/job",
headers:{
"content-type": "application/json",
Authorization: "Bearer " + access_token
},
data:JSON.stringify({
"input":{ "urn":urn2
},
"output":{ "destination":{
"region": "us"
},
"formats": [
{
"type": "svf",
"views": [
"2d",
"3d"
]
}
]
}
}),
success:function(response){
console.log(response);
urn3=response.urn;
console.log(urn3);
// console.log(access_token);
},
error:function(error){
console.log(error);
}
})
/* POSTMAN REQUEST CODE
var settings = {
"url": "https://developer.api.autodesk.com/modelderivative/v2/designdata/job",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/json",
"Cookie": "PF=5aKDLaxVErxdqJY5p40NQy",
Authorization: "Bearer " + access_token
},
"data": JSON.stringify({"input":{"urn":urn2,"rootFilename":fileName,"compressedUrn":false},"output":{"destination":{"region":"us"},"formats":[{"type":"svf","views":["2d","3d"]}]}}),
};
$.ajax(settings).done(function (response) {
console.log(response);
urn3 = response.urn;
console.log(urn3);
});
*/
}
function checkStatus(){
$.ajax({
method: 'GET',
url: "https://developer.api.autodesk.com/modelderivative/v2/designdata/" + encodeURIComponent(urn3) + "/manifest",
headers:{
Authorization: "Bearer " + access_token
},
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
})
}
/*
if(access_token == ''){
getToken();
}
else if(urn1 == ''){
uploadFile();
}
else translateToSVF();
*/
function displayViewer(){
var viewer;
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2', // for models uploaded to EMEA change this option to 'derivativeV2_EU'
getAccessToken: function(onTokenReady) {
var token = access_token;
var timeInSeconds = 3600; // Use value provided by Forge Authentication (OAuth) API
onTokenReady(token, timeInSeconds);
}
};
Autodesk.Viewing.Initializer(options, function() {
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.GuiViewer3D(htmlDiv);
var startedCode = viewer.start();
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
});
var documentId = 'urn:'+urn3;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
function onDocumentLoadSuccess(viewerDocument) {
var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel);
}
function onDocumentLoadFailure() {
console.error('Failed fetching Forge manifest');
}
}
/*
function check(){
if (access_token='') getToken
}
*/
function processSelectedFiles(fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
// alert("Filename " + files[i].name);
fileName = files[i].name;
console.log(fileName);
}
}
</script>
<body><h1>Model Viewer</h1>
<p><button onclick="getToken()">Get Token</button></p>
<p><button onclick="createBucket()">Create Bucket</button></p>
<p><button onclick="uploadFile()">upload file</button></p>
<p><button onclick="translateToSVF()">Translate</button></p>
<p><button onclick="checkStatus()">Check Status</button></p>
<p><button onclick="displayViewer()">display Viewer</button></p>
<p><input type="file" id="input" onchange="processSelectedFiles(this)"></p>
<div id="forgeViewer"></div>
</body>
</html>
Any help as to why this is happening would be greatly appreciated.
Cheers!
Your PUT is not specifying a file name, just a folder, so probably the upload is corrupted. Also, you don't need to provide a content-type.
The file must be selected by the user, your browser app does not have access to the local folder structure. You can create an input file or form, then pass it to the data field
method: 'PUT',
url:"https://developer.api.autodesk.com/oss/v2/buckets/"+encodeURIComponent(bucketKey)+"/objects/"+encodeURIComponent(fileName)+"",
data: theForm.theInput.files[0],
headers:{
Authorization: "Bearer " + access_token
},
You can verify your download via SHA-1 signature or, easier, comparing the file size local and live (inside the bucket).
Related
I can't figure out why I'm getting the below error when I attempt to create a post with the GMB API in Google Apps Script. I'm following this documentation https://developers.google.com/my-business/content/posts-data
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.mybusiness.v4.ValidationError",
"errorDetails": [
{
"code": 2,
"field": "summary",
"message": "Standard local post must have at least a media or summary."
}
]
}
]
}
}
Here is my script
function callToActionPost() {
var url = 'https://mybusiness.googleapis.com/v4/accounts/123/locations/456/localPosts';
var options = {
headers: { Authorization: "Bearer " + getGMBService_().getAccessToken() },
method: 'POST',
muteHttpExceptions: true,
languageCode: "en",
topicType: "STANDARD",
summary: "New Release!",
callToAction: {
actionType: "ORDER",
url: "https://www.artivem.com/"
},
media: {
sourceUrl: "https://untappd.akamaized.net/photos/2021_04_16/ccff4c358e362ce3c4835fcc94549a8f_640x640.jpg",
mediaFormat: "PHOTO"
}
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
I tried the following adaption, but it did not work
function callToActionPost() {
var url = 'https://mybusiness.googleapis.com/v4/accounts/123/locations/456/localPosts';
var options = {
headers: { Authorization: "Bearer " + getGMBService_().getAccessToken() },
method: 'POST',
muteHttpExceptions: true,
payload: {
languageCode: "en",
topicType: "STANDARD",
summary: "New Release!",
callToAction: {
actionType: "ORDER",
url: "https://www.artivem.com/"
},
media: {
sourceUrl: "https://untappd.akamaized.net/photos/2021_04_16/ccff4c358e362ce3c4835fcc94549a8f_640x640.jpg",
mediaFormat: "PHOTO"
}
}
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
Thanks in advance!
The request object needs to go into the payload. "payload" is a parameter of the options.
function callToActionPost() {
var url = 'https://mybusiness.googleapis.com/v4/accounts/123/locations/456/localPosts';
var payload = {
"languageCode": "en-US",
"summary": "New Release!",
"callToAction": {
"actionType": "ORDER",
"url": "https://www.artivem.com/"
},
"media": [{
"sourceUrl": "https://untappd.akamaized.net/photos/2021_04_16/9999999999999999.jpg",
"mediaFormat": "PHOTO"
}]
}
var options = {
headers: { Authorization: "Bearer " + getGMBService_().getAccessToken() },
method: 'POST',
muteHttpExceptions: true,
'contentType': 'application/json',
'payload' : JSON.stringify(payload)
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
if (response.getResponseCode() !== 200) {
console.log("Error Code: " + response.getResponseCode());
}
}
I am trying to make a Post request to an api but for some reason i am getting a 400 feedback in the process. Being that i am a beginner at this, i can't really figure out where i am getting it wrong. I understand 400 error has to do with incorrect syntax but i am not sure that is the case here. I also checked out the other related posts but none helped address my problem. I have also read through the documentation over and over again but still can't see where i am making a mistake. I will appreciate if you helped me point out the problem.
myPostRequest(){
var mybody = {
"amount": "5.0",
"currency": "EUR",
"externalId": "6547864",
"payer": { "partyIdType": "MSISDN","partyId": "0977948551"}
}
mybody = JSON.stringify(mybody);
var token = "mytoken";
//POST request
fetch('https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay', {
method: "POST",
headers: {
'Authorization': 'Bearer '+token,
'X-Reference-Id': 'f9b8b0a-XXXXXXXXXX',
'X-Target-Environment': 'sandbox',
'Ocp-Apim-Subscription-Key': '14d2a71dXXXXXXXXX',
},
body: mybody,
})
.then((responseJson) => {
alert(JSON.stringify(responseJson));
console.log(responseJson);
})
.catch((error) => {
alert(JSON.stringify(error));
console.error(error);
});
}
Use axios/apisauce instead of fetch
apisauce example:
import { create } from 'apisauce';
const api = create({
baseURL: `http://example.com`,
});
const response = await api.post('/path/to/', body, { headers });
In your case:
import { create } from 'apisauce';
const api = create({
baseURL: `https://sandbox.momodeveloper.mtn.com`,
});
const response = await api.post(
'/collection/v1_0/requesttopay',
{
"amount": "5.0",
"currency": "EUR",
"externalId": "6547864",
"payer": { "partyIdType": "MSISDN", "partyId": "0977948551" }
},
{
headers: {
'Authorization': 'Bearer ' + token,
'X-Reference-Id': 'f9b8b0a-XXXXXXXXXX',
'X-Target-Environment': 'sandbox',
'Ocp-Apim-Subscription-Key': '14d2a71dXXXXXXXXX',
}
}
);
I'm getting the error:
Invalid JSON payload received
When trying to create a new Apps Script file with the Apps Script API.
How do I fix that error?
function createNewFile() {
var d,options,payload,response,theAccessTkn,url;
theAccessTkn = ScriptApp.getOAuthToken();
//See https://developers.google.com/apps-script/api/reference/rest/v1/projects/create
url = "https://script.googleapis.com/v1/projects";
d = new Date().toString().slice(0,10);
payload = {
"title": "AA_" + d
}
options = {
"method" : "POST",
"muteHttpExceptions": true,
"headers": {
'Authorization': 'Bearer ' + theAccessTkn
},
"payload": JSON.stringify(payload)
};
response = UrlFetchApp.fetch(url,options);
Logger.log(response)
return response;
}
I have set the authorization scopes in the manifest file to avoid needing to add an OAuth library:
{
"timeZone": "America/New_York",
"oauthScopes": [
"https://www.googleapis.com/auth/script.projects",
"https://www.googleapis.com/auth/script.external_request"
],
"dependencies": {
},
"exceptionLogging": "STACKDRIVER"
}
I needed to add "contentType": "application/json" to the options.
options = {
"method" : "POST",
"muteHttpExceptions": true,
"headers": {
'Authorization': 'Bearer ' + theAccessTkn
},
"contentType": "application/json",
"payload": JSON.stringify(payload)
};
I need to update item in another site collection according to this article I make my code like this
<script type="text/javascript">
$(document).ready(function () {
var otherSiteUrl = "<sitecollectionurl>";
var listName = "TestList";
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": {
"type": itemType
},
"Title": "updated title"
};
$.ajax({
url: otherSiteUrl + "/_api/contextinfo",
type: "POST",
headers: {
"Accept": "application/json;odata=verbose"
},
success: function (contextData) {
alert(contextData.d.GetContextWebInformation.FormDigestValue);
$.ajax({
url: otherSiteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?#target='" + otherSiteUrl + "'",
method: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
async: false,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": contextData.d.GetContextWebInformation.FormDigestValue
},
success: function (data) {
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
}
});
});
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
I used
"X-RequestDigest":
contextData.d.GetContextWebInformation.FormDigestValue
after that I chenge ajax header like
"X-RequestDigest":
$("#__REQUESTDIGEST").val(contextData.d.GetContextWebInformation.FormDigestValue)
for both RequestDigest I got this error:
Invalid JSON. A token was not recognized in the JSON content
after that I chenge ajax header as
How can I update item successfully in another site collection with api?
eventually, I can edit item in another site collection.I just little change in my code.
first, most important part is library full name dose not contain List I use this url to find out library full name .
[Site url]/_api/web/lists/GetByTitle('List Name')/ListItemEntityTypeFullName
then I change metadate as
"__metadata": { "type": 'SP.Data.DocumentsItem' },
second I added
"X-HTTP-Method": "MERGE" , "If-Match": "*"
to header like:
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": contextData.d.GetContextWebInformation.FormDigestValue,
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
I am trying to call GCM notification by using POST.
The code I am using is :
var jsonbody={"to": "/topics/global",
"data": {
"title": "TestTitle",
"is_background": false,
"message": "Testmessage",
"image": "",
"payload": {
"team": "India",
"score": "5.6" },
"timestamp": "2016-12-13 16:32:05"
}
};
var request = require('request');
request.post({
headers: {'content-type': 'application/json',
Authorization:'key=(my key)'},
url: 'https://fcm.googleapis.com/fcm/send',
BODY: jsonbody
}, function (error, response, body) {
if (error) {
console.log('failure ' + error);
} else {
console.log('success '+response + 'and ' +body);
}
});
I am getting error as :
success [object Object]and JSON_PARSING_ERROR: Unexpected token END
OF FILE at position 0.
I was actually missing something :
body: JSON.stringify(jsonbody)
Rest all was correct.