I'm attempting to retrieve the data from my fitbit but when I use the GET() function to access JSON I'm getting a 400 Error.
Here is my code:
token_url = "https://api.fitbit.com/oauth2/token"
access_url = "https://api.fitbit.com/oauth2/token"
auth_url = "https://www.fitbit.com/oauth2/authorize"
key = "XXXX"
secret = "XXXX"
fbr = oauth_app("Glinski",key,secret)
fitbit = oauth_endpoint(token_url,auth_url,access_url)
token = oauth2.0_token(fitbit,fbr, scope = c("activity","heartrate"))
And attempting to access JSON with:
GET(url = "http://api.fitbit.com/1/user/-/activities/heartrate/date/2018-01-
01/today.json", config(token = token))
Which results in this:
Response [http://api.fitbit.com/1/user/-/activities/heartrate/date/2018-01-
01/today.json]
Date: 2018-01-20 22:07
Status: 400
Content-Type: application/json
Size: 122 B
Any help is appreciated
Related
We are trying to send and encrypted EDI(Electronic Data Interchange) String along with a digital signature in the form of SMIME to Canada Border Services Agency ,but getting Error everytime we try different approaches.
The request SMIME payload we are sending is :
Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg=sha1;
boundary="----=_Part_0_1964847681.1577187780616"
------=_Part_0_1964847681.1577187780616
Content-Type: application/edi-edifact
Content-Length: 881
UNA:+.?'
UNB+UNOA:3+KAGATEWAY:CBSANETWORKID+191017:0930+REF12345'UNG+CUSDEC+ +IIDT+191017:0930+GREF12345+UN+D:13A:IID'
UNH+MREF12345+GOVCBR:D:13A:UN:IID'
BGM+929+119081234567X+9'
DTM+132:CCYYMMDDHHMMZZZ:303'MOA+134:10000:CAD'
RFF+CN:WXYZ12345678987654321'
GOR++5'LOC+23+0809+3470'
NAD+IM+868929415RM0001++ INC+6955 AVE+NEWARK+CA+94560+US'UNS+D'
SEQ+1'NAD+VN+++ZOY HOME FURNISHING CO+BUILDING 2-5:TANGPU INDUSTRIAL PARK+DIPU,ANJI+ZJ+313301+CN'
NAD+UC+868929415RM0001++ CAN+123 +VANCOUVERBC+V5K1A5+CA'LOC+35+CN'
DTM+757:20191001:102'DOC+380+98027209'SEQ+1'DTM+3:20190901:102'MOA+39:10000CAD'MEA+AAE+AAB+KGM:5000'QTY+47:180:H87'LIN+1'NAD+MF+++ZOY HOME CO+BUILDING 2-5: INDUSTRIAL PARK+DIPU,ANJI+ZJ+313301+CN'
LOC+27+CN'PAC+180+3+BX'SEQ+1'GID+1'
IMD++8+:::METAL +AAE+ABS+KGM:4500'MOA+66:10000CAD'TCC+++9401791000:HS'CNT+51:180:EA'SEQ+1'HYN+3'UNS+S'UNT+20+MREF12345'UNE+1+GREF12345'UNZ+1+REF12345'
------=_Part_0_1964847681.1577187780616
Content-Type: application/pkcs7-signature
Content-Transfer-Encoding: base64
Content-Length: 1640
0�� *�H��
���0��1�u0�q0Y0Q1
0 UCA1
0 U
GC10U
cra-arc10
U
Extern10U
EXTTESTCASd=0
*�H��
� {/d�R'^J��o�����.�M5Q:��^��Ў�2�<�)9a �VS�|O�.�P/�(N�"�IJ��0_HH�m!��I.
j3�a �`����g�4|ll.�M��uVW�8��2�y[�$0_���j
���m�2���uul��9ehqS��N�O����������{m'� >�ϻ��cL���9�R�g�͜����{�O
�h-�UJ��(��W�dԼd\
Q7��|��:����P����0� *�H��
0 *�H��}B
0_.h�U�������"�q�����S �C2X������*a�
�eٲQ��>`˨�?�����|i���a��³ev�
��������`�����cY]�����#�Ӡ(n�o��Jm���!�F?J�1� �6]M�l#]��u֡p�;�Fn����
����w8Dz�Q�
����R�����~h�K��E��
�n{ϬA��3LA=����y�!��?7�h`\[%�y>�%10������� s�-��z=E�,�K�������:��9�?�F��
VpT#A�7�[=�� �y2�w�o:[�"�;���ŗp5�C�uk��qf5l�
Ȑ���:��X��Y1�ς�ˆ?P�]���^�����8�m�:3|���#Qm=0\���r �����X�
q�Eڂz�A�a\1l�D�4,x�V�g79c��)>T�ժ���d:��]<�.ri�#vl����C������|T��l��<;�n�,�H�p~D����;��VN�VT�*�o:���y%�jfh4�S���Pf)>Z����5��L�<�
R���������#�3Ҫ��T�a�nMh6q#cێ���eʯ�p$ƅv����� cb�zQc�&�5li���zg!��
E�)�i�$v��%Y'�
o�zX����q���P�)F��c<�`e�B~
&��SL�J��M��������o�M�K�Q{��<m�|��"�yo��(�%�_���g�����$���NiV�z�u����u��T��_#g���b��r�H��̨�'rw���:n[!�e#
o_�� �l2'2�
�T�Q��7�k7�(�4�e���G"����>{'1b�4,?Y���#)
��u(�ч���ܤ6weMLY��b�f�����8}&��v��?�Ti�R:g$�P5��v�Ž~���
܅��q��RK;��
*"N�G�O�[R����>��Cm8o懏�e�T_
------=_Part_0_1964847681.1577187780616--
The exception is:
Response code : 400
Response Message : Bad Request
Error Message : 400 BAD REQUESTYour transaction <<393BDE.000003.00179#yourhost.yourcompany.com>> could not be processed due to the following error(s):
java.io.IOException: Unexpected response code received from servlet: 400
EERROR 2207:Smime does not conains 2 body parts
END: Communication with servlet
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)--
If anyone has worked with CBSA or worked with entrust or EDI ..please help we are stuck
Any help related to the exception in SMIME will also be really helpful
The code I m using is:
mbp1.addHeader("Content-Length", String.valueOf(testMessage.length()));
PropUtil.getBooleanSystemProperty("mail.mime.multipart.ignoreexistingboundaryparameter", true);
// contentType = new ContentType("multipart","mixed",pml);
// contentType.setParameter("boundary", getBoundary());
//
// contentType1 = new ContentType("multipart","mixed",pml1);
// contentType1.setParameter("boundary", getBoundary());
//
// contentType2 = new ContentType("multipart","mixed",pml2);
// contentType2.setParameter("boundary", getBoundary());
// contentType = type.toString();
MimeMultipart mimeMultipart = new MyMimEMultipart("signed");
SMimeBodyPart ediEdiPart = new SMimeBodyPart();
ByteArrayOutputStream fout = new ByteArrayOutputStream();
fout.write(testMessage.getBytes());
ByteArrayOutputStream encoded = (ByteArrayOutputStream)MimeUtility.encode(fout, "7bit");
byte[] gg = encoded.toByteArray();
InternetHeaders internetHeaders = new InternetHeaders();
internetHeaders.addHeader("Content-Type", "application/edi-edifact");
internetHeaders.addHeader("Content-Length", String.valueOf(gg.length));
internetHeaders.addHeader("Content-Transfer-Encoding","7-bit");
SMimeBodyPart newthing= new SMimeBodyPart(internetHeaders,gg);
ByteArrayOutputStream consoleStream = new ByteArrayOutputStream();
newthing.writeTo(consoleStream);
// consoleStream.writeTo(System.out);
FileOutputStream f= new FileOutputStream("/Users/lakshyakumarsingh/Documents/kx-github/kn-cbsaproxy/src/main/resources/test1_decode.txt");
f.write(consoleStream.toByteArray());
// System.out.println("this is the input");
// System.out.println(consoleStream.toString("US-ASCII"));
// ediEdiPart.setHeader("Message-ID","29123185.1.1449072497221.JavaMail.axg129#WH12CU10178A");
// ediEdiPart.setHeader("Content-Type", "application/edi-edifact");
// int contentlength = testMessage.length();
ediEdiPart.setDataHandler(dataHandler);
// ediEdiPart.setText(finalString);
// ediEdiPart.setHeader("Content-Transfer-Encoding", "binary");
ediEdiPart.setHeader("Content-Length", String.valueOf(testMessage.length()));
// ediEdiPart.setContent(testMessage, "application/edi-edifact");
// mimeMultipart.setParent(PART.);
// System.out.println("contetnt type is : " + contentType.toString());
mimeMultipart.setSubType("signed");
mimeMultipart.setPreamble(
"Content-Type: multipart/signed; protocol=\"application/pkcs7-signature\"; micalg=sha1; \n" +
"\tboundary=\"----=_Part_0_1964847681.1577187780616\"");
mimeMultipart.addBodyPart(newthing);
SMimeBodyPart mbp2 = new SMimeBodyPart();
mbp2.addHeader("Content-Type", "application/pkcs7-signature");
mbp2.addHeader("Content-Transfer-Encoding", "binary");
// mbp2.addHeader("Content-Description", "S/MIME Cryptographic Signature");
Having a bit of trouble getting a gzipped JSON payload with python 3
def post_data ( data ) :
method_name = json.loads(data)['subject'][4][0][1]
instance = json.loads(data)['serialNumber']
timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
utc_now = datetime.datetime.utcnow().strftime("%m-%d-%Y %H:%M:%S")
not_after = datetime.datetime.strptime(json.loads(data)['notAfter'], "%b %d %H:%M:%S %Y GMT" ).strftime("%m-%d-%Y %H:%M:%S")
days = datetime.datetime.strptime(not_after, "%m-%d-%Y %H:%M:%S")-\
datetime.datetime.strptime(utc_now, "%m-%d-%Y %H:%M:%S")
values = days.days
raw_json = '''{"MetricReports":[{
"Metadata":{
"MinPeriod":"FiveMinute",
"MaxPeriod":"FiveMinute"
},
"Namespace":"Schema/Service",
"Metrics":[{
"Dimensions":{
"DataSet":"NONE",
"Marketplace":"PDX",
"HostGroup":"ALL",
"Host":"host.com",
"ServiceName":"Server",
"MethodName":"%s",
"Client":"ALL",
"MetricClass":"instance",
"Instance":"%s"
},
"MetricName":"daysToExpiry",
"Timestamp":"%s",
"Type":"MetricsLine",
"Unit":"None",
"Values":%s
}
]}
]}''' %(method_name, instance, timestamp, values)
headers = {'content-type' : 'application/x-gzip'}
putUrl = 'http://api-pdx.com/'
session = boto3.Session()
credentials = session.get_credentials()
region = 'us-west-2'
service = 'monitor-api'
auth = AWS4Auth(
credentials.access_key,
credentials.secret_key,
region,
service,
session_token = credentials.token)
r = requests.post(url = putUrl, json = gzip.compress(raw_json) , auth = auth, headers = headers, verify=False)
print(r.content)
get_data()
post_data(data)
I need to compress the raw_json because the API is expecting a gzipped attachment. The API is spitting back "The HTTP request is invalid. Reason: Invalid JSON attachment:Not in GZIP format" if I attempt to send the JSON as is.
I tried the gzip.compress, but it says : memoryview: a bytes-like object is required, not 'str'
so I tried gzip.compress(json.dumps(raw_json).encode('utf-8')) and that says Object of type bytes is not JSON serializable
To send a binary data with requests.post method they should be passed as data argument, not as json:
requests.post(url = putUrl,
data = gzip.compress(json.dumps(raw_json).encode('utf-8')),
auth = auth,
headers = headers,
verify=False)
I am trying to link my django web app to Azure ML API. I do have Django form with all the required inputs for my Azure API.
def post(self,request):
form = CommentForm(request.POST)
url = 'https://ussouthcentral.services.azureml.net/workspaces/7061a4b24ea64942a19f74ed36e4b438/services/ae2c257d6e164dca8d433ad1a1f9feb4/execute?api-version=2.0&format=swagger'
api_key = # Replace this with the API key for the web service
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
if form.is_valid():
age = form.cleaned_data['age']
bmi = form.cleaned_data['bmi']
args = {"age":age,"bmi":bmi}
json_data = str.encode(json.dumps(args))
print(type(json_data))
r= urllib.request.Request(url,json_data,headers)
try:
response = urllib.request.urlopen(r)
result = response.read()
print(result)
except urllib.request.HTTPError as error:
print("The request failed with status code: " + str(error.code))
print(json_data)
# Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
print(error.info())
print(json.loads(error.read()))
return render(request,self.template_name)
When i try to submit the form i am getting type error -
TypeError('POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.',)
Getting status code - 400 and below error
{'error': {'code': 'BadArgument', 'message': 'Invalid argument provided.', 'details': [{'code': 'RequestBodyInvalid', 'message': 'No request body provided or error in deserializing the request body.'}]}}
Arguments are using print(json_data) -
b'{"age": 0, "bmi": 22.0}'
Can someone help me on this?
Try to use JsonResponse:
https://docs.djangoproject.com/en/2.1/ref/request-response/#jsonresponse-objects
Also, I don't think you need a template for API response.
return JsonResponse({'foo': 'bar'})
Thanks all. I found the error it was the data which was not in proper order.
I am working on Instagram API in Django(python)
I am getting code from
'https://api.instagram.com/oauth/authorize/?client_id=%s&response_type=code&redirect_uri=%s' % (INSTAGRAM_APP_CONSUMER_KEY, redirect_uri)
but when i am exchanging code for access token code is failing
# All arguments are valid
def execute(self, code, redirect_uri, app_id, app_secret):
exchange_url = 'https://api.instagram.com/oauth/access_token'
try:
#Update : get request to post
r = requests.post(exchange_url, params={
'client_id': app_id,
'redirect_uri': redirect_uri,
'client_secret': app_secret,
'code': code,
'grant_type': 'authorization_code'
})
#print(r)
#print(json.loads(r))
print(r.json())
return r.json()
except Exception as e:
print(e)
r.json() gives simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1
Update 1 : r.json() works after request changed from get to post but error
message comming 'You must provide a client_id'
Please let me know what i am doing wrong
I think it requires data in post data, not in query params.
Try this :
your_post_data = {'client_id': '', ... }
r = requests.post('your_url', data=your_post_data)
Ref: Python Requests Docs
hi i have found a tutorial on how to use post json in lua.
here is the code :
http = require("socket.http")
crypto = require("crypto")
ltn12 = require("ltn12")
url = require("socket.url")
local json = require("json")
local commands_json =
{
["message"] = "Hello",
}
print (commands_json)
local json = {}
json.api_key = "6_192116334"
json.ver = 1
json.commands_json = json.encode(commands_json)
json.commands_hash = crypto.digest(crypto.md5, json.commands_json .. 'hkjhkjhkjh')
local post = "api=" .. url.escape(Json.Encode(json))
local response = {}
local r, c, h = http.request {
url = "http://127.0.0.1/?page=api",
method = "POST",
headers = {
["content-length"] = #post,
["Content-Type"] = "application/x-www-form-urlencoded"
},
source = ltn12.source.string(post),
sink = ltn12.sink.table(response)
}
local path = system.pathForFile("r.txt", system.DocumentsDirectory)
local file = io.open (path, "w")
file:write (Json.Encode(json) .. "\n")
file:write (post .. "\n")
file:write (response[1] .. "\n")
io.close (file)
json = Json.Decode(table.concat(response,''))
native.showAlert("hey", json.commands[1].tot_nbr_rows)
now i got these error:
Windows simulator build date: Dec 9 2011 # 14:01:29
Copyright (C) 2009-2011 A n s c a , I n c .
Version: 2.0.0
Build: 2011.704
table: 0346D6D0
Runtime error
...nistrator\my documents\corona projects\json\main.lua:17: attempt to c
all field 'encode' (a nil value)
stack traceback:
[C]: in function 'encode'
...nistrator\my documents\corona projects\json\main.lua:17: in main chun
k
Runtime error: ...nistrator\my documents\corona projects\json\main.lua:17: attem
pt to call field 'encode' (a nil value)
stack traceback:
[C]: in function 'encode'
...nistrator\my documents\corona projects\json\main.lua:17: in main chun
k
i don't know why i got the error from encode.
can anyone can help me about my case?
thanks in advance ...
This includes the Json code provided externally, likely with an encode function:
local json = require("json")
This throws away your old json variable and replaces it with an empty table:
local json = {}
And this tries to call json.encode which is now undefined since you redefined json as an empty table above:
json.commands_json = json.encode(commands_json)
The solution is to pick a different variable name.