Dealing With Files in REST API

DZone 's Guide to

Dealing With Files in REST API

In this article, see how to attach files to http request using HTTP's multipart method

· Integration Zone ·
Free Resource

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.)


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.


Now, if you are going to use the post method, the entire request goes like this.


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.


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. 


That's it. You will be able to see the image in the desired path.

Compare 2 Images

After downloading the image, many want to compare the images as part of testing or just to verify the image is the expected one.

Below is the scala code that compares two images by converting them to ByteArrays.


Thanks for reading!

api ,api automation ,http ,multipartfile ,rest ,scala

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}