0
0
Rest-apiHow-ToBeginner ยท 3 min read

How to Use Nested Resources in REST API: Syntax and Examples

In a REST API, nested resources represent a hierarchy where one resource belongs to another, shown by URLs like /parents/{parentId}/children/{childId}. Use nested paths to clearly express relationships and scope actions to specific parent resources.
๐Ÿ“

Syntax

Nested resources use URL paths that show the parent-child relationship between resources. The general pattern is:

  • /parentResource/{parentId}/childResource/{childId}
  • parentResource is the main resource (e.g., users)
  • childResource is the related resource (e.g., posts)
  • {parentId} and {childId} are identifiers for specific items

This structure scopes the child resource under the parent, making the relationship clear.

http
/users/{userId}/posts/{postId}
๐Ÿ’ป

Example

This example shows a simple REST API using nested resources to get posts of a specific user. The URL /users/42/posts fetches all posts for user with ID 42.

python
from flask import Flask, jsonify

app = Flask(__name__)

# Sample data
users = {
    42: {"name": "Alice", "posts": [
        {"id": 1, "title": "Hello World"},
        {"id": 2, "title": "REST APIs"}
    ]}
}

@app.route('/users/<int:user_id>/posts', methods=['GET'])
def get_user_posts(user_id):
    user = users.get(user_id)
    if not user:
        return jsonify({"error": "User not found"}), 404
    return jsonify(user["posts"])

if __name__ == '__main__':
    app.run(debug=True)
Output
[{"id": 1, "title": "Hello World"}, {"id": 2, "title": "REST APIs"}]
โš ๏ธ

Common Pitfalls

Common mistakes when using nested resources include:

  • Not validating the parent resource exists before accessing the child resource, which can cause errors or incorrect data.
  • Over-nesting resources, making URLs too long and complex.
  • Ignoring HTTP methods and using the same URL for unrelated actions.

Always check the parent resource first and keep nesting to a reasonable depth (usually 1 or 2 levels).

python
Wrong approach (no parent check):

@app.route('/users/<int:user_id>/posts/<int:post_id>')
def get_post(post_id):
    # This ignores user_id and may return wrong post
    post = find_post_by_id(post_id)
    return jsonify(post)

Right approach (validate parent):

@app.route('/users/<int:user_id>/posts/<int:post_id>')
def get_post(user_id, post_id):
    user = users.get(user_id)
    if not user:
        return jsonify({"error": "User not found"}), 404
    post = next((p for p in user["posts"] if p["id"] == post_id), None)
    if not post:
        return jsonify({"error": "Post not found"}), 404
    return jsonify(post)
๐Ÿ“Š

Quick Reference

Tips for using nested resources in REST APIs:

  • Use clear, plural nouns for resource names (e.g., users, posts).
  • Keep nesting shallow to avoid complex URLs.
  • Always validate parent resource existence before accessing children.
  • Use HTTP methods properly: GET to read, POST to create, PUT/PATCH to update, DELETE to remove.
  • Design URLs to reflect resource relationships clearly.
โœ…

Key Takeaways

Nested resources use URL paths that show parent-child relationships clearly.
Always check the parent resource exists before accessing or modifying child resources.
Keep nested URLs simple and avoid deep nesting to maintain clarity.
Use HTTP methods correctly to represent actions on nested resources.
Design your API URLs to reflect real-world relationships between resources.