FastAPI Backend Integration

For the full FastAPI Library Reference, click here.

Quick example

The following example creates a route which can only be accessed from logged-in users.

from fastapi import FastAPI, Depends
from propelauth_fastapi import init_auth, User

app = FastAPI()
auth = init_auth("YOUR_AUTH_URL", "YOUR_API_KEY")

@app.get("/")
async def root(current_user: User = Depends(auth.require_user)):
    return {"message": f"Hello {current_user.user_id}"}

You can find your Auth URL and API key(s) under the Backend Integration section for your project at https://app.propelauth.com

How it works

For a detailed description of what’s going on under the hood, see here.

Installation

$ pip install propelauth_fastapi

Initialize

init_auth performs a one-time initialization of the library. It will verify your api_key is correct and fetch the metadata needed to verify access tokens in require_user, optional_user, or require_org_member.

from propelauth_fastapi import init_auth

auth = init_auth("YOUR_AUTH_URL", "YOUR_API_KEY")

Protect API routes

require_user

A dependency that will verify the request was made by a valid user. If a valid access token is provided, it will return that user’s information (including fields like a user_id). If not, the request is rejected with a 401 status code.

from fastapi import FastAPI, Depends
from propelauth_fastapi import init_auth, User

app = FastAPI()
auth = init_auth("AUTH_URL", "API_KEY")

@app.get("/")
async def root(current_user: User = Depends(auth.require_user)):
    return {"message": f"Hello {current_user.user_id}"}

optional_user

Similar to require_user, except if an access token is missing or invalid, the request is allowed to continue, but the dependency will be None.

from typing import Optional

from fastapi import FastAPI, Depends
from propelauth_fastapi import init_auth, User

app = FastAPI()
auth = init_auth("AUTH_URL", "API_KEY")

@app.get("/api/whoami_optional")
async def whoami_optional(current_user: Optional[User] = Depends(auth.optional_user)):
    if current_user:
        return {"user_id": current_user.user_id}
    return {}

require_org_member

A function that will verify that a user belongs to a specific organization.

from fastapi import FastAPI, Depends
from propelauth_fastapi import init_auth, User

app = FastAPI()
auth = init_auth("AUTH_URL", "API_KEY")

@app.get("/api/org/{org_id}/check")
async def admin_only(org_id: str, current_user: User = Depends(auth.require_user)):
    org = auth.require_org_member(current_user, org_id)
    return {"message": f"You are in {org.org_name}"}
ArgumentDescription
current_userThe result of require_user
required_org_idThe id of an organization. This function will check that the current user is a member of this org. Typically, this is passed in from the frontend as a query or path parameter.

Specifically, it will:

  1. Check that a valid access token was provided. If not, the request is rejected with a 403 status code.
  2. Return the organization’s information for this user.

The returned organization is an OrgMemberInfo

User

A user returned by require_user or optional_user.

PropertyDescription
user_idThe id of the user
org_id_to_org_member_infoA dictionary of org ids to metadata about the org. Includes all orgs that the user is in
legacy_user_idThe original ID of the user, if the user was migrated from an external source

The values of org_id_to_org_member_info are OrgMemberInfo‘s.

OrgMemberInfo

PropertyDescription
org_idThe id of the org
org_nameThe name of the org
user_assigned_roleThe user’s role within the organization. See Roles and Permissions for more details.
user_is_role(role: str): boolReturns True if the user’s role within the organization matches the role passed in
user_is_at_least_role(role: str): boolReturns True if the user’s role within the organization is at least the role passed in. If the hierarchy of roles is Owner => Admin => Member, specifying “Admin” will return True for Admins and Owners, but False for Members.
user_has_permission(permission: str): boolReturns True if the user has a specific permission. The users’ permissions are derived from their role within this organization.
user_has_all_permissions(permissions: List[str]): boolReturns True if the user has all the specified permissions. The users’ permissions are derived from their role within this organization.

Roles and Permissions

A user has a Role within an organization. By default, the available roles are Owner, Admin, or Member, but these can be configured. These roles are also hierarchical, so Owner > Admin > Member.

Roles allow you to control what different users can do within your product. If you want to check a user’s role, you can use require_org_member_with_minimum_role or require_org_member_with_exact_role.

## Assuming a Role structure of Owner => Admin => Member

@app.get("/api/org/{org_id}/admin_only")
async def admin_only(org_id: str, current_user: User = Depends(auth.require_user)):
    org = auth.require_org_member_with_exact_role(current_user, org_id, "Admin")
    return {"message": f"You are an Admin of {org.org_name}"}

@app.get("/api/org/{org_id}/admin_or_owner")
async def admin_or_owner(org_id: str, current_user: User = Depends(auth.require_user)):
    org = auth.require_org_member_with_minimum_role(current_user, org_id, "Admin")
    return {"message": f"You are an Admin or Owner of {org.org_name}"}

Permissions are arbitrary strings associated with a role. For example, can_view_billing, ProductA::CanCreate, and ReadOnly are all valid permissions. The PropelAuth dashboard allows you to set up these permissions.

You can use require_org_member_with_permission or require_org_member_with_all_permissions to check for a given permission.

@app.get("/api/org/{org_id}/billing")
async def billing(org_id: str, current_user: User = Depends(auth.require_user)):
    org = auth.require_org_member_with_permission(current_user, org_id, "can_view_billing")
    pass

Usage with API docs

FastAPIs built in documentation will automatically add this button when you are using either require_user or optional_user.

API docs authorize button

You can obtain an access token either from the frontend or by navigating to ${YOUR_AUTH_URL}/api/v1/refresh_token.

API calls

In addition to protecting API routes, you can make requests to PropelAuth to fetch more information about your users or organizations. You can also create new users, update user metadata, and more.

See FastAPI Library Reference for more information on available functionality.

Next Steps

Done with your backend? Next you can deploy to production.