We often come across scenarios where we need to deal with files as a part of the payload of an HTTP request or as a response. Though it is easy to do it manually in postman or swagger, it is a challenge when it comes to automation. In this article, let's see how to automate such api endpoints by sending files as a part of requests and how to download if a response is also a file.
Attach File to Request
Scalaj-HTTP is a wrapper for an HTTP client in Scala. It provides a method — postMulti to attach files as a part of a request.
Let's say there is an endpoint that takes only a file as a payload. (Note, the file should be a multipart of type.)
MultiPart(filename, filepath, mimetype, byteArrayInputStream)
Define your file as a multipart like above. Wonder what is last argument byteArrayInputStream? you should pass the file as a byte array to the request. For example, if you are going to attach an image (png) it will be like below.
MultiPart("image", "src/image.png", "image/png", getByteArray("src/image.png"))
Now, if you are going to use the post method, the entire request goes like this.
val res = Http(url) .postMulti(MultiPart(filename, filepath, mimetype, data)) .method("POST") .asString
That's it, this will do the process of attaching files to your request.
Download the File From the Response
Let's say I am getting a file as a response from an endpoint, and I need to download the file. Follow the below 2 steps to do it.
1. Get the Response Using scalaj-HTTP Client
Let's assume we have a simple GET endpoint that gives an image as a response. By using the following code, you will be getting the response.
val res = Http(url) .header("accept", "image/png") .method("GET") .option(HttpOptions.connTimeout(100000)) .option(HttpOptions.readTimeout(100000))
Remember, how did we send the image as a byteArray to request? Now, it is a reverse to this.
Get the response as a byteArrayInputStream and write it to a file.
val file = new File("src/image/image.png") file.createNewFile() val bis = new ByteArrayInputStream(res.asBytes.body) IOUtils.copy(bis, new FileOutputStream(file))
That's it. You will be able to see the image in the desired path.