FastAPI Library Reference¶
Installation¶
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)
- 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.
- 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:
- Check that the user is a member of that organization. If not, the request is rejected with a 403 status code.
- (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. - 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. |
Fetch user metadata by id¶
Successful response:
{
"user_id": "e9d3520f-836e-403c-82c2-09843517e1ce",
"email": "user@example.com",
"email_confirmed": true,
"username": "example", // (1)
"first_name": "first", // (2)
"last_name": "last", // (3)
"picture_url": "https://...", // (4)
"locked": false,
"enabled": true,
"mfa_enabled": false,
"created_at": 1645131680,
"last_active_at": 1650654711,
// Only returned if include_orgs = true
"org_id_to_org_info": { // (5)
"2ef0e1fc-234f-4dc0-a50c-35adb1bbb7e4": {
"org_id": "2ef0e1fc-234f-4dc0-a50c-35adb1bbb7e4",
"org_name": "ExampleOrganization",
"user_role": "Owner"
}
}
}
- Optional: Only returned if you have the field enabled as part of your user schema
- Optional: Only returned if you have the field enabled as part of your user schema
- Optional: Only returned if you have the field enabled as part of your user schema
- Optional: Only returned if you have the field enabled as part of your user schema
- True if the user's account is locked for security purposes.
- Includes all organizations that the user is a member of
Fetch user metadata by email¶
Successful response is the same as fetch_user_metadata_by_user_id, expect it takes an email as an argument.
Fetch user metadata by username¶
Successful response is the same as fetch_user_metadata_by_user_id, expect it takes a username as an argument.
Batch fetch users by ids¶
# auth object somes from init_auth
user_id_to_metadata = auth.fetch_batch_user_metadata_by_user_ids([
"1be238f3-5908-4c51-b3bf-e53dd763047e",
"beb00acf-6e48-435d-8388-3758607ec01b",
"941c99e5-3530-4475-bd0f-bbc5d06603c3"
], include_orgs=False)
user_id_to_metadata
looks like
Any IDs that don't have a match are not returned. Duplicate users are only returned once.
{
"1be238f3-5908-4c51-b3bf-e53dd763047e": {
"user_id": "e9d3520f-836e-403c-82c2-09843517e1ce",
"email": "user@example.com",
"email_confirmed": true,
"username": "example", // (1)
"first_name": "first", // (2)
"last_name": "last", // (3)
"picture_url": "https://...", // (4)
"locked": false, // (5)
"enabled": true,
"mfa_enabled": false,
"created_at": 1645131680,
"last_active_at": 1650654711,
// Only returned if include_orgs = true
"org_id_to_org_info": { // (6)
"2ef0e1fc-234f-4dc0-a50c-35adb1bbb7e4": {
"org_id": "2ef0e1fc-234f-4dc0-a50c-35adb1bbb7e4",
"org_name": "ExampleOrganization",
"user_role": UserRole.Owner,
}
}
},
"beb00acf-6e48-435d-8388-3758607ec01b": {
//...
}
}
- Optional: Only returned if you have the field enabled as part of your user schema
- Optional: Only returned if you have the field enabled as part of your user schema
- Optional: Only returned if you have the field enabled as part of your user schema
- Optional: Only returned if you have the field enabled as part of your user schema
- True if the user's account is locked for security purposes.
- Includes all organizations that the user is a member of
Batch fetch users by emails¶
# auth object somes from init_auth
auth.fetch_batch_user_metadata_by_emails(["a@example.com", "b@example.com"], include_orgs=True)
Successful response is the same as Batch fetch users by ids, but the keys are matching email addresses
Batch fetch users by usernames¶
# auth object somes from init_auth
auth.fetch_batch_user_metadata_by_usernames(["usera", "userb", "userc"], include_orgs=True)
Successful response is the same as Batch fetch users by ids, but the keys are matching usernames
Search for users¶
# auth object somes from init_auth
auth.fetch_users_by_query(page_size=10, page_number=0, order_by=UserQueryOrderBy.CREATED_AT_ASC,
email_or_username=None, include_orgs=False):
Argument | Description |
---|---|
page_size | The number of results to return at a time. Must be between 1 and 100, default 10. |
page_number | Used to page over results |
order_by | How to order the results. See UserQueryOrderBy for options |
email_or_username | Searches for partial matches within email addresses or usernames. port would match a user with email address support@propelauth.com. |
include_orgs | Whether or not to include the user's organization information in the response. Default false |
Successful response:
{
"total_users": 103,
"current_page": 0,
"page_size": 10,
"has_more_results": true,
"users": [{
// See (1) for example users
}, {
// There will be 10 users in this response
}]
}
Fetch users in organization¶
# auth object somes from init_auth
auth.fetch_users_in_org(org_id, page_size=10, page_number=0, include_orgs=False)
Argument | Description |
---|---|
org_id | The organization to fetch users for |
page_size | The number of results to return at a time. Must be between 1 and 100, default 10. |
page_number | Used to page over results |
include_orgs | Whether or not to include the user's organization information in the response. Default false |
Successful response:
{
"total_users": 43,
"current_page": 0,
"page_size": 10,
"has_more_results": true,
"users": [{
// See (1) for example users
}, {
// There will be 10 users in this response, all in the specified organization
}]
}
Create User¶
# auth object somes from init_auth
auth.create_user(email, email_confirmed=False, send_email_to_confirm_email_address=True,
password=None, username=None, first_name=None, last_name=None)
Argument | Description |
---|---|
The user's email address | |
email_confirmed | Whether the email address should start off as already confirmed. If false, the user is required to confirm the email address before they sign in. |
send_email_to_confirm_email_address | Whether we should send an email immediately to confirm the user's email address. If false, the user will get a confirmation email when they first sign in. |
password | Optional password. If unset, the user can set it themselves via their account page |
username | Optional username. Can only be used if username is enabled in your user schema |
first_name | Optional first name. Can only be used if name is enabled in your user schema |
last_name | Optional last name. Can only be used if name is enabled in your user schema |
Successful response:
Update User Email¶
# auth object somes from init_auth
# Returns true if it was successful, false if the user was not found
auth.update_user_email(user_id, new_email, require_email_confirmation):
Argument | Description |
---|---|
new_email | New email address for this user |
require_email_confirmation | Whether the new email address requires confirmation. If true, an email will be sent to the new email address to confirm. If false, the users email address will be updated and confirmed immediately. |
Update User Metadata¶
# auth object somes from init_auth
# Returns true if it was successful, false if the user was not found
auth.update_user_metadata(user_id, username=None, first_name=None, last_name=None):
Argument | Description |
---|---|
username | Optional username. Can only be used if username is enabled in your user schema |
first_name | Optional first name. Can only be used if name is enabled in your user schema |
last_name | Optional last name. Can only be used if name is enabled in your user schema |
Fetch an organization¶
Successful response:
Fetch all organizations¶
# auth object somes from init_auth
auth.fetch_org_by_query(page_size=10, page_number=0, order_by=OrgQueryOrderBy.CREATED_AT_ASC):
Argument | Description |
---|---|
page_size | The number of results to return at a time. Must be between 1 and 100, default 10. |
page_number | Used to page over results |
order_by | How to order the results. See OrgQueryOrderBy for options |
Successful response:
{
"total_orgs": 21,
"current_page": 0,
"page_size": 10,
"has_more_results": true,
"orgs": [{
"org_id": "d488996d-8ccc-4101-b5f2-131f5f09ddb6",
"name": "OneOfYourCustomers"
}, {
// There will be 10 orgs in this response
}]
}
UserRole¶
An enum of roles within an organization. Values, in order of highest to lowest, include
If you use the decorator require_org_member(minimum_required_role=UserRole.Admin)
,
then users with roles Owner
and Admin
are allowed, but Member
is rejected.