Spring Boot and Content Negotiation - XML and JSON Representations


Image


CHECK OUT OUR 8 AMAZING AWS CERTIFICATION COURSES HERE


This guide will help you implement Content Negotiation for a REST API/Service with Spring Boot. Content Negotiation helps the Consumer and Provider interact about the data exchange format. In this article, we will expose both XML and JSON representations.

You will learn

  • What is Content Negotiation?
  • Why do you need Content Negotiation?
  • How do you implement Content Negotiation with Spring Boot?
  • How do you use XML representation for request and response with Spring Boot RESTful Services?
  • How do you use JSON representation for request and response with Spring Boot RESTful Services?

Free Courses - Learn in 10 Steps

Project Code Structure

Following screenshot shows the structure of the project we will create. Image

A few details:

  • SpringBoot2RestServiceApplication.java - The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.
  • pom.xml - Contains all the dependencies needed to build this project. We will use Spring Boot Starter AOP.
  • Student.java - Student JPA Entity
  • StudentRepository.java - Student JPA Repository. This is created using Spring Data JpaRepository.
  • StudentResource.java - Spring Rest Controller exposing all services on the student resource.
  • data.sql - Initial data for the student table. Spring Boot would execute this script after the tables are created from the entities.

Tools you will need

  • Maven 3.0+ is your build tool
  • Your favorite IDE. We use Eclipse.
  • JDK 1.8+

Complete Maven Project With Code Examples

Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-content-negotiation

What is Content Negotiation?

REST stands for REpresentational State Transfer.

Key abstraction in REST is a Resource. There is no restriction on what can be a resource. A todo is a resource. A person on facebook is a resource.

A resource can have multiple representations

  • XML
  • HTML
  • JSON

When a resource is requested, we provide the representation of the resource.

When a consumer sends a request, it can specify two HTTP Headers related to Content Negotiation

  • Accept and
  • Content-Type

Content-Type indicates the content type of the body of the request.

Accept indicates the expected content type of the response.

Example of Content Negotiation

Following screen shot shows how you can specify these headers in a request using Postman. Image

The server is expected to respond based on the Accept header.

For example, if a consumer sends a request to http://localhost:8080/students/10001 with Accept header as ‘application/xml’, we need to provide the xml representation of the resource.

<Student>
    <id>10001</id>
    <name>Ranga</name>
    <passportNumber>E1234567</passportNumber>
</Student>

If a consumer sends a request with Accept header as ‘application/json’, we need to provide the JSON representation of the resource.

{
  "id": 10001,
  "name": "Ranga",
  "passportNumber": "E1234567"
}

Similar concept applies to the Response Body Content based on the Content-Type.

A consumer can send a POST request to http://localhost:8080/students with Content-Type header as ‘application/xml’, and provide the XML representation of the resource to be created.

<Student>
    <name>Ranga</name>
    <passportNumber>E1234567</passportNumber>
</Student>

A consumer can also send a POST request to http://localhost:8080/students with Content-Type header as ‘application/json’, and provide the JSON representation of the resource to be created.

{
  "name": "Ranga",
  "passportNumber": "E1234567"
}

This dialog which happens between the Consumer and Service Provider is called Content Negotiation.

Bootstrapping a Project with a REST Resource

In the previous article in the series - http://www.springboottutorial.com/spring-boot-crud-rest-service-with-jpa-hibernate, we set up a simple restful service with a resource exposing CRUD methods.

We will use the same example to discuss about Content Negotiation.

Implementing Content Negotiation with Spring Boot

Let’s execute a few requests to discover that content negotiation is not provided by default by the project we created with Spring Boot Starter Web and move on the adding content negotiation to our application.

Executing a request with Accept Header ‘application/xml’

Send a request to http://localhost:8080/students/10001 with Accept header as ‘application/xml’.

You are expecting to get an XML representation of the resource.

However you would get a response with status -> 406 Not Acceptable. This indicates that application does not support providing a response with content type ‘application/xml’.

However if you send a request to http://localhost:8080/students/10001 with Accept header as ‘application/json’, you would get the response back as expected.

{
  "id": 10001,
  "name": "Ranga",
  "passportNumber": "E1234567"
}

Implementing XML Representation for Spring Boot Services

Its simple. All that you would need to do is to add a simple dependency to your pom.xml.

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

Restart your application.

Send a request to http://localhost:8080/students/10001 with Accept header as ‘application/xml’.

Response

<Student>
    <id>10001</id>
    <name>Ranga</name>
    <passportNumber>E1234567</passportNumber>
</Student>

Cool! Your application now supports both XML and JSON representations of the student resource.

You can use

  • Content-Type to indicate content type of the body for POST and PUT requests.
  • Accept indicates the expected content type of the response for GET requests.

Playing with Content Negotiation

GET Request

  • URL - http://localhost:8080/students
  • Request Method - GET
  • Request Headers
    • Accept - application/xml

Response

<List>
    <item>
        <id>10001</id>
        <name>Ranga</name>
        <passportNumber>E1234567</passportNumber>
    </item>
    <item>
        <id>10002</id>
        <name>Ravi</name>
        <passportNumber>A1234568</passportNumber>
    </item>
</List>

POST Request

  • URL - http://localhost:8080/students
  • Request Method - POST
  • Request Headers
    • Content-Type - application/xml

Request

    <item>
        <name>Tom</name>
        <passportNumber>Z1234567</passportNumber>
    </item>

Response

  • Status 201 - CREATED
  • Header Location →http://localhost:8080/students/2

PUT Request

  • URL → http://localhost:8080/students/10002
  • Request
    • Method → PUT
  • Request Headers
    • Content-Type - application/xml

Request

<item>
    <name>Tom</name>
    <passportNumber>Z1234567</passportNumber>
</item>

Response with status 204 - No Content

Complete Maven Project With Code Examples

Our Github repository has all the code examples - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-content-negotiation

8 AWS Certification Courses

We are releasing courses for 3 Certifications under 3 categories - STEP BY STEP, EXAM REVIEW and PRACTICE TESTS:

  • Step by Step courses are for you if you are getting started with AWS
  • Exam Review courses help you to quickly review for the exam in a few hours
  • Practice Tests help you to test your preparation - How ready are you for the exam?

STEP BY STEP COURSES: ZERO AWS KNOWLEDGE? Start your journey now!

EXAM REVIEW COURSES: You prepare for the exam for 1-6 months. How do you remember everything you studied? Review for the exam in under 6 HOURS using this crash courses!

PRACTICE TESTS: Test yourselves for the certification exam with our practice tests

Best Selling Udemy Courses

Image
Image Image Image Image Image Image Image Image Image Image Image

Join 450,000 Learners and 30+ Amazing Courses

350,000 Learners are learning everyday with our Best Selling Courses : Spring Boot Microservices, Spring, Spring Boot, Web Services, Hibernate, Full Stack React, Full Stack Angular, Python, Spring Interview Guide, Java Interview, Java Functional Programming, AWS, Docker, Kubernetes, PCF, AWS Fargate and Azure


Do not know where to start your learning journey? Check out our amazing learning paths:
Learning Path 01 - Spring and Spring Boot Web Applications and API Developer,
Learning Path 02 - Full Stack Developer with Spring Boot, React & Angular,
Learning Path 03 - Cloud Microservices Developer with Docker and Kubernetes,
Learning Path 04 - Learn Cloud with Spring Boot, AWS, Azure and PCF and
Learning Path 05 - Learn AWS with Microservices, Docker and Kubernetes


Subscribe

FREE COURSES



Related Posts

Understanding jwt token

Let us understand the json web tokens

Single sign-on workflow

Let us understand the single sign-on workflow

Oauth2.0 - Resource Owner Password Credentials grant workflow

Let us understand the Oauth2.0 Resource Owner Password Credentials grant workflow

Oauth2.0 - Implicit grant workflow

Let us understand the Oauth2.0 implicit grant workflow

Oauth2.0 - Client Credentials grant workflow

Let us understand the Oauth2.0 client credentials grant workflow

Oauth2.0 - Authorization grant workflow

Let us understand the Oauth2.0 authorization grant workflow

Writing Integration Tests for Rest Services with Spring Boot

Setting up a basic REST Service with Spring Boot is a cake walk. We will go one step further and add great integration tests!

Integrating Spring Boot and Spring JDBC with H2 and Starter JDBC

Learn using Spring Boot Starter JDBC to connect Spring Boot to H2 (in memory database) using Spring JDBC. You will create a simple project with Spring Boot. You will add code to the project to connect to a database using Spring JDBC. You will learn to implement the basic CRUD methods.

JUnit Tutorial for Beginners in 5 Steps

JUnit Tutorial for Beginners in 5 Steps. Setting up a basic JUnit example and understanding the basics of junit.

JPA and Hibernate Tutorial For Beginners - 10 Steps with Spring Boot and H2

JPA and Hibernate in 10 Steps with H2 - Setting up a basic project example with Spring Boot and in memory database H2. Its a cake walk.


Search