Skip to content

FastAPI - Integrate your backend

Minimal 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", #(1)
                 "YOUR_API_KEY") #(2)

@app.get("/")
async def root(current_user: User = Depends(auth.require_user)):
    return {"message": f"Hello {current_user.user_id}"}
  1. The base URL where your authentication pages are hosted. You can find this under the Backend Integration section for your project at https://app.propelauth.com.
  2. You can manage your api keys under the Backend Integration section for your project.

How it works

You've seen that the frontend gets an access token. When it makes an HTTP request, it provides this access token in an Authorization header.

PropelAuth provides you with metadata that you use to validate the access token and figure out who it belongs to. The complexity of fetching the metadata and validating the tokens is hidden in the FastAPI library.

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", # (1)
                 "YOUR_API_KEY") # (2)
  1. The base URL where your authentication pages are hosted. You can find this under the Backend Integration section for your project at https://app.propelauth.com.
  2. You can manage your api keys under the Backend Integration section for your project.

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}"}

User

A user returned by require_user or optional_user.

Property Description
user_id The id of the user
org_id_to_org_member_info A dictionary of org ids to metadata about the org. Includes all orgs that the user is in

The values of org_id_to_org_member_info have these properties:

org_id_to_org_member_info properties Description
org_id The id of the org
org_name The name of the org
user_role The user's role within the org. See UserRole for more details.

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, UserRole

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

@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(current_user, org_id, UserRole.Admin)
    return {"message": f"You are at least an admin of {org.org_name}"}
Argument Description
current_user The result of require_user
required_org_id The 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.
minimum_required_role If specified, require_org_member will check both that the user is a member of the organization, and that their role is >= minimum_required_role. If not, the request is rejected with a 403 Forbidden error.

Specifically, it will:

  1. Check that the user is a member of that organization. If not, the request is rejected with a 403 status code.
  2. (Optionally) Check that the user's role in that organization is >= minimum_required_role. If not, the request is rejected with a 403 status code.
  3. Return the organization's information for this user.

The returned organization has the following properties:

Property Description
org_id The id of the org
org_name The name of the org
user_role The user's role within the org. See UserRole for more details.

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 authorze 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, etc.

See the reference for everything you can do.

Next Steps

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