Wanted to test a post request in POSTMAN.
public enum TimeUnit { HOURS("hours"), MINUTE("mins"); private String value; public static TimeUnit get(String text) { return Arrays.stream(TimeUnit.values()) .filter(a -> Objects.equals(a.getValue(), text)) .findFirst() .orElse(null); } }
public final class SchoolTimeTable { private Double value; private TimeUnit unit; public SchoolTimeTable (double value, TimeUnit unit) { this.value = value; this.unit=unit; } }
public class SchoolDto { private String name; private String address; private MultipartFile profileImage; private MultipartFile[] galleryImages; private SchoolTimeTable openCloseTime; }
Spring MVC Controller
@PostMapping(value = "/schoolInfo", produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<Object> saveSchoolInfo( @Parameter(required = true, schema = @Schema(implementation = SchoolDto.class)) SchoolDto schoolDto) throws IOException, InterruptedException { ... }
I want to send SchoolDto (POSTMAN: body->raw->json) in post request to get desired result. But I am not able to create the json which supports SchoolTimeTable (Object) and MultipartFile types. I don’t even know whether it is possible with JSON or not. Note: Same could be achieved using body->form-data with key/value.
Please help.
Advertisement
Answer
I think you should not upload files within a application/json
request, to do so you should use a multipart/form-data
request. Your request may have three parts profileImage
, galleryImages
and schoolInfo
.
Remove profileImage
and galleryImages
from SchoolDto
class
Modify your method signature to support the multipart request
@PostMapping(value = "/schoolInfo", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<Object> saveSchoolInfo(@RequestPart(value = "profileImage") MultipartFile profileImage, @RequestPart(value = "galleryImages") MultipartFile[] galleryImages, @RequestPart(value = "schoolInfo") SchoolDto schoolInfo) throws IOException, InterruptedException { ... }
In addtion you can implement a @SpringBootTest
unit test using RestDocumentationExtension
to check whether your code works and to produce a curl request sample that will help you to understand how to make a request to your endpoint