0
0
Rest APIprogramming~30 mins

Nested resources in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Nested Resources in a REST API
📖 Scenario: You are building a simple REST API for a blog. Each blog has many posts. You want to organize your API so that posts are nested inside blogs. This means the URL for posts will include the blog they belong to, like /blogs/1/posts.
🎯 Goal: Create a basic REST API with nested resources where posts belong to blogs. You will define the data, set up a route prefix for blogs, create a nested route for posts inside blogs, and finally show how to get all posts for a specific blog.
📋 What You'll Learn
Create a dictionary called blogs with two blogs, each having an id and name.
Create a list called posts with posts that include id, blog_id, and title.
Define a variable blog_id to select which blog's posts to get.
Write a function get_posts_for_blog(blog_id) that returns posts belonging to the given blog.
Print the titles of posts for the selected blog.
💡 Why This Matters
🌍 Real World
Nested resources are common in REST APIs to organize related data clearly, like posts inside blogs or comments inside posts.
💼 Career
Understanding nested resources helps you design clean and scalable APIs, a key skill for backend developers and API designers.
Progress0 / 4 steps
1
Create the initial data structures
Create a dictionary called blogs with these exact entries: 1: {'id': 1, 'name': 'Tech Blog'} and 2: {'id': 2, 'name': 'Food Blog'}. Also create a list called posts with these exact dictionaries: {'id': 1, 'blog_id': 1, 'title': 'New Python Features'}, {'id': 2, 'blog_id': 1, 'title': 'REST API Tips'}, and {'id': 3, 'blog_id': 2, 'title': 'Best Pizza Recipes'}.
Rest API
Need a hint?

Think of blogs as a dictionary where keys are blog IDs and values are blog details. posts is a list of dictionaries, each with a blog ID to show which blog it belongs to.

2
Set the blog ID to filter posts
Create a variable called blog_id and set it to 1 to select the Tech Blog.
Rest API
Need a hint?

This variable will help us get posts only for the selected blog.

3
Create a function to get posts for a blog
Write a function called get_posts_for_blog(blog_id) that returns a list of posts from posts where the post's blog_id matches the function's blog_id parameter.
Rest API
Need a hint?

Use a list comprehension to filter posts where post['blog_id'] equals the function's blog_id parameter.

4
Print the titles of posts for the selected blog
Use the function get_posts_for_blog(blog_id) to get posts for the blog with blog_id. Then print each post's title on its own line.
Rest API
Need a hint?

Call the function with blog_id and loop over the returned posts to print each title.