PUT requests to upload a file in form data Using karate - karate

I've tried to write equivalent karate script for below curl request
curl -X PUT \
'http://localhost:8055/uploadfile' \
-H 'content-type: multipart/form-data;' \
-F code=#/Users/test/Downloads/Next.zip
Tried karate script
Given path 'uploadfile'
#Given header Content-Type = 'multipart/form-data'
And form field code = '/Users/test/Downloads/Next.zip'
#And multipart file code = { read: '/Users/test/Downloads/Next.zip' , contentType: 'application/zip' }
When method PUT
Then status 200
Am I doing something mistake here (tried different things)? Still not getting expected API response.
FYI : I've got that curl command from postman and it is working fine.

It is hard to tell with the limited info you have provided. Try this:
Given url 'http://localhost:8055/uploadfile'
And multipart file code = { read: 'file:/Users/test/Downloads/Next.zip', filename: 'Next.zip', contentType: 'application/zip' }
When method put
If you are still stuck follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue (or use postman ;)

Related

Unable to convert rest assured test to karate test

I am trying to migrate one of api test to karate framework. However I am unable to write the corrent step defined in karate documentation. Maybe I am missing some basic syntax..but could anyone have any idea how we write following steps in karate feature
requestPostDoc.header("x-api-key","FG6dcYHN9N7PYKfWCUlGo5QGTwZhv2Re1MrDSOTV");//New chnages
requestPostDoc.contentType("multipart/form-data").multiPart("part2-file",file).formParam("part1-json",objDocumentWrite.toJSONString());
requestPostDoc.queryParam("loadProperties",true); //New changes
responseForNewCaseDocFile=requestPostDoc.post("https://vrh0oox3hl.execute-api.eu-central-1.amazonaws.com/default/");//New changes
filterableRequestSpecification = (FilterableRequestSpecification) requestPostDoc;
filterableRequestSpecification.removeQueryParam("loadProperties");
I have written following feature file in karate:
Given url 'https://vrh0oox3hl.execute-api.eu-central-1.amazonaws.com/default/'
And header x-api-key = 'FG6dcYHN9N7PYKfWCUlGo5QGTwZhv2Re1MrDSOTV'
And header Authorization = 'Bearer ' + jwt
And param loadProperties = true
And multipart file info = { read: 'classpath:testData/documentWrite.json', filename: 'documentWrite.json' }
And multipart file Uploading = { read: 'classpath:testData/TextFile.txt', filename: 'TextFile.txt' }
When method post
Then print response
Then status 200
When I execute this test i am getting 400 response code
status code was: 400, expected: 200, response time in milliseconds: 252, url: https://vrh0oox3hl.execute-api.eu-central-1.amazonaws.com/default/?loadProperties=true, response:
Based on the cURL command in the comments, this is my best guess. The rest is up to your research. Read the docs and tweak the Content-Type and other sub-headers if needed. You need to figure this out depending on what your server wants: https://github.com/karatelabs/karate#multipart-file
* multipart file part1-json = { read: 'documentWrite.json' }
* multipart file part2-file = { read: 'TextFile.txt' }
For anyone coming across this question in the future and if you are stuck, get a friend if needed and go through this exercise together: https://github.com/karatelabs/karate/issues/1645#issuecomment-862502881
This stuff can be hard and needs time. There are no short cuts.

Get SQL results from DB2 on cloud to Power Query via API

I try to connect to db2 on cloud via Excel Power Query.
Based on documentation this is format of curl request:
curl -X POST https://hostname.com/dbapi/v4/sql_query_export -H 'authorization: Bearer MyToken' -H 'content-type: text/csv' -d '{"command":"select * from mytable"}'
I tried to go via GUI but this gives me error
I am pretty sure I am not doing it right, but I could not even google how to pass my parameters.
Could someone please navigate how to assembly M code for this?
I tried this according to #nfgl answer
let
body = [#"command"="select * from mytable"]
,json = Json.FromValue(body)
,wc = Web.Contents("https://hostname.com/dbapi/v4/sql_query_export", [Headers=[#"content-type"="text/csv", authorization="Bearer XXX"]])
,Source = Csv.Document(wc,[Delimiter=",", Encoding=65001, QuoteStyle=QuoteStyle.Csv])
in
Source
However cannot go around credentials ui anonymously:
When I try Web API with token:
BTW, everything works with python:
import http.client
conn = http.client.HTTPSConnection("hostname.com")
payload = "{\"command\":\"select * from mytable\"}"
headers = {
'content-type': "text/csv",
'authorization': "Bearer XXX"
}
conn.request("POST", "/dbapi/v4/sql_query_export", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
You can't do it via GUI, command JSON must be in request content, and content-type is the one you send, ie JSON, open advanced editor and do something like this
let
url = "https://showcase.api.linx.twenty57.net/UnixTime/fromunixtimestamp",
body = [#"UnixTimeStamp"= 1589772280, #"Timezone"=""],
json = Json.FromValue(body),
wc = Web.Contents(url, [Headers=[#"Content-Type"="application/json"], Content=json]),
Source = Csv.Document(wc,[Delimiter=",", Encoding=65001, QuoteStyle=QuoteStyle.Csv])
in
Source

Gnome Shell Extension: Send Request with Authorization Bearer Headers

I am trying to build a gnome shell extension (using gjs) that I need to communicate with an external REST API. In order to do so, I need to accompany my requests with the header: Authorization: Bearer <token> and with a Content-Type: application/json.
I have looked all over for questions like this and I did find some similar ones but none of them works. The documentation is not helpful at all, and, if anything, it has only confused me more.
With curl I could send that request as follows:
curl -X GET -H "Authorization: Bearer <token>" -H "Content-Type: application/json" <url>
So far, I have only created extensions that send simple GET requests with no headers. Then I would do the following:
const Soup = imports.gi.Soup;
let soupSyncSession = new Soup.SessionSync();
let message = Soup.Message.new('GET', url);
let responseCode = soupSyncSession.send_message(message);
let res;
if(responseCode == 200) {
res = JSON.parse(message['response-body'].data);
}
Any idea on how I can add the headers? Any help would be appreciated!
EDIT:
By using #ptomato's answer I ended up using the following code:
function send_request(url, type='GET') {
let message = Soup.Message.new(type, url);
message.request_headers.append(
'Authorization',
`Bearer ${token}`
)
message.request_headers.set_content_type("application/json", null);
let responseCode = soupSyncSession.send_message(message);
let out;
if(responseCode == 200) {
try {
out = JSON.parse(message['response-body'].data);
} catch(error) {
log(error);
}
}
return out;
}
Initial Comment:
So, I managed to find a workaround but it is not efficient and so I will not mark it as the accepted answer. If anyone knows how to answer my question using Soup, please answer!
My workaround involves using the imports.misc.util file which includes the function spawnCommandLine for executing shell commands. So, I used curl in order to download the json to a file (the path variable below):
Util.spawnCommandLine(`/usr/bin/curl -X ${type} -H "Authorization: Bearer ${token}" -H "Content-Type: application/json" ${url} -o ${path}`);
and then I read the contents by using the following:
let text = GLib.file_get_contents(path)[1];
let json_result = JSON.parse(text);
This is not efficient at all and there should be an easier way around. But, until that is found, I hope this will be able to help someone else.
message.request_headers is a Soup.MessageHeaders object to which you can append() the authorization and content type headers.
Additionally there is a convenient set_content_type() method for the content type header specifically.

Linking to Fidel API via Flutter http.dart package

probably a basic question, but I'm new to this:
I am trying to link to the Fidel test API environment. They give examples (https://reference.fidel.uk/reference#get-transaction) of how to do this via cURL. In this case the example is:
curl -X GET \
https://api.fidel.uk/v1/transactions/84782884-6ab8-4885-820f-4cd081dd658f \
-H 'Content-Type: application/json' \
-H 'Fidel-Key: sk_test_50ea90b6-2a3b-4a56-814d-1bc592ba4d63'
If I run this in my terminal it works perfectly. But I can't get anything back if I try to run the same in my browser, or if I try to run it via the http.dart package in Flutter, which is where I need it to run eventually.
In Flutter I am writing it as:
void getData() async {
Response response = await get(
"https://api.fidel.uk/v1/transactions/84782884-6ab8-4885-820f-4cd081dd658f \'Content-Type: application/json' \'Fidel-Key: sk_test_50ea90b6-2a3b-4a56-814d-1bc592ba4d63'");
print(response.body);
}
I am sure it's a syntax thing that I don't understand. Any help would be appreciated.
It was just syntax! I solved by saying
Response response = await get(
'https://api.fidel.uk/v1/transactions/84782884-6ab8-4885-820f-4cd081dd658f',
headers: {
'Content-Type': 'application/json',
'Fidel-Key': 'sk_test_50ea90b6-2a3b-4a56-814d-1bc592ba4d63',
});
Will leave here in case anyone else, like me, gets stuck on the basics.

Not a valid base64 image

I'm trying to semd a base64 encoded fimage to the ocr.space api following https://ocr.space/blog/2016/10/ocr-api-supports-base64.html and https://ocr.space/ocrapi . You can see my Postman settings in the screenshot.
However when I submit it I see:
"ErrorDetails": "Not a valid base64 image. The accepted base64 image format is 'data:<content_type>;base64,<base64_image_content>'. Where 'content_type' like 'image/png' or 'image/jpg' or 'application/pdf' or any other supported type.",
Using Postman I have created the following curl request https://pastebin.com/ajfC3a5r
What am I doing wrong
How about this modification?
Modification points:
In your base64 data at here, \n is included.
When I tried to decode the base64 data after \n was removed from the base64 data, it was found that the data was PDF file. The content type was not image/png.
By these, I think that the error which was shown at your question occurs. So please modify as follows.
Modified curl command:
Please remove \n from the base64 data.
About the header of base64 data, please modify from data:image/png;base64,##### base64 data ##### to data:application/pdf;base64,##### base64 data #####.
When above modifications were done, how about using the following curl command?
curl -X POST \
https://api.ocr.space/parse/image \
-H "apikey:#####" \
-F "language=eng" \
-F "isOverlayRequired=false" \
-F "iscreatesearchablepdf=false" \
-F "issearchablepdfhidetextlayer=false" \
-F "base64Image=data:application/pdf;base64,##### base64 data #####"
Result:
When above sample is run, the following value is returned.
{
"ParsedResults": [
{
"TextOverlay": {
"Lines": [],
"HasOverlay": false,
"Message": "Text overlay is not provided as it is not requested"
},
"TextOrientation": "0",
"FileParseExitCode": 1,
"ParsedText": "##### text data #####",
"ErrorMessage": "",
"ErrorDetails": ""
}
],
"OCRExitCode": 1,
"IsErroredOnProcessing": false,
"ProcessingTimeInMilliseconds": "123",
"SearchablePDFURL": "Searchable PDF not generated as it was not requested."
}
Note:
In my environment, I could confirm that the API worked using above modified base64 data and sample curl.
The curl sample including the modified base64 data is this.
If you use this, please set your API key.
Or you can also directly use the image file which is not base64 data. The sample curl is
curl -X POST https://api.ocr.space/parse/image -H "apikey:#####" -F "file=#sample.png"