Deleting a file from a bucket - autodesk-forge

I'm trying to delete an object from a bucket. Reading the docs it all sounds super simple, but I just can't seem to get it working.
I'm following the instructions here to try and delete this object, which I can see using https://developer.api.autodesk.com/oss/v2/buckets/my-persistent-bucket/objects:
bucketKey => 'my-persistent-bucket'
objectKey => '--test2.dwg'
objectId => 'urn:adsk.objects:os.object:my-persistent-bucket/--test2.dwg'
sha1 => '477085439a60779064d91fd1971d53c77c7a163a'
size => (int) 188600
location => 'https://developer.api.autodesk.com/oss/v2/buckets/my-persistent-bucket/objects/--test2.dwg'
According to the docs we use this end point:
https://developer.api.autodesk.com/oss/v2/buckets/:bucketKey/objects/:objectName
Where
:bucketKey is url encoded 'my-persistent-bucket'
:objectName is url encoded 'urn:adsk.objects:os.object:my-persistent-bucket/--test2.dwg'
I've tried using PHP's urlencode() and the following base64 encode function:
private function _base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
to encode the :bucketKey and :objectName but no matter how I try to encode it I always get:
404 : Object not found
Could anyone help me understand where I'm going wrong?
Thanks a lot

Of course, after I've made a SO post I find the answer.
For anyone having the same issues you must encode your :objectName, which is just the filename, in my example '--test2.dwg', using PHP's rawurlencode() function rather than urlencode().

Related

Typescript HttpClient.post returning bad request from json formatted string

Ok I have been manipulating this string for hours! So any help is greatly appreciated
I am trying to simply make a post call and generate a password. The api is setup to take in a string a parses the json formatted string itself.
private headers = new HttpHeaders({ 'Content-Type': 'application/json' });
constructor(http: HttpClient) {
var url: string = 'https://eus-safeaccounts-test.azurewebsites.net/' + 'passwords/generate';
var body: string = '"{\"regex\":\"[a-zA-Z0-9]\",\"minLength\":8,\"maxLength\":12}"';
http.post<string>(url, body, { headers: this.headers }).subscribe(result => {
this.signUpResponseStr = result["password"];
}, error => console.error(error));
}
This call returns code 400 bad request. (I think because the text is not being seen as json?)
However, if we set body = '""'; then we get a password sent back from the api no problem. It is seen as an empty string on API side and then they give us a password. Exploring further I tried setting body = '"abc"'; because that is a string not following json format. In this case, we DO NOT get bad request 400, but the api recognizes bad json format and returns Invalid Json
My Question:
What should the body string look like for me to send this request? The API is open so anyone can reproduce and the API code shouldn't have anything to do with the 400 bad request issue, as we can see from my explorations, but the code is here https://github.com/nickpavini/SafeAccountsAPI.
Thanks for any help! :)
EDIT: I also tried sending as JSON type and I also tried JSON.stringify() with no luck
Found it. The string is a bit tricky to understand but hopefully this will help others.
body = '"{\\"regex\\":\\"[a-zA-Z0-9]\\",\\"minLength\\":8,\\"maxLength\\":12}"'
In this case it seems that the body contains a string. (the actual string that will be received by the server)
Inside that string, whenever we need the server to see a " that does not close the string, we must pass an actual backslash \\ and then a ". We do not need 3 backslashes in this case because the single quote ' at the beginning makes sure all paranthesis are included.
Note: Test this with the api in question if it seems weird to you. I think it has to do with the api implementation.
Probably body should not be double quoted, and should look instead like...
var body: string = '{"regex":"[a-zA-Z0-9]","minLength":8,"maxLength":12}'

Getting JSON from HTTP Discord.Js

Im making a discord bot, and I have a URL here which has some raw json: link here and I want one of the values (hashrateString) to be put inside a embed like:
hashrateString: 1GH
is there a way to do that and if so how?
I never tried this with an external link but it should work the same way.
FIRST: write somewhere high up in your code this line
var fs = require('fs');
var data = JSON.parse(fs.readFileSync('http://ric.pikapools.com/api/stats', 'utf8'));
After you can basically do whatever you want with your new object. There was no hashrateString: 1GH, but hashrateString: 4.68 GH should be accessible with data.algos.primesr.hashrateString (Output: 4.68 GH)
If it, for some weird reason, doesn't accept an URL, just try to copy&paste the text in a json file if possible, and use the path to it
I was able to get this to work by specifying a constant to be the JSON from the url using node-fetch
const ricp = await fetch('http://ric.pikapools.com/api/stats').then(response => response.json());
and find an object in the JSON using
message.channel.send(ricp.algos.primesr.hashrateString)

Angular 4 html for loop displaying loosely typed object (string) normally but not when element is extracted directly?

I'm using Angular 4 to develop an app which is mainly about displaying data from DB and CRUD.
Long story short I found that in Angular 4 the component html doesn't like displaying loosely typed object (leaving the space blank while displaying other things like normal with no warning or error given in console) even if it can be easily displayed in console.log output, as shown in a string.
So I made a function in the service file to cast the values into a set structure indicating they're strings.
So now something like this works:
HTML
...
<div>{{something.value}}</div>
...
Component.ts
...
ngOnInit() {
this.route.params.subscribe(params => {
this.pkey = params['pkey'];
this.service.getSomethingById(this.pkey)
.then(
something => {
this.something = this.service.convertToStructure(something);
},
error => this.errorMessage = <any>error);
});
}
...
Code of the function convertToStructure(something)
convertToStructure(someArr: myStructure): myStructure {
let something: myStructure = new myStructure();
something.value = someArr[0].value;
return something;
}
But as I dig into other files for copy and paste and learn skills from what my partner worked (we're both new to Angular) I found that he did NOT cast the said values into a fixed structure.
He thought my problem on not being able to display the values (before I solved the problem) was because of me not realizing it was not a plain JSON object {...} but an array with a single element containing the object [{...}] .
He only solved half of my problem, cause adding [0] in html/component.ts was not able to make it work.
Component.ts when it did NOT work
...
ngOnInit() {
this.route.params.subscribe(params => {
this.pkey = params['pkey'];
this.service.getSomethingById(this.pkey)
.then(
something => {
console.log(something[0].value); //"the value"
this.something = something[0]; //html can't find its value
},
error => this.errorMessage = <any>error);
});
}
...
HTML when it did NOT work
...
<div>{{something[0].value}}</div> <!--Gives error on the debug console saying can't find 'value' of undefined-->
...
And of course when I'm using the failed HTML I only used this.something = something instead of putting in the [0], and vice versa.
So I looked into his code in some other page that display similar data, and I found that he used *ngFor in html to extract the data and what surprised me is that his html WORKED even if both of our original data from the promise is identical (using the same service to get the same object from sever).
Here's what he did in html:
...
<div *ngFor="let obj of objArr" ... >
{{obj.value}}
</div>
...
His html worked.
I'm not sure what happened, both of us are using a raw response from the same service promise but using for loop in html makes it automatically treat the value as strings while me trying to simply inject the value fails even if console.log shows a double quoted string.
What's the difference between having the for loop and not having any for loop but injecting the variable into html directly?
Why didn't he have to tell Angular to use the set structure indicating the values are strings while me having to do all the trouble to let html knows it's but a string?
The difference here is as you said that your JSON is not simple object , its JSON Array and to display data from JSON array you need loop. So, that is why your friends code worked and yours did not. And please also add JSON as well.

JSON.parse returning undefined object

Blizzard just shut down their old API, and made a change so you need an apikey. I changed the URL to the new api, and added the API key. I know that the URL is valid.
var toonJSON = UrlFetchApp.fetch("eu.api.battle.net/wow/character/"+toonRealm+"/"+toonName+"?fields=items,statistics,progression,talents,audit&apikey="+apiKey, {muteHttpExceptions: true})
var toon = JSON.parse(toonJSON.getContentText())
JSON.pase returns just an empty object
return toon.toSorce() // retuned ({})
I used alot of time to see if i could find the problem. have come up empty. Think it has something to do with the "responce headers".
Responce headers: http://pastebin.com/t30giRK1 (i got them from dev.battle.net (blizzards api site)
JSON: http://pastebin.com/CPam4syG
I think it is the code you're using.
I was able to Parse it by opening the raw url of your pastebin JSON http://pastebin.com/raw/CPam4syG
And using the following code
var text = document.getElementsByTagName('pre')[0].innerHTML;
var parse = JSON.parse(text);
So to conclude I think it is the UrlFetchApp.fetch that's returning {}
So i found the problems:
I needed https:// in the URL since i found after some hours that i had an SSL error
If you just use toString instead of getContentText it works. Thow why getContentText do not work, i am not sure of.
was same problem, this works for me (dont forget to paste your key)
var toonJSON = UrlFetchApp.fetch("https://eu.api.battle.net/wow/character/"+toonRealm+"/"+toonName+"?fields=items%2Cstatistics%2Cprogression%2Caudit&locale=en_GB&apikey= ... ")

MediaWiki API Extension JSON

I have developed a MediaWiki extension that gets a (JSON) string from an external service using cURL.
Now I'm looking for a way to retrieve just that string from the MediaWiki system. (This URL will be used for AJAX calls.)
First, I thought that MediaWiki API was the way to do that. However, I can't seem to be able to output just that string.
What would be the right way to achieve this?
UPDATE
Thank you, that did the trick. For your information, here's how far I got:
$this->getResult()->addValue(null, null, array( 'autocomplete' => array( 'server', 'servers' ) ) );
returns [{"autocomplete":["server","servers"]}] when appending format=json to the API URL. Instead of the above JSON string, the JavaScript client I'm working with needs {"autocomplete":["server","servers"]} in order to work correctly. In other words, I needed to get rid of [ and ].
Just out of curiosity, is a custom printer still the way to go?
In your API module, override getCustomPrinter():
public function getCustomPrinter() {
return new ApiFormatRaw(
$this->getMain(),
$this->getMain()->createPrinterByName( 'json' )
);
}
(the nested createPrinterByName() call is for fallback format in case of errors, you can change it to some other format)
Then, in your execute() method or wherever you need to return the value:
$this->getResult()->addValue( null, 'text', $data_you_want_to_return );
$this->getResult()->addValue( null, 'mime', 'application/json' );