简体   繁体   中英

Use of byte[] with spring-rest and springfox

I am new to REST API design and I have two questions about the API I am trying to write.

I want to create a service that, giving a PDF file encoding, creates an object in the database.

My current service looks like this:

@RequestMapping(value = "/create", method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE,
    consumes = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public String create(@RequestBody byte[] pdf)

My questions are:

  1. Is it "recommended" to use the byte[] with REST APIs ? PS: the service will be consumed by web clients as well as toolkits.
  2. I tried to use springfox to document my API. the UI tool does not allow me to submit binary data.

I used the following annotation

    @ApiImplicitParams({
    @ApiImplicitParam(name = "pdf", value = "PDF encoding", required = true,
     allowMultiple = true,
     paramType = "body", dataType = "byte")
  })

The generated JSON is:

{"type":"array","items":{"type":"string","format":"byte"}}

However the UI interface displays a textarea for the PDF encoding and submits any content as a string. (For example, if I submit the value "5", the server receives [53]).

Do you have any idea what I am missing at this level ?

-- EDIT --

The PDF is generated in the client side from an HTML form. So it is not a simple form submit.

The recommended approach to uploading files is to use the MultipartFile . So I'd change the signature to something like shown below.

@RequestMapping(value = "/create", method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE,
    consumes = MediaType.MULTIPART_FORM_DATA_VALUE) //<-- NOTE THIS
public String create(@RequestParam("pdf") MultipartFile pdf) //<-- NOTE THIS

Secondly, For documentation don't worry about the @ApiImplicitParams stuff, just yet. See if the above solution works.

After you've determined its working as expected in swagger-ui. Use @ApiParam to document the description etc. @ApiImplicitParams is used to document parameters that are as the name suggests implicit . So for eg if your method signature deals with raw types like HttpServletRequest and extracts the parameters that are implicitly part of the request, thats when you'd use that annotation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM