DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Update User Details in API Test Client Using REST Assured [Video]
  • Create User API Test Client With REST Assured [Video]
  • How to Make a REST API Call in Angular
  • Develop a Spring Boot REST API in AWS: PART 4 (CodePipeline / CI/CD)

Trending

  • Designing AI Multi-Agent Systems in Java
  • Data Lake vs. Warehouse vs. Lakehouse vs. Mart: Choosing the Right Architecture for Your Business
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Dealing With Files in REST API

Dealing With Files in REST API

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

By 
Gowthamraj Palani user avatar
Gowthamraj Palani
·
May. 22, 20 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
15.5K Views

Join the DZone community and get the full member experience.

Join For Free

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

Scala
xxxxxxxxxx
1
 
1
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.

Scala
xxxxxxxxxx
1
 
1
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.

Scala
xxxxxxxxxx
1
 
1
val res = Http(url)
2
            .postMulti(MultiPart(filename, filepath, mimetype, data))
3
            .method("POST")
4
            .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.

Scala
xxxxxxxxxx
1
 
1
val res = Http(url)
2
      .header("accept", "image/png")
3
      .method("GET")
4
      .option(HttpOptions.connTimeout(100000))
5
      .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. 

Scala
xxxxxxxxxx
1
 
1
val file = new File("src/image/image.png")
2
file.createNewFile()
3
4
val bis = new ByteArrayInputStream(res.asBytes.body)
5
    IOUtils.copy(bis, new FileOutputStream(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.

Scala
x
20
 
1
  def getByteArray(path: String): Array[Byte] = {
2
3
    val bImage = ImageIO.read(new File(path))
4
    val bos = new ByteArrayOutputStream()
5
    ImageIO.write(bImage, "png", bos)
6
    bos.toByteArray
7
  }
8
9
  def compareImage(image1: Array[Byte], image2: Array[Byte]): Boolean = {
10
    if (image1.deep == image2.deep && image1.sameElements(image2))
11
      true
12
    else
13
      false
14
  }
15
16
  def verifyImages() {
17
    val image1 = getByteArray("src/image.png")
18
    val image2 = getByteArray("src/image1.png")
19
    assert(compareImage(image1, image2))
20
  }


Thanks for reading!

REST API Web Protocols

Opinions expressed by DZone contributors are their own.

Related

  • Update User Details in API Test Client Using REST Assured [Video]
  • Create User API Test Client With REST Assured [Video]
  • How to Make a REST API Call in Angular
  • Develop a Spring Boot REST API in AWS: PART 4 (CodePipeline / CI/CD)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!