0

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.

ferjani
  • 89
  • 8

1 Answers1

1

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 e.g 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.

Dilip Krishnan
  • 5,417
  • 3
  • 37
  • 53
  • I didn't use the MultipartFile type because the user will not always upload a file. The PDF will be generated in the client side from an HTML form. – ferjani Jun 24 '16 at 09:59