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

Content negotiation with HTTP headers

With our earlier example, we have seen that the server understands the content-types of incoming requests and entities with HTTP request header content-types.

In our code example, we have implemented the following content type and, by default application/JSON, and to represent what content type that the client desired to get, we use application/JSON  as the Accept header.

Please note that if no Accept header is present in the request, the server will send a pre-configured default representation type. In our example, it is always application/JSON, as shown in the following screenshot:

The preceding screenshot depicts the Content-Type and Accept headers from our examples.

If we want to implement our earlier example of a w3c image within our investor service application  in a similar fashion, all we need to do is add the following dependency to pom.xml:

<dependency> 
  <groupId>com.fasterxml.jackson.dataformat</groupId> 
  <artifactId>jackson-dataformat-xml</artifactId> 
</dependency> 

Modify the @GetMapping annotation in the controller class as follows:

@GetMapping(path="/investors/{investorId}/stocks/{symbol}", produces={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})

So, by using the accept request header, the client either gets the response as XML or as JSON. Cool, isn't it?

With Postman, we will get either a XML or JSON response according to the application/XML or application/JSON Accept header value:

Two other ways that we can pass the content type information to the server are as follows:

The following table provides a quick reference guide of a few other content-negotiation examples as server and client may need to deal with many other aspects of content-negotiation: