Wifi REST API GET call - how to concatenate and pass URL parameters? - api

I'm not too familiar with the arduino c+ language, but I would like to get this native code to work.
In curl this works:
curl "http://access.alchemyapi.com/calls/text/TextGetTextSentiment?text=i+feel+great&outputMode=json&apikey=my-apikey"^C
So I am trying to use a WiFi client for the same request but it seems the passing and parsing of the URL parameters is causing a problem.
sprintf(request,"/calls/text/TextGetTextSentiment?apikey=%s&text=%s&outputMode=%s","31adba6dfc3a879b88762f50efc9f892bd573207", "i+feel+great", "json");
Serial.println(request);
When I print the request, everything after the & gets truncated.
char serverName[] = "access.alchemyapi.com";
if(client.connect(serverName,port) == 1)
{
sprintf(outBuf,"GET %s HTTP/1.1",page);
client.println(outBuf);
sprintf(outBuf,"Host: %s",serverName);
client.println(outBuf);
client.println(F("Connection: close\r\n"));
}
This works (HTTP status 200, though with missing parameters error from the API service) if I only pass in 1 parameter.

Related

api request problem response 500 from backend

All welcome, I ran into a problem in which at the time of passing id and body in the method it is received, it gives 500 errors. In swagger I have an infected method, it looks like this:
swagger
Accordingly, in the body of the request, I pass all the parameters of the fields it needs (I drive them in strictly, just to check for operability):
code
In response I get this:
response
If you try to do the same in the swagger, then the method works and a 200 response comes:
swagger 200 response
What am I doing wrong?
I tried to make the code asynchronous, I tried to pass fields in different ways, but nothing happens, the answer comes 500
Try to put the id field inside the obj.
const form = {
id: 790,
...
}
You are passing too much params inside the callback (id, form).

Mule 4: uriParams size is showing as 0 even though it is there

So I created a endpoint inside the raml file such as:
/proxy:
/{proxyDestinationTarget}:
uriParameters:
proxyDestinationTarget:
type: string
example: "myurl.com"
post:
description: Pass through operation that targets IAA
is: [client-credentials-required,standard-error-responses,traceHeaders]
and then inside of the logic.xml in my variable component I have
attributes.uriParams.'proxyDestinationTarget'
when I send the request in postman and debug i am getting a uriParams size of 0
the url i entered in postman is
https://localhost:8092/proxy/uat.something.somethingElse.com/Assign/Assignment.svc
but if i send a request like this :
https://localhost:8092/proxy/uat.something.somethingElse.com
I get a uriParam size = 1 which is what I want. I guess the / is whats causing the problem. how can I pass url as uri param with escape characters???
It looks like you are not sending an URL that matches the RAML definition in the first case.
For the URL:
https://localhost:8092/proxy/uat.something.somethingElse.com/Assign/Assignment.svc
The RAML defined that the API should expect /proxy/{proxyDestinationTarget} but it is receiving something like /proxy/{proxyDestinationTarget}/Assign/Assignment.svc, where {proxyDestinationTarget} is uat.something.somethingElse.com, but nothing matches /Assign/Assignment.svc. The API should include those two last components too to match. It is not escaping them, they probably need to be defined.

Porting Cryptsy authenticatedAPI to Python 3

I am trying to port a class I use to connect to Cryptsy's authenticated API to Python 3.3. I have managed to solve the data type issues, and am getting something that is at least getting a request from the website, but it is rejecting my authentication, this is the code, API keys are not included, for obvious reasons...:
req['method'] = method
req['nonce'] = int(time.time())
post_data = urllib.parse.urlencode(req)
sign = hmac.new(self.Secret, str.encode(post_data), hashlib.sha512).hexdigest()
headers = {
'Sign': sign,
'Key': self.APIKey
}
print('headers: ',headers)
print('post data: ',post_data)
b=urllib.parse.urlencode(headers)
print(b)
test=post_data + '&'+ b
print('test: ',test)
data=test.encode()
print('data: ',data)
ret = urllib.request.urlopen(urllib.request.Request('https://www.cryptsy.com/api', data))
q=ret.read()
w=q.decode()
e=json.loads(w)
return self.post_process(e)
And this is the response from the server:
{'error': 'Unable to Authorize Request - Check Your Post Data', 'success': '0'}
Thanks.
The original script had the DATA and HEADERS components for the Request, but was somehow formatted in a way that confused Python 3 into thinking the HEADERS part was a TIMEOUT argument, and throwing an error about it needing to be an INT. This sent me on a wild goose chase of trying to concatenate the DATA and HEADERS.

Problems Connecting to MtGox API 2 with Python

I am writing a trading program that I need to connect to MtGox (a bitcoin exchange) through the API v2. But I keep getting the following error:
URL: 1 https://data.mtgox.com/api/2/BTCUSD/money/bitcoin/address
HTTP Error 403: Forbidden.
Most of my script is a direct copy from here (that is a pastebin link). I just had to change it to work with Python 3.3.
I suspect that it has to do with the part of script where I use base64.b64encode. In my code, I have to encode my strings to utf-8 to use base64.b64encode:
url = self.__url_parts + '2/' + path
api2postdatatohash = (path + chr(0) + post_data).encode('utf-8') #new way to hash for API 2, includes path + NUL
ahmac = base64.b64encode(str(hmac.new(base64.b64decode(self.secret),api2postdatatohash,hashlib.sha512).digest()).encode('utf-8'))
# Create header for auth-requiring operations
header = {
"User-Agent": 'Arbitrater',
"Rest-Key": self.key,
"Rest-Sign": ahmac
}
However, with the other guy's script, he doesn't have too:
url = self.__url_parts + '2/' + path
api2postdatatohash = path + chr(0) + post_data #new way to hash for API 2, includes path + NUL
ahmac = base64.b64encode(str(hmac.new(base64.b64decode(self.secret),api2postdatatohash,hashlib.sha512).digest()))
# Create header for auth-requiring operations
header = {
"User-Agent": 'genBTC-bot',
"Rest-Key": self.key,
"Rest-Sign": ahmac
}
I'm wondering if that extra encoding is causing my header credentials to be incorrect. I think this is another Python 2 v. Python 3 problem. I don't know how the other guy got away without changing to utf-8, because the script won't run if you try to pass a string to b64encode or hmac. Do you guys see any problems with what I am doing? Is out code equivalent?
This line specifically seems to be the problem -
ahmac = base64.b64encode(str(hmac.new(base64.b64decode(self.secret),api2postdatatohash,hashlib.sha512).digest()).encode('utf-8'))
To clarify, hmac.new() creates an object to which you then call digest(). Digest returns a bytes object such as
b.digest()
b'\x92b\x129\xdf\t\xbaPPZ\x00.\x96\xf8%\xaa'
Now, when you call str on this, it turns to
b'\\x92b\\x129\\xdf\\t\\xbaPPZ\\x00.\\x96\\xf8%\\xaa'
So, see what happens there? The byte indicator is now part of the string itself, which you then call encode() on.
str(b.digest()).encode("utf-8")
b"b'\\x92b\\x129\\xdf\\t\\xbaPPZ\\x00.\\x96\\xf8%\\xaa'"
To fix this, as turning bytes into a string back into bytes was unnecessary anyhow(besides problematic), I believe this will work -
ahmac = base64.b64encode(hmac.new(base64.b64decode(self.secret),api2postdatatohash,hashlib.sha512).digest())
I believe you are likely to find help in a related question of mine although it deals with the WebSocket API:
Authenticated call to MtGox WebSocket API in Python 3
Also, the HTTP 403 error seems to indicate that there is something fundamentally wrong with the request. Even if you threw the wrong authentication info at the API you should have gotten an error message as a response and not a 403. My best guess is that you are using the wrong HTTP method so check if you are using the appropriate one (GET/POST).

AngularJS resource service with jsonp fails

I'm trying to fetch the JSON output of a rest api in AngularJS. Here are the problems I'm facing:
The Rest api url has the port number in it which is being interpolated by AngularJS for a variable. I tried several resolutions for this in vain.
I'm having issues with JSONP method. Rest api isn't hosted on the same domain/server and hence a simple get isn't working.
The parameters to the rest api are slash separated and not like a HTML query string. One of the parameters is an email address and I'm thinking the '#' symbol is causing some problem as well. I wasn't able to fix this either.
My rest api looks something like: http://myserver.com:8888/dosomething/me#mydomain.com/arg2.
Sample code / documentation would be really helpful.
I struggled a lot with this problem, so hopefully this will help someone in the future :)
JSONP expects a function callback, a common mistake is to call a URL that returns JSON and you get a Uncaught SyntaxError: Unexpected token : error. Instead, JSONP should return something like this (don't get hung up on the function name in the example):
angular.callbacks._0({"id":4,"name":"Joe"})
The documentation tells you to pass JSON_CALLBACK on the URL for a reason. That will get replaced with the callback function name to handle the return. Each JSONP request is assigned a callback function, so if you do multiple requests they may be handled by angular.callbacks._1, angular.callbacks._2 and so forth.
With that in mind, your request should be something like this:
var url = 'http://myserver.com:8888/dosomething/me#mydomain.com/arg2';
$http.jsonp(url + '?callback=JSON_CALLBACK')
.then(function (response) {
$scope.mydata = response.data;
...
Then AngularJS will actually request (replacing JSON_CALLBACK):
http://myserver.com:8888/dosomething/me#mydomain.com/arg2?callback=angular.callbacks._0
Some frameworks have support for JSONP, but if your api doesn't do it automatically, you can get the callback name from the querystring to encapsulate the json.
Example is in Node.js:
var request = require('request');
var express = require('express');
var app = express();
app.get('/', function(req, res){
// do something to get the json
var json = '{"id":4,"name":"Joe"}';
res.writeHead(200, {"Content-Type": "application/javascript"});
res.write(req.query.callback + '(' + json + ')');
res.end();
});
app.listen(8888);
The main issue I was facing here was related to CORS. I got the $http to retrieve the JSON data from the server by disabling the web security in Chrome - using the --disable-web-security flag while launching Chrome.
Regarding the 8888 port, see if this works:
$scope.url = 'http://myserver.com:port/dosomething/:email/:arg2';
$scope.data = $resource($scope.url, {port:":8888", email:'me#mydomain.com',
arg2: '...', other defaults here}, …)
Try escaping the ':'
var url = 'http://myserver.com\:8888/dosomething/me#mydomain.com/arg2';
Pretty sure I read about this somewhere else