This simple Flask application demonstrates how to implement API key verification using the Unkey service. The application has both public and protected routes, with the protected route requiring a valid API key.
- Public Route: Accessible without any authentication.
- Protected Route: Requires a valid API key to access.
- Middleware: Utilizes a decorator to enforce unkey verification on protected routes.
- Create an unkey account
- Create a new API. Copy the
API ID. - Go to permissions and create a new permission named
withAuth - Now go to roles and create a new role and select the
withAuthpermission for the role. - Go to apis again and create a new key
- Click on the "Keys" tab.
- Select the key you created.
- Click on the "Permissions" tab.
- Check the role's checkbox to assign the role and permission to the key.
- Create a new root key from the settings/root-key
- Python 3.x
- Flask
- Requests library
- An account with Unkey and your API ID and Root Key
-
Clone this repository:
git clone https://github.com/harshsbhat/unkey-flask.git cd unkey-flask -
Set up a virtual environment (optional but recommended): :
python3 -m venv venv # For Linux/macOS source venv/bin/activate # For Linux/macOS python -m venv venv # For Windows venv\Scripts\activate # For Windows -
Set up your environment variables: Create a .env file in the project root and add the following variables. Get the Unkey API ID and Unkey rootkey from unkey dashboard
UNKEY_API_ID=your_unkey_api_id UNKEY_ROOT_KEY=your_unkey_root_key -
Install the required dependencies
pip install -r requirements.txt
-
Run the project:
python3 src/main.py # For MacOS/Linux python src/main.py # For windows
- Public Route: Visit
http://localhost:3000/publicto access the public route. - Protected Route: Use a tool like Postman or curl to send a GET request to
http://localhost:3000/protectedwith anAuthorizationheader containing your API key.
curl http://127.0.0.1:3000/publiccurl -H "Authorization: Bearer <api_key>" http://localhost:3000/protected