Hands-On RESTful API Design Patterns and Best Practices
上QQ阅读APP看书,第一时间看更新

Media types and media type design rules

As you saw in the Manipulation of Resources section of Chapter 1Introduction to the Basics of RESTful Architecture, media types help to identify the form of the data in a request or response message body, and the content-type header value represents a media type also known as the Multipurpose Internet Mail Extensions (MIME) type.

Media type design influences many aspects of a REST API design, including hypermedia, opaque URIs, and different and descriptive media types so that app developers or clients can rely on the self-descriptive features of the REST API.

The following points discuss the rules of media type design in brief:

  • Uses application-specific media types: REST APIs treat the body of an HTTP request or response as part of an application-specific interaction. While the request or response body is built with languages such as JSON or XML, it typically has semantics that requires special processing beyond merely parsing the language's syntax. An example representation of such a REST API URI is https://swapi.co/api/planets/1 that responds to the GET requests with a representation of the Star Wars planet resource that's formatted using JSON.
  • Supports media type negotiations in case of multiple representations: The client may require different formats and schema by submitting the desired media type as part of the Accept header, so the API should allow the clients to get the response in the desired format.Following is an example representation of the media type negotiations from developer.atlassian.com for the following Accept header:
Content-Type: application/json
Accept: application/json

Observe the following curl execution:

curl -i -u application_name:application_password --data '{"value": "my_password"}' http://testapi.com /crowd/rest/usermanagement/1/authentication?username=my_username --header 'Content-Type: application/json' --header 'Accept: application/json'  

 We can conclude the following:

  • Support media type selection using a query parameter:
    • To support clients with simple links and debugging, REST APIs should support media type selection through a query parameter named accept, with a value format that mirrors that of the accept HTTP request header
    • An example is REST APIs should prefer a more precise and generic approach as following media type, using the GET https://swapi.co/api/planets/1/?format=json query parameter identification over the other alternatives
Windows OS users can use MobaXterm (https://mobaxterm.mobatek.net/) or any SSH clients that supports Unix commands.