Data file content for Postman Runner to test a POST request of type multipart/form-data - postman

What is the data file that should be provided in Postman runner to execute multiple calls to a POST endpoint that expects multiplart/form-data?
I have an Azure function which looks like this (simplified for this post):
[FunctionName("UploadImage")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
{
var form = await req.ReadFormAsync();
if (!form.Files.Any()) return new BadRequestObjectResult("form.Files is empty");
var uploadedFile = form.Files.First();
form.TryGetValue("fileName", out var fileNames);
return new OkObjectResult($"Uploaded image length: {uploadedFile.Length} file name {fileNames.First()}");
}
I use Postman to send it a request successfully like this:
Postman request body params
I want to call this function 100 times concurrently to test its performance using the "Run Collection" selection of Postman. It asks to provide a csv datafile. So I tried a file that has only 2 lines like this:
FileName, Photo
Attachment1, Regina.jpg
But it does not work with that data file. I get a response message that "form.Files is empty"
How to correctly provide a data file for this Postman runner to test calling the endpoint (n) times async?

Related

How do I make putObject request to presignedUrl using s3 AWS

I am working with AWS S3 Bucket, and trying to upload image from react native project managed by expo. I have express on the backend. I have created a s3 file on backend that handles getting the presigned url, and this works, and returns the url to the front end inside this thunk function from reduxjs toolkit. I used axios to send request to my server, this works. I have used axios and fetch to try the final put to the presigned url but when it reached the s3 bucket there is nothing in the file just an empty file with 200 bytes everytime. When I use the same presigned url from postman and upload and image in binary section then send the post request the image uploads to the bucket no problems. When I send binary or base64 to bucket from RN app it just uploads those values in text form. I attempted react-native-image-picker but was having problems with that too. Any ideas would be helpful thanks. I have included a snippet from redux slice. If you need more info let me know.
redux slice projects.js
// create a project
// fancy funtion here ......
export const createProject = createAsyncThunk(
"projects/createProject",
async (postData) => {
// sending image to s3 bucket and getting a url to store in d
const response = await axios.get("/s3")
// post image directly to s3 bucket
const s3Url = await fetch(response.data.data, {
method: "PUT",
body: postData.image
});
console.log(s3Url)
console.log(response.data.data)
// make another request to my server to store extra data
try {
const response = await axios.post('/works', postData)
return response.data.data;
} catch (err) {
console.log("Create projects failed: ", err)
}
}
)

Is it possible to send environment variable data as response from postman mock server?

In pre-req script I wrote logic:
var obj = pm.request.body.toJSON();
var rawObj = JSON.parse(obj.raw);
var token =rawObj.token;
if(token==1){
pm.environment.set("status_code", 200);
pm.environment.set("msg", "token-1");
}else if(token==2){
pm.environment.set("status_code", 202);
pm.environment.set("msg", "token-2");
}
For response I wrote,
{"status_code":{{status_code}}, "msg":{{msg}}}
But in response the values are not passing, it prints above line as string.
How to send the environment value as response for mock server api request?

Retuning stream in AWS API Gateway -> Lambda function?

I have created an API using AWS api gateway like https://api.mydomain.com/v1/download?id=1234". The download resource has GET method. And the GET method is invoking lambda function using Lambda Proxy Integration.
The Lambda function needs to act as Proxy. It needs to resolve correct backend endpoint based on header x-clientId and then forward the request to that backend endpoint and return response as it is. So it needs to be generic to handle GET request of different content-type.
My lambda function looks like ( .NET Core)
public async Task<APIGatewayProxyResponse> Route(APIGatewayProxyRequest input, ILambdaContext context)
{
var clientId = headers["x-clientId"];
var mappings = new Mappings();
var url = await mappings.GetBackendUrl(clientId, input.Resource);
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
var proxyResponse = new APIGatewayProxyResponse()
{
Headers = new Dictionary<string, string>(),
StatusCode = (int)System.Net.HttpStatusCode.OK,
IsBase64Encoded = false,
Body = await response.Content.ReadAsString())
};
}
The handler above works as long as request and response's content-type is application/json or application/xml. However i am not sure how to handle response when backend returns stream.
For download API, the backend returns Content-Disposition: attachment; filename="somefilename and ContentType may be one of the following:
application/pdf
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/x-zip-compressed
application/octet-stream
For these streams, How do i set APIGatewayProxyResponse.Body?
For Excel file I have tried setting body like below
var proxyResponse = new APIGatewayProxyResponse()
{
Headers = new Dictionary<string, string>(),
StatusCode = (int)System.Net.HttpStatusCode.OK,
IsBase64Encoded = true,
Body = Convert.ToBase64String(await response.Content.ReadAsByteArrayAsync())
};
proxyResponse.Headers.Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
proxyResponse.Headers.Add("Content-Disposition", "attachment; filename=\"Report.xlsx\"");
When i access the Url from the browser and try to open the file. I get error
Excel cannot open the fileReport.xlsxbecuase the file format or file extension is not valid. Verify that the file has not been corrupted and that the extention matches the format of the file
I think the issue is how i am setting the response body
Update 1
So based on AWS doc Binary Data Now Supported by API Gateway. Now as per the documentation
you can specify if you would like API Gateway to either pass the
Integration Request and Response bodies through, convert them to text
(Base64 encoding), or convert them to binary (Base64 decoding). These
options are available for HTTP, AWS Service, and HTTP Proxy
integrations. In the case of Lambda Function and Lambda Function Proxy
Integrations, which currently only support JSON, the request body is
always converted to JSON.
I am using Lambda Function Proxy, which currently support JSON. However the example here shows how to do it with Lambda Proxy.
I think what i am missing here is Binary Media Types setting and Method Response settings. Below is my setting. Not sure if these settings are correct
Binary Media
Method Response
here how solved it
1>add Binary Media Types. API->Settings->Binary Media Types -> add
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
2>In Method Response Add Content-Disposition and Content-Type headers for thestatus 200
3>In Integration Response map these headers to headers that are coming from the backend. And also set content handling convert to binary. (our backend api is returning file blob in body)

Grails RESTFUL web service api

I am currently developing a web app which should do restful service calls to existing web service api.
What I have is the base URL and the API names.
Any help on how do I start working on it?
I suppose I need to use httpbuilder for the base url I have, then followed by /api name. But how do I test it on grails if its working?
When I paste the base url on the browser it does return some xml information, so what I need is to do it on grails instead.
XML response when I paste the url through browser
<ns1:createNewUserResponse>
<userId>21</userId>
</ns1:createNewUserResponse>
So I need to be able to get this response through my web-app (grails) instead of pasting it on the browser.
EDIT*
this is a good example I found useful
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
def http = new HTTPBuilder( 'http://ajax.googleapis.com' )
// perform a GET request, expecting JSON response data
http.request( GET, JSON ) {
uri.path = '/ajax/services/search/web'
uri.query = [ v:'1.0', q: 'Calvin and Hobbes' ]
headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
// response handler for a success response code:
response.success = { resp, json ->
println resp.statusLine
// parse the JSON response object:
json.responseData.results.each {
println " ${it.titleNoFormatting} : ${it.visibleUrl}"
}
}
// handler for any failure status code:
response.failure = { resp ->
println "Unexpected error: ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
}
}
but i do not understand the query part and how do I alter it to my need?
the URL I have contains credential of username and password, the response should return a securityToken which I need to get it out from the results. Any help would be greatly appreciated!
You can start with groovy-wslite, it provides both SOAP and REST webservice clients.
To make a call to a resfull service look at Groovy HttpBuidler - http://groovy.codehaus.org/HTTP+Builder

How do I read a Django HTTPResponse in Flex?

I'm a complete Flex noob, so I apologize in advance if I'm missing something obvious.
I wrote a fairly simple file uploader in Flex, which calls my Django back-end via URLRequest (the FileReference object handles the upload). My upload works as intended and I have Django return a HTTPResponse object. As such, I'd like to read the contents of the HTTPResponse object.
Any thoughts?
something along the lines of
<mx:HTTPService id="myHTTPRequest"
url="{whatever your url request is}"
result="resultHandler(event)"
fault="faultHandler(event)"
showBusyCursor="true"
resultFormat="object">
then inside the resultHandler something like this
private function resultHandler (event : ResultEvent) : void {
var obj : Object = event.result;
//do something with returned object
}
Debug at the point of the resultHandler to see exaclty whats being returned, make sure its what you think should be getting returned.
By the time it gets to the client it's just a normal HTTP response so treat it like any other response
I am also new to flex and I ran in the same problem when doing an upload to a Java Rest backend, I solved it using the DateEvent on the FileReference. To get the response data use something like this.:
var fileRef:FileReference = new FileReference();
fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, responseHandler);
var request:URLRequest = new URLRequest("yourUrl");
fileRef.upload(request, "fileData");
private function responseHandler(event:DataEvent):void {
var response:XML = new XML(event.data);
//Note the DataEvent: this is the event that holds the response.
//I sent back data as xml
}
Your response should always be a successful HTTP status code (200), if your backend sends status 500 codes it will not trigger the DateEvent. Server errors can still be caught with a HTTPStatusEvent, but then you don't have access to the response.
you can access the response like so in your onComplete event handler:
private function saveCompleteHandler(event:Event):void {
var loader:URLLoader = event.currentTarget as URLLoader;
trace("saveCompleteHandler - event returned:" + loader.data as String);
}
we do this this to get json fron a java web service.
you just need to use a URLLoader to load the URLRequest in the first place:
var loader:URLLoader = new URLLoader();
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, statusHandler, 10000);
loader.addEventListener(IOErrorEvent.IO_ERROR, saveErrorHandler, 10000);
loader.addEventListener(Event.COMPLETE, saveCompleteHandler, 10000);
var request:URLRequest = new URLRequest("http:/whereverer");
request.method = URLRequestMethod.GET;
loader.load(request);