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 30Create 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