0
0
Rest APIprogramming~30 mins

Rate limit error responses in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Rate Limit Error Responses
📖 Scenario: You are building a simple REST API that limits how many requests a user can make in a short time. If the user sends too many requests, the API should respond with a clear error message and status code.
🎯 Goal: Create a basic API endpoint that tracks request counts per user and returns a rate limit error response when the limit is exceeded.
📋 What You'll Learn
Create a dictionary called request_counts to store user request counts.
Create a variable called MAX_REQUESTS and set it to 3.
Write a function called check_rate_limit(user_id) that increases the count for the user and returns True if under limit, False if limit exceeded.
Print the error response {"error": "Rate limit exceeded", "status": 429} when the limit is exceeded.
💡 Why This Matters
🌍 Real World
APIs often limit how many requests a user can make to protect servers and ensure fair use.
💼 Career
Understanding rate limiting is important for backend developers and API designers to build reliable and secure services.
Progress0 / 4 steps
1
Create the request count dictionary
Create a dictionary called request_counts that is empty initially.
Rest API
Need a hint?

Use curly braces {} to create an empty dictionary.

2
Set the maximum allowed requests
Create a variable called MAX_REQUESTS and set it to 3.
Rest API
Need a hint?

Just assign the number 3 to the variable MAX_REQUESTS.

3
Write the rate limit check function
Write a function called check_rate_limit(user_id) that does the following:
1. If user_id is not in request_counts, add it with value 1.
2. If user_id is already in request_counts, increase its count by 1.
3. Return True if the count is less than or equal to MAX_REQUESTS, otherwise return False.
Rest API
Need a hint?

Use an if statement to check if the user is new, then update counts accordingly.

4
Print the rate limit error response
Call check_rate_limit("user1") five times in a loop. For each call, if it returns False, print the exact string {"error": "Rate limit exceeded", "status": 429}.
Rest API
Need a hint?

Use a for loop to call the function 5 times and print the error message only when the function returns False.