Bird
0
0
FastAPIframework~30 mins

Password hashing with bcrypt in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Password hashing with bcrypt in FastAPI
📖 Scenario: You are building a simple FastAPI app that needs to securely store user passwords. Instead of saving plain text passwords, you will hash them using bcrypt.
🎯 Goal: Create a FastAPI app that hashes a given password using bcrypt and stores the hashed password in a dictionary.
📋 What You'll Learn
Use the bcrypt library to hash passwords
Create a FastAPI app with a POST endpoint to accept passwords
Store hashed passwords in a dictionary with usernames as keys
Do not store plain text passwords
💡 Why This Matters
🌍 Real World
Web applications must never store plain text passwords. Hashing passwords with bcrypt is a common and secure practice to protect user data.
💼 Career
Understanding password hashing and secure user authentication is essential for backend developers and anyone working on web security.
Progress0 / 4 steps
1
Set up FastAPI app and initial data storage
Import FastAPI from fastapi and create an app instance called app. Then create an empty dictionary called users_db to store usernames and hashed passwords.
FastAPI
Hint

Use app = FastAPI() to create the app and users_db = {} for storage.

2
Add bcrypt import and salt rounds configuration
Import bcrypt and create a variable called SALT_ROUNDS set to 12 to configure the hashing complexity.
FastAPI
Hint

Use import bcrypt and set SALT_ROUNDS = 12 for good security.

3
Create POST endpoint to hash and store password
Define a POST endpoint /register that accepts JSON with username and password. Hash the password using bcrypt.hashpw(password.encode(), bcrypt.gensalt(SALT_ROUNDS)) and store the hashed password as a UTF-8 string in users_db under the username key.
FastAPI
Hint

Use await request.json() to get data and bcrypt.hashpw to hash the password.

4
Add a GET endpoint to verify stored hashed password
Create a GET endpoint /users/{username} that returns the stored hashed password string for the given username from users_db. If the username is not found, return a JSON message {'error': 'User not found'}.
FastAPI
Hint

Use a path parameter username and check if it exists in users_db.