0
0
Rest APIprogramming~30 mins

Per-user vs per-IP limits in Rest API - Hands-On Comparison

Choose your learning style9 modes available
Implementing Per-User and Per-IP Rate Limits in a REST API
📖 Scenario: You are building a simple REST API server that needs to control how many requests each user and each IP address can make. This helps keep the server safe and fair for everyone.
🎯 Goal: Build a basic Python REST API that tracks requests and limits them per user and per IP address.
📋 What You'll Learn
Create a dictionary called user_requests to track requests per user ID
Create a dictionary called ip_requests to track requests per IP address
Set a limit variable called MAX_REQUESTS to 3
Write a function can_make_request(user_id, ip_address) that returns True if both user and IP are under the limit, otherwise False
Print the result of calling can_make_request for a test user and IP
💡 Why This Matters
🌍 Real World
APIs often need to limit how many requests a user or IP can make to prevent overload or abuse.
💼 Career
Understanding rate limiting is important for backend developers and API designers to build reliable and secure services.
Progress0 / 4 steps
1
Create dictionaries to track requests
Create two empty dictionaries called user_requests and ip_requests to keep track of how many requests each user and IP address has made.
Rest API
Need a hint?

Use curly braces {} to create empty dictionaries.

2
Set the maximum allowed requests
Create a variable called MAX_REQUESTS and set it to 3. This will be the limit for requests per user and per IP.
Rest API
Need a hint?

Just assign the number 3 to the variable MAX_REQUESTS.

3
Write the function to check request limits
Write a function called can_make_request(user_id, ip_address) that: - Checks how many requests the user_id has made using user_requests (default 0 if not found) - Checks how many requests the ip_address has made using ip_requests (default 0 if not found) - Returns True only if both counts are less than MAX_REQUESTS, otherwise returns False
Rest API
Need a hint?

Use the get method on dictionaries to get counts with a default of 0.

4
Test the function with sample data
Add some sample counts to user_requests and ip_requests for user_id = 'user123' and ip_address = '192.168.1.1'. Then print the result of calling can_make_request('user123', '192.168.1.1').
Rest API
Need a hint?

Set the counts below the limit and then print the function call result.