Skip to main content

Overview

This guide covers everything you need to protect your Python API with Unkey, including integrations for FastAPI, Flask, and Django using the official Python SDK. What you’ll learn:
  • Quick setup with the Unkey Python SDK
  • FastAPI dependency injection patterns
  • Flask middleware implementation
  • Django middleware integration
  • Creating and managing API keys
  • Production-ready error handling

Prerequisites

Installation

Setup Credentials

Get a root key from Settings → Root Keys and set it as an environment variable:

FastAPI Integration

FastAPI’s dependency injection system makes it easy to add authentication.

Basic Dependency

dependencies/auth.py

Use in Routes

main.py
Run your FastAPI app:
Test with a valid API key:

Permission-Based Access

Create dependencies for different permission levels:
dependencies/auth.py
Use in routes:
main.py

Rate Limit Headers

Return rate limit info in response headers:
dependencies/auth.py

Flask Integration

For Flask applications:
app.py

Flask Middleware

Create reusable middleware:
middleware/auth.py
Use it:
app.py

Django Integration

Create a custom middleware:
middleware/unkey_auth.py
Add to settings:
settings.py
Use in views:
views.py

Creating API Keys

Here’s how to create API keys programmatically:
The full API key is only returned once at creation. Store it securely and never show it again.

Error Handling

Always handle Unkey errors gracefully:

Next Steps

Add rate limiting

Protect your endpoints from abuse

Python SDK Reference

Complete Python SDK documentation

Authorization

Add roles and permissions

Cookbook

More Python recipes and examples