Multipart media types

We have already talked about various data types you may use with your API. http://206.189.161.181/2015/06/common-hypermedia-types/. However at times you may need to encode binary data in your representations.

In the interest of transparency it makes sense to declare the payload as a multipart type.

A multipart message gives you the power to pass more than one media type over a single HTTP message. Each media part occupies it’s own space in the message.

Multiple medias

Multiple medias

A sample message for a user representation is shown below.

Content-type:   multipart/mixed;    boundary="multi_sep"
--multi_sep
Content-Type:   application/xml;charset=UTF-8
<user>  ... </user>
--multi_sep
Content-type:   image/png
... image   

In the above HTTP Message. We use an arbitrary boundary multi_sep to separate the two different media types.

The most common are listed below:

multipart/form-data

By far the most common. This particular multipart media type is used to encode name pair values in HTML forms which have binary data, say a profile picture upload.

multipart/mixed

This particular type mixes two or more representations in one message such as the one above where we mixed the user details data which is in XML with their profile picture which is in PNG.

multipart/alternative

In some cases one asset needs multiple representations. For example you may want to send both a HTML and a JSON representation of the same resource. In this case you need to specify the media type as above.

multipart/related

When you have various related parts in the application such as a user biographical information and their social media information, you can display both of them by using the multipart/related media type and refer to the other part using the Content-ID

You may possibly be tempted to use a binary to text encoding such as Base64 to keep your representations in the same HTTP message. This is a bad idea. To understand why check out this paper Base64 Can Get You Pwned

However on the flip side if you can avoid using multiparts all together and instead provide a rel link so that the assets are each on their own HTTP message, this would be the better option.

Lets keep the conversation going comment below. As usual don’t forget to Signup for our newsletter!

`

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Published by

jchencha

Software Project Manager