Spring Boot REST Web Services Content Negotiation

Mahesh Bonagiri
3 min readJul 2, 2021

Introduction

REST resources can have multiple presentations (e.g. JSON or XML) as different clients can request different representation. The mechanism for selecting a correct representation is known as content negotiation.

Content negotiation allows clients to request specific content type(s) to be returned by the server. With content negotiation, we enable a single endpoint to support different types of resource representations

Content Negotiation Strategies

Content Negotiation can be done in following ways

  • Using Path Extension This has the highest preference. In the request we specify the required response type using the extension like .json,.xml or .txt.
  • Using url parameter This has the second highest preference. In the request we specify the required response type using the url parameter like format=xml or format=json.
  • Using Accept Headers When making a request using HTTP we specify required response by setting the Accept header property.

Lets start

let’s use https://start.spring.io/ web site to generate the base for our project.

Import to your eclipse and start the project, you should see below message

Started SpringbootContentNegotiationApplication in 6.796 seconds (JVM running for 10.25)”

Add Books.java and BooksController.java as shown below

Url Parameter Strategy

Add below Configuration class and overwrite configure Content Negotiation method. We can enable this strategy by setting the value of the favorParameter property to true.

Compile above code and run SpringbootContentNegotiationApplication.java as Java application.

we can use Curl/Postman/browser for accessing our rest resource, i am using browser here. Open your favorite browser and access below url with mediaType as xml

URL: http://localhost:8080/books/all?mediaType=xml

Media Type — xml

with mediaType as json

URL: http://localhost:8080/books/all?mediaType=json

Media Type — Json

URL: http://localhost:8080/books/book/1?mediaType=json

/books/book/1

Accept Headers strategy:

If the Accept header is enabled, Spring MVC will look for its value in the incoming request to determine the representation type. set ignoreAcceptHeader value to false to enable this approach.

with Accept — application/json

Accept application/json

with Accept — application/xml

Conclusion:

If you would like to refer to the full code, do check https://github.com/projectk-user1/Springboot-learning.git

Please do refer my other articles on Spring boot

Feel free to provide your suggestions in comments section

--

--