I'm still relatively new to Python and my first time to use aiohttp so I'm hoping someone can help spot where my problem is.
I have a function that does the following:
retrieves from the JSON payload two base64 strings - base64Front and base64Back
decode them, save to "images" folder
send the Front.jpg and Back.jpg to an external API
this external API expects a multipart/form-data
imgDataF = base64.b64decode(base64FrontStr)
frontFilename = 'images/Front.jpg'
with open(frontFilename, 'wb') as frontImgFile:
frontImgFile.write(imgDataF)
imgDataB = base64.b64decode(base64BackStr)
backFilename = 'images/Back.jpg'
with open(backFilename, 'wb') as backImgFile:
backImgFile.write(imgDataB)
headers = {
'Content-Type': 'multipart/form-data',
'AccountAccessKey': 'some-access-key',
'SecretToken': 'some-secret-token'
}
url = 'https://external-api/2.0/AuthenticateDoc'
files = [('file', open('./images/Front.jpg', 'rb')),
('file', open('./images/Back.jpg', 'rb'))]
async with aiohttp.ClientSession() as session:
async with session.post(url, data=files, headers=headers) as resp:
print(resp.status)
print(await resp .json())
The response I'm getting is status code 400 with:
{'ErrorCode': 1040, 'ErrorMessage': 'Malformed/Invalid Request detected'}
If I call the url via Postman and send the two jpg files, I get status code 200.
Hope someone can help here.
Thanks in advance.
Try using FormData to construct your request. Remove the content type from header and use it in FormData field as below:
data = FormData()
data.add_field('file',
open('Front.jpg', 'rb'),
filename='Front.jpg',
content_type='multipart/form-data')
await session.post(url, data=data)
Reference: https://docs.aiohttp.org/en/stable/client_quickstart.html#post-a-multipart-encoded-file
Related
I have code that calls a vendor API to do a formdata upload of a file by axios from inside an AWS Lambda. The call returns a 400 error. If I run the code locally using the same node version v14 it works. I want to capture both raw requests and compare them for differences. How do I capture both raw requests? I've tried using ngrok and pipedream but they don't show the raw but decode the request and the file.
let response = null;
try {
const newFile = fs.createReadStream(doc);
const formData = new FormData();
formData.append("file", newFile);
formData.append("url", url);
const headers = {
Authorization: "Bearer " + token,
...formData.getHeaders(),
};
console.log("Headers: ", headers);
response = await axios.post(`${APIBASE}/file/FileUpload`, formData, {
headers,
});
console.log("file upload response", response);
} catch (err) {
console.log("fileupload error at API", err);
}
You might be able to just use a custom request interceptor and interrogate at the requests that way.
https://axios-http.com/docs/interceptors
You're not able to capture the request on the network level, as this is totally controlled by AWS. Maybe there's a way to do this when running in a VPC, but I don't think so.
You could simply use a tool such as axios debug logger to print out all of the request and response contents (including headers etc) before the request is made/after the response has arrived. This might provide some more information as to where things are going wrong.
As to the cause of the problem, it is difficult to help you there since you haven't shared the error message nor do we know anything about the API you're trying to call.
There are multiple ways to debug
axios debug logger .
AWS cloud watch where you can see all the logs. you can capture the request
and response.
Use postman to call the prod lambda endpoint and verify the response.
https://github.com/smart-on-fhir/bulk-import/blob/master/import.md
I used above link for reference and tried to run import using the following code
import requests
url = "https://<fhir-server-name>.azurehealthcareapis.com/$import"
payload = "{\r\n\t\"inputFormat\": \"application/fhir+ndjson\",\r\n\t\"inputSource\": \"https://localhost\",\r\n\t\"storageDetail\": { \"type\": \"https\" },\r\n\t\"input\": [\r\n\t{\r\n\t\t\"type\": \"Patient\",\r\n\t\t\"url\": \"https://localhost/patient_ndjson.ndjson\"\r\n\t}\r\n\t]\r\n}"
headers = {
'Accept': 'application/fhir+json',
'Prefer': 'respond-async',
'Content-Type': 'application/json',
'Authorization': 'Bearer <Auth Token>'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
i am receiving 400 Bad Request . i tried posting to both
url = "https://<fhir-server-name>.azurehealthcareapis.com/$import"
url = "https://<fhir-server-name>.azurehealthcareapis.com/Patient/$import"
I used apache for hosting the file and the file is accessible with both http and https.. Instead of importing it using http server, is there any way to directly point to my local ndjson file ?
patient_ndjson.ndjson contains
{"resourceType":"Patient","id":"8c76dfe7-2b94-497b-9837-8315b150ac0e","meta":{"versionId":"1","lastUpdated":"2020-04-27T11:08:10.611+00:00"},"active":true,"name":[{"use":"official","family":"p000001"}],"gender":"female","birthDate":"2020-04-27T11:00:00+05:30"}
{"resourceType":"Patient","id":"bfab05c7-d36a-4b5a-a0d6-6efb1da0fb3d","meta":{"versionId":"1","lastUpdated":"2020-04-27T11:34:43.83+00:00"},"active":true,"name":[{"use":"official","family":"p000001"}],"gender":"female","birthDate":"2020-04-27T11:00:00+05:30"}
{"resourceType":"Patient","id":"4c314eb1-6309-424b-affc-197fb0131cf6","meta":{"versionId":"1","lastUpdated":"2020-04-27T12:09:20.777+00:00"},"active":true,"name":[{"use":"official","family":"p000002"}],"gender":"female","birthDate":"2020-04-27T03:00:00+05:30"}
Can you please provide some sample request . it would be helpful.
$import is a draft spec and it is not supported (yet) on the Azure API for FHIR.
I am trying to download a zip fie which is returned as binary in the response of a AJAX Request.
I tried the following code but was not able to download it and even if I downloaded it the file got corrupted. I checked whether the response is correct and went to the network tab in developer tool and saved the response as a zip file and opened it, and it was successfully opened.
Hopefully someone can tell me what I am doing wrong.
var URL = window.URL;
var downloadData = new Blob([data._body], { type: 'application/octet-stream' });
var downloadURL = URL.createObjectURL(downloadData);
window.open(downloadURL);
the browser openes up a new window and tells me the file is not supported in IE & downloads a corrupted file in Chrome. The URL in browser is something like
blob:http://localhost:4200/62b8283c-1391-4133-98a4-ed3cc9aa1f73
-
var downloadData = new Blob([data._body], { type: 'application/zip' });
FileSaver.saveAs(downloadData,"hi.zip");
The above code does not give any specific errors but when the file is saved it is corrupted.
I also tried the above code with type as application/octet-stream but that has the same result.
Thing is the binary data seems to be perfectly fine, the only thing I need to do is open a save dialog which will save the binary data. Seems to be a pretty simple usecase, but seems to be a bit confusing in case of zip in the Js/TS side.
I think the main issue is that I am creating a blob with the binary data(which I don't think I need to or should be transforming to a blob) but I was not able to trigger the download without creating a blob object as the APIs seem to be accepting only blob(like the URL Object or FileSaver API).
I had the exact same problem, the zip file was corrupt when I was trying to open it.
I fixed it by adding: responseType = ResponseContentType.ArrayBuffer
Here is my code:
public httpRequest(call) {
call.headers = new Headers({
'Authorization': 'Bearer ' + localStorage.getItem('id_token'),
'Content-Type': 'application/json',
'Accept': 'application/octet-stream'
});
let req = new Request(call);
req.responseType = ResponseContentType.ArrayBuffer;
return this.http.request(req).map((res: Response) => {
return res;
});
}
make sure you imported:
import { Http, Headers, Request, Response, BaseResponseOptions, ResponseContentType } from '#angular/http';
I am able to successfully POST from AngularJS to my Sinatra route such that I get a "200" Status.
When I inspect in Chrome, I see the request payload as follows:
{"input":"testing"}
But response is empty.
Here is how I am POST-ing:
$http({
method: "POST",
url: "http://floating-beyond-3787.herokuapp.com/angular",
/*url: "https://worker-aws-us-east-1.iron.io/2/projects/542c8609827e3f0005000123/tasks/webhook?code_name=botweb&oauth=LOo5Nc0x0e2GJ838_nbKoheXqM0",*/
data: {input: $scope.newChat}
})
.success(function (data)
{
// $scope.chats.push(data);
$scope.chats.push($scope.newChat)
// if successful then get the value from the cache?
})
.error(function (data)
{
$scope.errors.push(data);
});
};
$scope.newChat = null
Chrome under Request Payload shows it properly -- as above.
When I check the logs in Heroku where I run my Sinatra app, I can't tell if I am properly processing the request payload. And I'm definitely not getting anything in the Response:
post '/angular' do
puts "params: #{params}"
puts params[:input]
puts #json = JSON.parse(request.body.read)
return RestClient.post 'https://worker.io' {:send => params[:input]}
end
My expectation is:
The Sinatra app can receive the payload :input
It can successfully post to my worker on iron.io
It can return something back in the Response to Angular JS along with Success.
Is this possible and if so, how?
Possibly you are running into a case where the request.body has already been read further up the chain before hitting your route.
Try the following
request.body.rewind
request_payload = JSON.parse request.body.read
This is a fairly common issue encountered in Sinatra so if this addresses your issue you may want to put it in a before filter.
before do
request.body.rewind
#request_payload = JSON.parse request.body.read
end
Also the following will not work with a JSON payload.
params[:input]
The params[:field] style works if the Content-Type is application/x-www-form-urlencoded to allow accessing form data in a traditional web application style. It also works to pull params off a parameterized route; something like the following.
post '/angular/:data'
puts params[:data]
# Do whatever processing you need in here
# assume you created a no_errors var to track problems with the
# post
if no_errors
body(json({key: val, key2: val2, keyetc: valetc}))
status 200
else
body(({oh_snap: "An error has occurred!"}).to_json) # json(hash) or hash.to_json should both work here.
status 400 # Replace with your appropriate 4XX error here...
end
end
Something I did recently was to use this last style post 'myroute/:myparam and then Base64 encode a JSON payload on the client side and send it in the URL :myparam slot. This is a bit of a hack and is not something I would recommend as a general practice. I had a client application that could not properly encode the JSON data + headers into the request body; so this was a viable workaround.
I am trying to post an image using the source parameter (Multipart/form-data) in the Graph API explorer. My source parameter looks like this:
{Content-Type: multipart/form-data; boundary=xxxsrixxx
--xxxsrixxx
Content-Disposition: attachment; filename=try2.gif
Content-Type: image/gif
Content-Transfer-Encoding: binary,base64
R0lGODlhXgExAYeAAQAAAAEBAQICAgMDAwQEBAUFBQYGBgcHBwgICAkJCQoKCgsLCwwMDA0NDQ4ODg8PDxAQEBERERISEhMTExQUFBUVFRYWFhcXFxgYGBkZGRoaGhsbGxwcHB0dHR4eHh8fHyAgICEhISIiIiMjIyQkJCUlJSYmJicnJygoKCkpKSoqKisrKywsLC0tLS4uLi8vLzAwMDExMTIyMjMzMzQ0NDU1NTY2Njc3Nzg4ODk5OTo6Ojs7Ozw8PD09PT4+Pj8/P0BAQEFBQUJCQkNDQ0REREVFRUZGRkdHR0hISElJSUpKSktLS0xMTE1NTU5OTk9PT1BQUFFRUVJSUlNTU1RUVFVVVVZWVldXV1hYWFlZWVpaWltbW1xcXF1dXV5eXl9fX2BgYGFhYWJiYmNjY2RkZGVlZWZmZmdnZ2hoaGlpaWpqamtra2xsbG1tbW5ubm9vb3BwcHFxcXJycnNzc3R0dHV1dXZ2dnd3d3h4eHl5eXp6ent7e3x8fH19fX5+fn9/fzL/oICAgIGBgYKCgoODg4SEhIWFhYaGhoeHh4iIiImJiYqKiouLi4yMjI2NjY6Ojo+Pj5CQkJGRkZKSkpOTk5SUlJWVlZaWlpeXl5iYmJmZmZqampubm5ycnJ2dnZ6enp+fn6CgoKGhoaKioqOjo6SkpKWlpaampqenp6ioqKmpqaqqqqurq6ysrK2tra6urq+vr7CwsLGxsbKysrOzs7S0tLW1tba2tre3t7i4uLm5ubq6uru7u7y8vL29vb6+vr+/v8DAwMHBwcLCwsPDw8TExMXFxcbGxsfHx8jIyMnJycrKysvLy8z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LwE8RMAgOs3deCFcDUgQPuwAfGAIODE7jtAKflAUdkvd7qKJA556ShHRGaMCkTAKclAUCvDZRbGXjPHh6QIFRuAEnCHGVpGYS8GrBiMGffAFbtAGTbCtiUxY1RIAZSCPlTECquAMXRAIuNAHiHDRSxEH/AIDMkMqVe0YSTgsALguBtECu6YtuvopRXDh1XJQVI4Q1mAHfzAECtAApPcAKCAGoU11XxFpldGvvRGnX94RYIIIwHCrXD4szzvn/VHcfG4d7vK1fy4feeI96NqB48OSn4ZeHgSVLku06OwhLyMH6eZR6JQOHdd06evh55oeHJze6bpRLlYhqqD+Heq8I3ta6uUhDC1wA6H5kKq+HoLAARKACLaQDDDwMLG+67ze677+68Ae7MI+7MRe7MZ+7Mie7Mq+7Mze7M7+7NAe7dKOKAAAIf8LUElBTllHSUYxLjAWSW1hZ2UgZnJvbSBjbGlwYm9hcmQBIAA7
--xxxsrixxx--}
This always seems to return
{
"error": {
"message": "(#324) Requires upload file",
"type": "OAuthException",
"code": 324
}
}
Few questions:
Does facebook source parameter accept base64 encoded image data?
Has anyone tried using the source parameter in the graph api explorer and have a working sample?
should the source param value should be url-encoded?
Note: My access token has all the required permissions and if i am not wrong, my encoding seems to be wrong. The base64 encoded text above is a complete image and i could decode it and get the image.
Ok. This is going to sound crazy. After a week of trying I was able to post an image successfully to the facebook wall. The fix was to send the raw binary data as it is (no base64 encoding - fb does not like it) and make sure your multipart/form-data is correct. For instance, if you boundary is defined as "boundary=--xxxsrixxx" your actual request should look like this "----xxxsrixxx\r\nContent-Disposition......\r\n----xxxsrixxx"
This works fine for me, it only uses native JavaScript features and a file input:
const fileReader = new FileReader();
const file = document.getElementById('imageInput').files[0];
fileReader.onloadend = async () => {
const photoData = new Blob([fileReader.result], {type: 'image/jpg'});
const formData = new FormData();
formData.append('access_token', pageAccessToken);
formData.append('source', photoData);
formData.append('message', 'some status message');
let response = await fetch(`https://graph.facebook.com/${pageId}/photos`, {
body: formData,
method: 'post'
});
response = await response.json();
console.log(response);
};
fileReader.readAsArrayBuffer(file);
More information: http://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-with-formdata/