badge-checkValidate Api Key

Verify an incoming API key and get its identity.

circle-info

When to use: On every protected API endpoint that accepts API key authentication.

chevron-rightPrerequisiteshashtag

5-Line Core

identity = await api_key_provider.validate_api_key(api_key)
if identity:
    print(f"Valid! Scopes: {identity.scopes}")
else:
    print("Invalid key")

Step-by-Step

1

Extract API Key from Request

# Typically from X-API-Key header
api_key = request.headers.get("X-API-Key")
if not api_key:
    raise HTTPException(status_code=401, detail="Missing API key")
2

Validate the Key

identity = await api_key_provider.validate_api_key(api_key)
3

Check Result

if identity is None:
    raise HTTPException(status_code=401, detail="Invalid API key")

print(f"Key ID: {identity.api_key_id}")
print(f"Tier: {identity.tier}")
print(f"Scopes: {identity.scopes}")
4

Check Scopes

if not identity.has_scope("api:write"):
    raise HTTPException(status_code=403, detail="Insufficient scope")

# Proceed with operation
5

Expected Output

Key ID: 550e8400-e29b-41d4-a716-446655440000
Tier: organization
Scopes: ['api:read', 'api:write']
circle-check

Complete Example

Create validate_api_key.py:

Run it:

Expected output:

FastAPI Integration

Common Pitfalls

Pitfall
Solution

Not checking scopes

Always verify required scopes

Exposing key details

Only log key ID, never full key

Wrong status codes

401 for invalid key, 403 for missing scope

Last updated

Was this helpful?