0
0
Spring Bootframework~30 mins

Content type negotiation in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Content Type Negotiation in Spring Boot
📖 Scenario: You are building a simple Spring Boot REST API that returns user information. Different clients may want the data in JSON or XML format.Content type negotiation allows the server to send the response in the format the client prefers.
🎯 Goal: Create a Spring Boot controller that returns user data and supports content type negotiation for JSON and XML.
📋 What You'll Learn
Create a User class with id and name fields
Create a REST controller with a GET endpoint /user
Configure the controller to return the User object
Enable content type negotiation so the response can be JSON or XML based on client request
💡 Why This Matters
🌍 Real World
APIs often need to serve different clients that prefer different data formats like JSON or XML. Content type negotiation makes your API flexible and user-friendly.
💼 Career
Understanding content type negotiation is essential for backend developers building RESTful services that interact with diverse clients.
Progress0 / 4 steps
1
Create the User class
Create a public class called User with two private fields: int id and String name. Add a public constructor that takes int id and String name as parameters and sets the fields.
Spring Boot
Need a hint?

Think of User as a simple box holding an id and a name. You need a constructor to put values inside.

2
Create the REST controller
Create a class called UserController annotated with @RestController. Add a method getUser annotated with @GetMapping("/user") that returns a new User object with id 1 and name "Alice".
Spring Boot
Need a hint?

Use @RestController to make the class a REST API controller. The @GetMapping("/user") marks the method as the GET endpoint.

3
Enable content type negotiation
Add the @RequestMapping(produces = {"application/json", "application/xml"}) annotation to the UserController class to allow the endpoint to produce both JSON and XML responses.
Spring Boot
Need a hint?

The @RequestMapping annotation with produces tells Spring Boot to support these response types.

4
Add XML support dependency
Add the spring-boot-starter-web and jackson-dataformat-xml dependencies to your pom.xml or build.gradle to enable XML serialization support in Spring Boot.
Spring Boot
Need a hint?

Spring Boot needs the XML data format library to convert objects to XML.