Python
Overview
Python client for unkey
unkey.py
An asynchronous Python SDK for accessing the Unkey API.
Installation
Python version 3.8 or greater is required to use unkey.py.
Stable
pip install -U unkey.py
Development
pip install -U git+https://github.com/Jonxslays/unkey.py
For more information on using pip
, check out the pip documentation.
Examples
Verifying an api key manually
import asyncio
import os
import unkey
async def main() -> None:
# NOTE: Verifying keys don't require an unkey root api key
# but all other endpoints the client hits do
client = unkey.Client(api_key=os.environ["API_KEY"])
await client.start()
result = await client.keys.verify_key("prefix_123ABC", "api_345")
if result.is_ok:
data = result.unwrap()
print(data.valid)
print(data.owner_id)
print(data.meta)
print(data.error)
else:
print(result.unwrap_err())
await client.close()
if __name__ == "__main__":
asyncio.run(main())
Using the protected
decorator
import os
from typing import Any, Dict, Optional
import fastapi # pip install fastapi
import unkey # pip install unkey.py
import uvicorn # pip install uvicorn
app = fastapi.FastAPI()
def key_extractor(*args: Any, **kwargs: Any) -> Optional[str]:
if isinstance(auth := kwargs.get("authorization"), str):
return auth.split(" ")[-1]
return None
@app.get("/protected")
@unkey.protected(os.environ["UNKEY_API_ID"], key_extractor)
async def protected_route(
*,
authorization: str = fastapi.Header(None),
unkey_verification: Any = None,
) -> Dict[str, Optional[str]]:
assert isinstance(unkey_verification, unkey.ApiKeyVerification)
assert unkey_verification.valid
print(unkey_verification.owner_id)
return {"message": "protected!"}
if __name__ == "__main__":
uvicorn.run(app)
Other examples may omit the async main function, setup, and imports for brevity.
Guides
Other Links
Was this page helpful?