0
0
Rest APIprogramming~30 mins

Why consistent formats improve usability in Rest API - See It in Action

Choose your learning style9 modes available
Why Consistent Formats Improve Usability in REST APIs
📖 Scenario: You are building a simple REST API for a bookstore. The API returns book information in JSON format. To make it easy for developers to use your API, you want to keep the response format consistent.
🎯 Goal: Build a REST API endpoint that returns book data in a consistent JSON format. You will create the data, set a configuration for the response format, apply the main logic to format the data consistently, and finally output the JSON response.
📋 What You'll Learn
Create a list of dictionaries representing books with exact keys and values
Add a configuration variable to control the response format
Use a function to format each book's data consistently
Print the final JSON response with consistent formatting
💡 Why This Matters
🌍 Real World
APIs are used by many developers and apps. Consistent data formats reduce confusion and bugs.
💼 Career
Understanding how to design and format API responses is important for backend developers and API designers.
Progress0 / 4 steps
1
Create the book data list
Create a list called books with these exact dictionaries: {'id': 1, 'title': '1984', 'author': 'George Orwell'}, {'id': 2, 'title': 'To Kill a Mockingbird', 'author': 'Harper Lee'}, and {'id': 3, 'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald'}.
Rest API
Need a hint?

Use a list with three dictionaries exactly as shown.

2
Add a response format configuration
Create a variable called response_format and set it to the string 'json'.
Rest API
Need a hint?

Just assign the string 'json' to the variable response_format.

3
Format the book data consistently
Create a function called format_book that takes a book dictionary and returns a new dictionary with keys 'bookId', 'bookTitle', and 'bookAuthor' mapped from book['id'], book['title'], and book['author'] respectively. Then create a list called formatted_books by applying format_book to each book in books.
Rest API
Need a hint?

Use a function to rename keys and a list comprehension to apply it to all books.

4
Print the JSON response
Import the json module and print the JSON string of formatted_books using json.dumps() with indent=2 for readability.
Rest API
Need a hint?

Use json.dumps() with indent=2 to print the list nicely.