Skip to main content

Check permissions with the Python SDK (asyncio)

Connect a Python application that uses asyncio to Permit.io and call permit.check() to allow or deny a request. This quickstart is for backend developers who have a Permit.io policy and want to enforce the policy from Python code. At the end, a FastAPI app returns an allow or deny result for each request, and the check appears in the Permit audit log. If your code doesn't use asyncio, see Check permissions with the Python SDK (sync).

Prerequisites

  • A Permit.io account with at least one policy. If you don't have a policy yet, complete the Quickstart.
  • Docker, if you run the policy decision point (PDP) as a container. See Install Docker.

1. Get your environment API key

The SDK and the PDP authenticate with Permit using an environment API key. Each API key belongs to one environment.

  1. In the Permit dashboard, open the Projects screen.
  2. Find the project and the environment you want to connect to.
  3. On the environment card, click the Three dots menu icon icon in the top-right corner.
  4. Click Copy API Key.
Projects screen with the environment card menu open and Copy API Key highlighted
Copy the API key from the user menu

You can also copy the API key of the active environment from User Menu > Copy Environment Key.

User menu open with Copy Environment Key highlighted
The user menu copies the active environment's key

The API key you copy from the user menu belongs to the active environment in the sidebar. If you switch the active environment and click Copy Environment Key again, you copy a different API key: the key of the newly active environment.

Keep the API key out of source control

Anyone with your environment API key can change that environment's policy and data through the Permit API. Load the API key from an environment variable or a secret store, and don't commit the API key to your repository.

2. Set up your policy decision point (PDP)

Your application sends each permission check to a policy decision point (PDP), the service that evaluates the check against your policy. Use the managed Cloud PDP that Permit.io runs, or run the PDP as a Docker container on your machine.

The SDK examples on this page connect to a container PDP at http://localhost:7766. To use the Cloud PDP, set the SDK's PDP URL to https://cloudpdp.api.permit.io instead.

The Cloud PDP needs no installation. Pass the Cloud PDP URL when you initialize the Permit SDK. The following Node.js example shows the shape. The SDK install step further down shows the same setting in this page's language. Replace [YOUR_API_KEY] with your environment API key:

// This line initializes the SDK and connects your app
// to the Permit.io Cloud PDP.

const permit = new Permit({
pdp: "https://cloudpdp.api.permit.io",
// your API Key
token: "[YOUR_API_KEY]",
});
Cloud PDP policy models

The Cloud PDP is a managed service that Permit.io runs. The Cloud PDP supports RBAC (role-based access control) and ReBAC (relationship-based access control) policies. The Cloud PDP does not support ABAC (attribute-based access control) policies, so the ABAC examples on this page need a container PDP.

For capabilities, limits, and when to choose each PDP type, see Cloud PDP capabilities.

3. Install the Python SDK and check permissions

Install and initialize the Python SDK (asyncio)

Install the permit package, import the Permit class, and create a Permit client that connects to your PDP. The Permit class in the permit module uses asyncio. If your code doesn't use asyncio, use the sync Python SDK instead.

  1. Install the Permit.io Python SDK:
pip install permit
  1. Import the Permit class:
from permit import Permit
  1. Create a Permit client. Replace <YOUR_API_KEY> with your environment API key, and set pdp to the URL of your PDP:
# Connect the SDK to the PDP that evaluates permission checks.
permit = Permit(
# your environment API key
token="<YOUR_API_KEY>",

# in production, change this URL to the address of your PDP
pdp="http://localhost:7766",

# optional, the timeout in seconds for requests to the PDP (supported from version 2.5.0)
pdp_timeout=5,
# optional, the timeout in seconds for requests to the Permit API (supported from version 2.5.0)
api_timeout=5,
)
OptionDescription
tokenYour environment API key.
pdpThe URL of the PDP that evaluates checks: http://localhost:7766 for the container PDP, or https://cloudpdp.api.permit.io for the Cloud PDP.
pdp_timeoutOptional. Timeout in seconds for requests to the PDP. Available since SDK version 2.5.0.
api_timeoutOptional. Timeout in seconds for requests to the Permit API. Available since SDK version 2.5.0.

To send checks to the managed Cloud PDP instead of a container PDP, set pdp to the Cloud PDP URL:

permit = Permit(
token="<YOUR_API_KEY>",
pdp="https://cloudpdp.api.permit.io",
)

The Cloud PDP supports RBAC (role-based access control) and ReBAC (relationship-based access control) policies. ABAC (attribute-based access control) checks need a container PDP. See Cloud PDP capabilities.

Check permissions with the Python SDK (asyncio)

Call await permit.check() inside an async function, with three arguments. permit.check() returns True when the policy allows the action, and False otherwise.

ArgumentDescription
userThe key that identifies the user in Permit, typically the user ID from your authentication provider. To pass attributes, use a dictionary with key and attributes.
actionThe action key, for example create.
resourceThe resource type key, for example document, or a dictionary with type, tenant, and attributes.

This example checks whether the user john@smith.com can create a document:

import asyncio

from permit import Permit

permit = Permit(token="<YOUR_API_KEY>", pdp="http://localhost:7766")

async def main():
permitted = await permit.check("john@smith.com", "create", "document")

if permitted:
print("John is permitted to create a document")
else:
print("John is NOT PERMITTED to create document!")

asyncio.run(main())

If john@smith.com exists in your environment and has a role that grants create on document, the example prints John is permitted to create a document. Otherwise, the example prints John is NOT PERMITTED to create document!. To add users and assign roles, see Sync users.

Check a permission in a specific tenant

In a multi-tenant application, pass the tenant key in the tenant field of the resource dictionary. To look up the keys of your tenants, call the list tenants API.

This example checks whether john@permit.io can read documents in the awesome_inc tenant. Like every await permit.check() call, it runs inside an async function:

permitted = await permit.check(
# the key of the user
"john@permit.io",
# the action
"read",
# the resource (all resources of type document under the awesome_inc tenant)
{ "type": "document", "tenant": "awesome_inc" }
)
Where checks run and where user data is stored

permit.check() sends each check to the PDP URL you configure. A container PDP evaluates checks on your machine, using policy and data that the PDP loads from Permit. Users, roles, and attributes that you create in the dashboard or sync through the Permit API are stored in the Permit control plane.

Run a full Python example app (FastAPI)

This single-file FastAPI app runs a permission check on each request to its root URL.

  1. Create a directory for the project:
mkdir hello-permissions && cd hello-permissions
  1. Optional: create a virtual environment for the project. The following command needs pyenv and pyenv-virtualenv.
pyenv virtualenv permissions && pyenv activate permissions
  1. Install the Permit.io SDK, FastAPI, and Uvicorn, the server that runs the app:
pip install permit fastapi "uvicorn[standard]"
  1. Create a file called test.py:
touch test.py
  1. Copy the following code into test.py. Replace <YOUR_API_KEY> with your environment API key, and john@smith.com with the key of a user in your environment.

    The first part of test.py creates the FastAPI app, the Permit client, and the user the app checks:

from permit import Permit
from fastapi import FastAPI, status, HTTPException
from fastapi.responses import JSONResponse

app = FastAPI()

# Connect the SDK to the PDP that evaluates permission checks.
permit = Permit(
# in production, change this URL to the address of your PDP
pdp="http://localhost:7766",
# your environment API key
token="<YOUR_API_KEY>",
)

# The user must exist in your environment and have a role that grants the action.
# To create users and assign roles, see the Sync users guide.
user = {
"key": "john@smith.com",
"first_name": "John",
"last_name": "Smith",
"email": "john@smith.com",
} # in a real app, you would typically decode the user id from a JWT token

Append the route handler, which runs one check per request to / and answers 403 when the policy denies the action:

@app.get("/")
async def check_permissions():
permitted = await permit.check(user["key"], "read", "document")
if not permitted:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail={
"result": f"{user.get('first_name')} {user.get('last_name')} is NOT PERMITTED to read document!"
})

return JSONResponse(status_code=status.HTTP_200_OK, content={
"result": f"{user.get('first_name')} {user.get('last_name')} is PERMITTED to read document!"
})
  1. Start the app. Replace <YOUR_LOCALHOST_PORT_NUMBER> with a free port, for example 8000:
uvicorn test:app --reload --port=<YOUR_LOCALHOST_PORT_NUMBER>
  1. Open http://localhost:<YOUR_LOCALHOST_PORT_NUMBER> in a browser.

The app checks whether john@smith.com can read a document. If the policy allows the action, the app returns HTTP 200 with this body:

{"result": "John Smith is PERMITTED to read document!"}

Otherwise, the app returns HTTP 403 with the message John Smith is NOT PERMITTED to read document!. If the app returns is NOT PERMITTED and you expect an allow, check that john@smith.com has a role that grants read on document, and that the container PDP is running with an API key from the same environment.

Explore the Python example repository

The permit-python-example repository contains a FastAPI app that uses SQLAlchemy, PostgreSQL, and the Permit.io Python SDK. The example covers:

  • RBAC (role-based access control) policy
  • ABAC policy
  • ReBAC (relationship-based access control) policy
  • Terraform setup

Check ABAC permissions with the Python SDK (asyncio)

An attribute-based access control (ABAC) policy grants permissions based on user and resource attributes, grouped into user sets and resource sets. See ABAC policy components. ABAC checks need a container PDP.

To check an ABAC policy, pass the user and the resource as dictionaries that carry the attributes the policy compares. In this example, replace check@permit.io, action, resource, and tenant with a user key, action key, resource key, and tenant key from your environment:

permitted = await permit.check(
# the user object
{
# the user key
"key": "check@permit.io",
# just-in-time attributes on the user
"attributes": {
"location": "England",
"department": "Engineering",
},
},
# the action the user is trying to do
"action",
# the resource the user is trying to act on
{
# the type of the resource (the resource key)
"type": "resource",
# just-in-time attributes on the resource
"attributes": {
"hasApproval": "true",
},
# the tenant the resource belong to
"tenant": "tenant",
}
)

For more check options, see Check permissions with permit.check().

4. Confirm the check in the audit log

Open the Audit Log screen in the Permit dashboard. Each permission check from your application appears as an entry with the user, the action, the resource, and the decision.

If the check doesn't appear in the audit log, see Troubleshoot audit logs.

Next steps