0
0
Rest APIprogramming~30 mins

Content negotiation in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Content Negotiation in a REST API
📖 Scenario: You are building a simple REST API that returns user information. Different clients want the data in different formats, like JSON or XML.
🎯 Goal: Create a REST API endpoint that returns user data. Use content negotiation to send JSON if the client asks for 'application/json' and XML if the client asks for 'application/xml'.
📋 What You'll Learn
Create a dictionary called user with keys 'name' and 'age' and values 'Alice' and 30
Create a variable called accept_header with the value 'application/json' or 'application/xml'
Write an if statement to check if accept_header is 'application/json' or 'application/xml'
Print the user data as JSON if accept_header is 'application/json'
Print the user data as XML if accept_header is 'application/xml'
💡 Why This Matters
🌍 Real World
APIs often need to send data in different formats depending on what the client wants. Content negotiation helps decide the format automatically.
💼 Career
Understanding content negotiation is important for backend developers building APIs that work well with many clients and devices.
Progress0 / 4 steps
1
Create the user data dictionary
Create a dictionary called user with these exact entries: 'name': 'Alice' and 'age': 30
Rest API
Need a hint?

Use curly braces to create a dictionary. The keys are strings 'name' and 'age'. The values are 'Alice' and 30.

2
Set the Accept header variable
Create a variable called accept_header and set it to the string 'application/json'
Rest API
Need a hint?

Just assign the string 'application/json' to the variable accept_header.

3
Write the content negotiation logic
Write an if statement that checks if accept_header is 'application/json' or 'application/xml'
Rest API
Need a hint?

Use if and elif to check the value of accept_header.

4
Print user data in the requested format
Inside the if block for 'application/json', print the user dictionary as JSON using json.dumps(user). Inside the elif block for 'application/xml', print the user dictionary as XML with tags <user>, <name>, and <age>. Import the json module at the top.
Rest API
Need a hint?

Use json.dumps(user) to convert the dictionary to a JSON string. For XML, build a string with tags and values.