0
0
Rest APIprogramming~30 mins

Bearer token authentication in Rest API - Mini Project: Build & Apply

Choose your learning style9 modes available
Bearer Token Authentication
📖 Scenario: You are building a simple REST API that requires users to authenticate using a bearer token. This is a common way to secure APIs by sending a secret token with each request.
🎯 Goal: Create a REST API endpoint that checks for a bearer token in the request headers and returns a success message if the token is valid, or an error message if it is missing or invalid.
📋 What You'll Learn
Create a variable called VALID_TOKEN with the exact value 'abc123token'.
Create a function called check_token that takes a headers dictionary as input.
In check_token, check if the Authorization header exists and starts with 'Bearer '.
Extract the token from the Authorization header and compare it to VALID_TOKEN.
Return True if the token matches, otherwise False.
Create a function called api_endpoint that takes a headers dictionary as input.
Use check_token inside api_endpoint to verify the token.
Return the string 'Access granted' if the token is valid, or 'Access denied' if not.
Print the result of calling api_endpoint with the headers {'Authorization': 'Bearer abc123token'}.
💡 Why This Matters
🌍 Real World
Bearer token authentication is widely used to secure APIs in web and mobile apps. It helps ensure that only authorized users can access protected resources.
💼 Career
Understanding bearer token authentication is essential for backend developers, API developers, and anyone working with secure web services.
Progress0 / 4 steps
1
Create the valid token variable
Create a variable called VALID_TOKEN and set it to the string 'abc123token'.
Rest API
Need a hint?

Think of VALID_TOKEN as the secret key that the API will accept.

2
Create the token check function
Create a function called check_token that takes a parameter headers. Inside the function, check if the Authorization header exists in headers and starts with 'Bearer '. Return True if the token after 'Bearer ' matches VALID_TOKEN, otherwise return False.
Rest API
Need a hint?

Use headers.get('Authorization', '') to safely get the header. Then check if it starts with 'Bearer '. Extract the token by slicing the string after 'Bearer '.

3
Create the API endpoint function
Create a function called api_endpoint that takes a parameter headers. Inside the function, use check_token(headers) to verify the token. Return the string 'Access granted' if the token is valid, otherwise return 'Access denied'.
Rest API
Need a hint?

Use an if statement to check the result of check_token(headers). Return the correct string based on the result.

4
Print the API endpoint result
Print the result of calling api_endpoint with the headers dictionary {'Authorization': 'Bearer abc123token'}.
Rest API
Need a hint?

Use print() to show the result of api_endpoint called with the correct headers.