Katalon - Upload a file using POST API - api

I’ve searched for this issue and seems to be discussed a couple of times but with no real resolution.
I’m trying to upload an XML file using a POST request and form-data, but I get the following error response:
{
"error":"The results file is required."
}
The error shows using ObjectRepository and also by code using with withMultipartFormDataBodyContent()
If I use curl it works fine. Also works fine with Postman.
Can someone please help me with this?
Thanks.

After a looooooooooooong time of searching and trying different things I already found the solution (that works for me). It uses Okhttp library so you will need to import it.
If anyone else need it, there it is:
public void importJUnitTestExecRequest() {
OkHttpClient client = new OkHttpClient();
String reportFile = GlobalVariable.reportFolder + "\\JUnit_Report.xml";
File file = new File(reportFile);
String url = GlobalVariable.importTestExecJUnitEndpoint+"?testExecKey="+GlobalVariable.testExecKey;
//Form request body that will be a multipart
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("text/xml"), file))
.build();
//Form the actual request adding necessary headers
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.addHeader("Content-Type", GlobalVariable.contentTypeMultipart)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
println("************ IMPORT TEST EXECUTION RESULTS RAW RESPONSE ************");
println("Response status: " + response);
println("********************************************************************");
if (response.isSuccessful()){
String responseBody = response.body().string();
println("************ IMPORT TEST EXECUTION RESULTS RESPONSE BODY ************");
println(responseBody);
println("*********************************************************************");
} else {
throw new IOException("Unexpected HTTP code " + response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
I've opened a ticket to support because with the built in functionality in Katalon, it is currently (or I don't know how to do it) not possible.

Related

How to add an attachment to Testrail using the Testrail API

I have tried the following API endpoint to add an attachment to Testrail via their API.
But it is not very clear how to name the said file attachment (I am using Postman)
API endpoint:
[POST]
https:///{{testrail link}}/index.php?/api/v2/add_attachment_to_result/449
Headers:
{
"Content-Type","value":"multipart/form-data"
}
What must the body params be?
I have currently selected the file and multipart/form-data for Content-type. Please help!
The error right now on Postman :
{
"error": "No file attached or upload size was exceeded."
}
The upload size is just fine (under 256 MB)
using postman you need to pass the file through the body by adding a file type key named 'attachment' and value:{select your file}
eg:
key: attachment | value:myfile.txt
Here is a working Java example - I know it's a little late, but it may be useful for reference:
public void uploadScreenshot(long resultId, String screenshotFile) {
String url = String.format("add_attachment_to_result/%d", resultId);
try {
client.sendPost(url, screenshot);
}
catch(Exception e) {
e.printStackTrace();
}
}
You can add an attachment to various assets within TestRail, in this example I am adding a screenshot to a result, which has to be passed in (when you add a result you can get the JSON response and store the 'id' of the newly created result.

Sending a file with XMLHttpRequest() to Tika server

I'm trying to send a PDF for content extraction to a Tika Server but always get the error: "Cannot convert text from stream using the source encoding"
This is how Tika is expecting the files:
"All services that take files use HTTP "PUT" requests. When "PUT" is used, the original file must be sent in request body without any additional encoding (do not use multipart/form-data or other containers)." Source https://wiki.apache.org/tika/TikaJAXRS#Services
What is the correct way of sendig the file with XMLHttpRequest()?
Code:
var response, error, file, blob, xhr;
file = new File("/PROJECT/web/dateien/ai/pdf.pdf");
blob = file.toBuffer().toBlob("application/pdf");
url = "http://localhost:9998/tika";
// send data
try {
xhr = new XMLHttpRequest();
xhr.open("PUT", url);
xhr.setRequestHeader("Accept", "text/plain");
xhr.send(blob);
} catch (e) {
error = e;
}
({
response: xhr.responseText,
status: xhr.statusText,
error: error,
type: xhr.responseType,
blob: blob
});
Error:
I suspect PUT request to be converted into a POST request by wakanda when there is blob in XHR body. Can you wireshark your XHR request and add details ? If so, you can probably fill an issue in wakanda (https://github.com/Wakanda/wakanda-issues/issues)
Hope it helps,
Yann

GET API code request failure

I just started learning how to use API and I found some really usefull websites and apps like Postman and import.io yet I'm having problems finishing it without help.
I started my little project by getting a working api from import.io (It reads a website and can give you a working API that finds the info in the website)
My REST API looks like this:
https://extraction.import.io/query/runtime/7629f27e-ceee-4ce2-9a1c-cede623d2fc0?_apikey=[apiKey]&url=http%3A%2F%2Fimdb.com
To test and make sure it's working I used postman app and then found a neat feature - code generation.
The app generated this code:
import http.client
conn = http.client.HTTPSConnection("extraction.import.io")
headers = {
'cache-control': "no-cache",
'postman-token': "2087cc79-77b5-0cb9-aa06-adc642978287"
}
conn.request("GET", "/query/runtime/1ac40e3e-f3eb-4290-88c0-e2651b8194a5?_apikey=[apiKey]&url=http%253A%252F%252Fwww.leagueofgraph.com", headers=headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
however the result is:
{
"message" : "Your extraction request has failed.",
"code" : 1003
}
What am I doing wrong?
The code that has been generated has double escaped the "http://"
it should be http%3A%2F%2F not http%253A%252F%252F
Try this corrected code:
import http.client
conn = http.client.HTTPSConnection("extraction.import.io")
headers = {
'cache-control': "no-cache",
'postman-token': "2087cc79-77b5-0cb9-aa06-adc642978287"
}
conn.request("GET", "/query/runtime/1ac40e3e-f3eb-4290-88c0-e2651b8194a5?_apikey=[apiKey]&url=http%3A%2F%2Fwww.leagueofgraph.com", headers=headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

Google Apps Script: Salesforce API Call

Just finished breakfast and already hit a snag. I'm trying to call the salesforce REST api from my google sheets. I've written a working script locally in python, but converting it into JS, something went wrong:
function authenticateSF(){
var url = 'https://login.salesforce.com/services/oauth2/token';
var options = {
grant_type:'password',
client_id:'XXXXXXXXXXX',
client_secret:'111111111111',
username:'ITSME#smee.com',
password:'smee'
};
var results = UrlFetchApp.fetch(url, options);
}
Here is the error response:
Request failed for https://login.salesforce.com/services/oauth2/token
returned code 400. Truncated server response:
{"error_description":"grant type not
supported","error":"unsupported_grant_type"} (use muteHttpExceptions
option to examine full response) (line 12, file "Code")
Mind you, these exact parameters work fine in my local python script (putting the key values inside quotations).
Here are the relevant docs:
Google Script: Connecting to external API's
Salesforce: REST API guide
Thank you all!
Google's UrlFetchApp object automatically defaults to a GET request. To authenticate, you have to explicitly set in the options the method "post":
function authenticateSF(){
var url = 'https://login.salesforce.com/services/oauth2/token';
var payload = {
'grant_type':'password',
'client_id':'XXXXXXXXXXX',
'client_secret':'111111111111',
'username':'ITSME#smee.com',
'password':'smee'
};
var options = {
'method':'post',
'payload':payload
};
var results = UrlFetchApp.fetch(url, options);
}

Invalid 'HttpContent' instance provided. It does not have a 'multipart' content-type header with a 'boundary' parameter

I'm writing a web API that has a post method accepting files uploaded from UI.
public async Task<List<string>> PostAsync()
{
if (Request.Content.IsMimeMultipartContent("form-data"))
{
string uploadPath = HttpContext.Current.Server.MapPath("~/uploads");
var streamProvider = new MyStreamProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(streamProvider);
return streamProvider.FileData
.Select(file => new FileInfo(file.LocalFileName))
.Select(fi => "File uploaded as " + fi.FullName + " (" + fi.Length + " bytes)")
.ToList();
}
else
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Request!");
throw new HttpResponseException(response);
}
}
Then I post a request for the above action by postman.
I set the content-type header to multipart/form-data
but an error occurred during the execution of action.
here is the error message body :
"Invalid 'HttpContent' instance provided. It does not have a 'multipart' content-type header with a 'boundary' parameter.\r\nParameter name: content"
I went to the postman headers but I found that the request header content type was set to application-json.
You are looking on the response header which is json format and this is ok for you.
Your real problem is with the postman request, so just remove the 'Content-Type: multipart/form-data' entry from request header.
It's enough to upload a file as form-data and send the request.
Look what happen when you set the Content-Type manually vs. when you not:
Postman knows to set both the content type and boundary, since you set only the content type
First: Postman have a bug in handling file-based requests.
You can try adding this to your WebApiConfig.cs it worked for me:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();