This maybe a simple question but I couldn't figure it out myself nor could I find an online resource for it.
I have to develop a REST API using spring boot. I see two options to accept the json payload (max payload size 3 MB in some cases)
Option 1: Ask clients to send json in request body. Let Jackson convert it to Java object
@RestController
public class EmployeeController {
@PostMapping
public void createEmployees(@RequestBody List<Employee> employees) {
// do something with employees
}
}
Option 2: Ask clients to upload a json file and let the controller accept Multipart payload
@RestController
public class EmployeeController {
@PostMapping(consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public void createEmployees(@RequestParam(name = "file") MultipartFile file) {
// convert multipart file data to List of Employee objects
//do something with employees
}
}
Which option is better and why?
CodePudding user response:
I think Option 1 is better. This is because if you use a file, you have to read the json payload written in the file and convert it to List<Employee>
.
And if you use a multipartFile, you receive base64 encoded data. Since base64 encoded data expresses 8-bit data as 6-bit data, 33% increase in size occurs compared to the original.
CodePudding user response:
If we are talking about structured data your API uses directly, then better to upload it as application/json
. If we are talking about some sort of attachment, which your API probably does not touch or touches it only a lot later e.g. images, PDF, etc. then better to use multipart/form-data
and send a JSON with it, which describes the metadata of the attachment, e.g. it is a photo of a friend, etc. So I think it depends on the JSON and what you want to do with it. In your case since it will be processed, then better to send it as application/json
. If you process it later, then still better to send it this way and make a transaction resource where you can follow the state of the processing, something like POST /transactions {json}
.