简体   繁体   中英

REST API Design for Binary Data

This feels like reinventing the wheel a bit, but I'm trying to create high-level guidelines for a REST API. For example, GET requests are used to retrieve data, POST requests are used to create objects or to invoke actions, PATCH requests are used to update parts of objects, etc.

I'm struggling with the POST portion. Here's why:

  • If I don't consider binary data, I'd prefer all POST request bodies to be JSON. See PayPal REST API as an example. I like this because it's more expressive and easily convertible for consumption in a NoSQL database.
  • But I do need some API operations to handle binary data. In this case I'm not sure JSON would still work...

My questions are:

  • Does it make sense to standardize POST requests in the API design? Option 1 : All POST requests either use Content-Type "application/x-www-form-urlencoded" or "multipart/form-data". Option 2 : All POST requests use Content-Type "application/json".
  • If going with Option 2 above, how do I allow clients to send binary file data?

An example

To clarify my question, let's take a single POST /profiles operation. Without binary data, an "application/json" body could look like the following.

{
  firstName: "Yours",
  lastName: "Truly"
}

But if a user needs to include binary content, a "multipart/form-data" body would look like this, with the binary content for an input named photo coming later in the request.

firstName=Yours
lastName=Truly

There's no perfect solution here -- it's one of the places where REST starts to feel limiting. As you describe, it would be nice to be able to standardize on JSON for all requests, while also being able to add binary input to some of the requests. However, in order to pass binary input alongside application/json input, users have to submit a multipart request with a full JSON part and a binary part, which is more cumbersome than using form-data.

One consideration is whether the JSON might become hierarchical -- form data fields don't scale as well to representing more complicated data structures, and so for these, having a true application/json part is preferred, especially if you're trying to maintain consistency with another endpoint that doesn't need binary input.

Another consideration is if you're going to have language native SDKs for customers. These SDKs can abstract away the more messy and cumbersome details about multipart form requests, allowing you to maintain the consistency and flexibility without as many usability problems.

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