0
0
Rest APIprogramming~15 mins

401 Unauthorized vs 403 Forbidden in Rest API - Hands-On Comparison

Choose your learning style9 modes available
Understanding 401 Unauthorized vs 403 Forbidden in REST APIs
📖 Scenario: You are building a simple REST API server that controls access to a resource. You want to understand the difference between 401 Unauthorized and 403 Forbidden HTTP status codes by simulating them in your API responses.
🎯 Goal: Create a small Python program that simulates API responses with status codes 401 and 403 based on user authentication and permission checks.
📋 What You'll Learn
Create a dictionary called users with usernames as keys and a boolean is_authenticated as values.
Create a variable called resource_permission that stores whether the user has permission to access the resource.
Write a function called check_access that takes a username and returns 401 if the user is not authenticated, 403 if authenticated but no permission, or 200 if access is allowed.
Print the result of check_access for two users: one not authenticated and one authenticated but without permission.
💡 Why This Matters
🌍 Real World
APIs often need to tell clients why access is denied. Using 401 and 403 correctly helps clients understand if they need to log in or if they lack permission.
💼 Career
Backend developers and API designers must know how to use HTTP status codes properly to build secure and user-friendly APIs.
Progress0 / 4 steps
1
Create the users dictionary
Create a dictionary called users with these exact entries: 'alice': False and 'bob': True representing their authentication status.
Rest API
Need a hint?

Use curly braces to create a dictionary and separate entries with commas.

2
Add resource permission variable
Create a variable called resource_permission and set it to False to represent that the user does not have permission to access the resource.
Rest API
Need a hint?

Just assign False to the variable resource_permission.

3
Write the check_access function
Write a function called check_access that takes a parameter username. Inside the function, check if users[username] is False, then return 401. Else if resource_permission is False, return 403. Otherwise, return 200.
Rest API
Need a hint?

Use if and elif statements to check conditions and return the correct status code.

4
Print access check results
Print the result of check_access('alice') and check_access('bob') on separate lines to show the status codes for an unauthenticated user and an authenticated user without permission.
Rest API
Need a hint?

Use two print statements, one for each user.