How to send file upload multipart form in restassured - api

I want to send below as a Multipart Form in API Body for a POST request:
Upload passing two attributes (KEY) with (VALUE)
Send arquivo (KEY) with (file)
How to do this using REST-Assured
multipart print https://ibb.co/0QQCkQv
attempts:
Response response = (Response)
given()
.relaxedHTTPSValidation()
.header("Content-Type", "multipart/form-data")
.formParam("tipo", "capital_relatorio_faturamento")
.multiPart("arquivo", file, "image/jpg")
enter code here
------------------------------
.formParam("arquivo", "image/jpg")
.multiPart("tipo", "capital_balanco_patrimonial")
.multiPart("arquivo",file)
-------------------------------
.header("Content-Type", "multipart/form-data")
.multiPart("tipo", "capital_comprovante_endereco")
.multiPart("arquivo",file)```

Try
.multiPart("tipo", "capital_balanco_patrimonial")
.multiPart("arquivo", file, "image/jpg")
Rest-assured will automatically add content-type for these.

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.

How to read the contents of a Post request on Postman?

In the systems I am testing, there are cases that the response informs 200 (ok), but the content may indicate an error in the internal validations of the backend service. How can I read the contents of the response with Postman and schedule a successful validation if this service error code comes as expected?
You can use the tests tab in Postman to run checks on the body (JSON and XML). There are snippets which show you the syntax. You can adapt them to check for the element of the response body which indicates the error.
Postman has a tab called "Tests" where you can provide you test script for execution.
If you want to validate your request responded with 200 OK, following is the script
pm.test("Status test", function () {
pm.response.to.have.status(200);
});
If you want to validate the response contains any specified string,
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});
In your case am assuming the above script can be used. In case the response body is JSON,
pm.test("JSON Body match", function () {
var respBody = pm.response.json();
pm.expect(respBody.<json node>).is.to.equal("Error_name");
});
Example JSON response body
{
"id" : 100,
"status" : "Bad Request"
}
pm.test("JSON Body matches string", function () {
var respBody = pm.response.json();
pm.expect(respBody.status).is.to.equal("Bad Request");
});

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

BadRequest when try Create folder via REST

I've downloaded a exampled that show the files in the "Shared with everyone" folder in my OneDrive for Bussiness. It's work fine!
But, when I try to create a Folder or File (without content) like this documentation the response became with a BadRequest .
The request goes like:
string requestUrl = String.Format(CultureInfo.InvariantCulture, "{0}/files", serviceInfo.ApiEndpoint);
// Prepare the HTTP request:
using (HttpClient client = new HttpClient())
{
Func<HttpRequestMessage> requestCreator = () =>
{
HttpRequestMessage request = new HttpRequestMessage( HttpMethod.Post, requestUrl);
request.Headers.Add("Accept", "application/json;odata.metadata=full");
request.Content = new StringContent(#"{'__metadata':{'type':'MS.FileServices.Folder'},Name:'TestFolder'}");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return request;
};
}
And the response is a BadRequest.
I think that my problem is in the "__metadata"'s json value. It´s is correct? Where can I find a working example implementing this operations?
Thanks in advance!
EDIT: Changing the API Endpoint from "/_api/web/getfolderbyserverrelativeurl('Documents')/files" to "_api/files" the error became to: "The property '__metadata' does not exist on type 'MS.FileServices.FileSystemItem'. Make sure to only use property names that are defined by the type."
I´m think I foward in this. But, I still continue with problems.
I am not sure if this can be of any help to you, as this pertains to oneDrive and not oneDrive for business.
Also the documentations are confusing :)
according to the documentation the request should be as follow:
POST https://apis.live.net/v5.0/me/skydrive
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json
{
"name": "My example folder"
}
if you can see that in the header there is authorization access token
I don't see that you sent to the server any access token. and that is why you had a bad request.
I am trying to below way to create a folder in SP and it's working for me. Hope it will work for you as well.
Create a folder using SharePoint Web API -
POST https://<Domain>.sharepoint.com/_api/web/folders
Accept: "application/json;odata=verbose"
Content-Type: "application/json"
{
"ServerRelativeUrl": "/Shared Documents/<Folder-Name>"
}

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();