How to send multipart/form-data and nested json in the same request in postman?

Viewed 5999

I have a REST api that takes data of nested json including multipart file

While testing the REST api through postman I am having problems.

I don't exactly know how to send the diverse types of data that I need - multipart/form-data file and nested json.

I have used REST in each case separately in other projects but I am unable to combine them in one request.

To use multipart/form-data I have to select form-data in the Body, then File from the dropdown in the key field, click on the select files button on the value field and select the file I want to upload.

Adding file in form-data

To use nested json I have to select raw in the dropdown, and select json at the right of it and simply add the nested json in the body.

adding json data

But how do I combine these two approaches?

I need multipart/form-data as well as nested json in the same request. How do I send these from postman? I am trying various approaches as you can see in the screenshots but I am not getting anywhere.

Thanks in advance

P.S. If it matters, I am using java (spring boot) for the backend.

2 Answers

Your first approach is correct. However to pass the most complicated data it will be a nightmare to do from that location. If passing data from postman is the requirement then you can use the pre-request script in the postman. Below is the example:-

enter image description here

For pre-req, I have kept a basic js object. enter image description here

Try with this feature.

I followed the above answer and it worked for me.

Step 1: set json data value in pre-request Script.

var data = {    
name:"COD Black Ops",
cost:60,
}
pm.variables.set("somedata",JSON.stringify(data));

Step 2: set form values. enable content type option from (...) like button next to description column in order to set the value of your json field as "application/json".

Step 3: express code for handling form data

const multer  = require('multer')
const upload = multer(<options>)
app.post('/stats', upload.single('uploaded_file'), function (req, res) {
  // req.file is the name of your file in the form above, here 'uploaded_file'
  // req.body will hold the text fields, if there were any 
console.log(req.file, req.body)
});
Related