SDKS
Python SDK
The WorkOS Python SDK provides your Python applications convenient access to the WorkOS Audit Trail and SSO APIs.
Installation
To get started, you can install the WorkOS package via PyPi with:
Terminal
pip install workosAlternatively, you can also install from source:
Terminal
git clone [email protected]:workos-inc/workos-python.git && cd workos-python && python setup.py installView the source on GitHub.
Configuration
To use the SDK you must first provide your API key and Project ID from the Developer Dashboard.
You can set the API key and Project ID after importing the module, before your application starts:
Python
import workos
workos.api_key = "{secretKey}"
workos.project_id = "{projectId}"The audit_trail Module
The audit_trail module provides convenience methods for publishing application events to WorkOS.
workos.audit_trail.create_event()
workos.audit_trail.create_event accepts the follow args:
event (dictionary)— an event object containing descriptive attributes that detail your application's event.
workos.audit_trail.create_event accepts the follow kwargs:
idempotency_key (string, defaults to None)— a unique value which the server uses to recognize successive retries of the same request and safely retry requests without creating the same event more than once.
For example, publishing a non-idempotent event:
Python
event = {
"group": "example.com",
"location": "65.215.8.114",
"action": "user.login_succeeded",
"action_type": "R",
"actor_name": "[email protected]{foo-corp.com}",
"actor_id": "user_01DEQWZNQT8Y47HDPSJKQS1J3F",
"target_name": "[email protected]{foo-corp.com}",
"target_id": "user_01DEQWZNQT8Y47HDPSJKQS1J3F",
"occurred_at": "2020-08-14T03:49:22.428Z",
"metadata": {
"source": "Email",
}
}
workos.audit_trail.create_event(event)Results in WorkOS logging the following event:
JSON
{
"id": "evt_04DKH0F9DXZJ312A8G0CKRJ648Y",
"group": "example.com",
"location": "65.215.8.114",
"action": "user.login_succeeded",
"action_type": "R",
"actor_name": "[email protected]{foo-corp.com}",
"actor_id": "user_01DEQWZNQT8Y47HDPSJKQS1J3F",
"target_name": "[email protected]{foo-corp.com}",
"target_id": "user_01DEQWZNQT8Y47HDPSJKQS1J3F",
"occurred_at": "2020-08-14T03:49:22.428Z",
"metadata": {
"source": "Email",
}
}For details about the specific use of each event attribute, as well as more information about using idempotency keys and metadata, refer to the API Reference.
workos.audit_trail.get_events()
workos.audit_trail.get_events accepts the following kwargs:
before (string, defaults to None)- Event ID to look beforeafter (string, defaults to None)- Event ID to look afterlimit (int, defaults to 10)- Number of Events to returngroup (string|list, defaults to None)- Group or groups to filter foraction (string|list, defaults to None)- Action or actions to filter foraction_type (string|list, defaults to None)- Action type or types to filter foractor_name (string|list, defaults to None)- Actor name or name to filter foractor_id (string|list, defaults to None)- Actor ID or IDs to filter fortarget_name (string|list, defaults to None)- Target name or names to filter fortarget_id (string|list, defaults to None)- Target ID or IDs to filter foroccurred_at (string, defaults to None)- ISO-8601 datetime of when an event occurredoccurred_at_gt (string, defaults to None)- ISO-8601 datetime of when an event occurred afteroccurred_at_gte (string, defaults to None)- ISO-8601 datetime of when an event occurred at or afteroccurred_at_lt (string, defaults to None)- ISO-8601 datetime of when an event occurred beforeoccurred_at_lte (string, defaults to None)- ISO-8601 datetime of when an event occured at or beforesearch (string, defaults to None)- Keyword search
Returns:
tuplelist- List of WorkOSEvent objectsstring- Before cursorstring- After cursor
Example:
Python
events, before, after = workos.audit_trail.get_events()The sso Module
The sso Module provides convenience methods for authenticating a Single Sign-on user via WorkOS. WorkOS SSO follows the OAuth 2.0 specification.
First, you'll direct your users to an authorization_url. They will sign in to their account with their Identity Provider, and be redirected to a callback URL that you set in your WorkOS Dashboard. The user will be redirected with a code URL parameter, which you can then exchange for a WorkOSProfile using the workos.sso.get_profile method.
See our Python SSO example app for a complete example.
workos.sso.get_authorization_url()
Generate an authorization URL to intitiate the WorkOS OAuth2 workflow.
workos.sso.get_authorization_url accepts the following args:
domain (string)— the authenticating user's company domain, without protocol (ex.example.com)redirectURI (string)— a callback URL where your application redirects the user-agent after an authorization code is granted (ex.workos.dev/callback)provider (ConnectionType)— optional parameter that specifies the type of Connection to authenticate with. If used, a user of any domain can be authenticated. OnlyGoogleOAuthis currently supported. Most commonly used for "Signup with Google" buttons.
workos.sso.get_authorization_url accepts the following kwargs:
state (string, defaults to None)— an optional encoded string used to manage state across authorization transactions (ex.{ next_page: '/docs'})
This method will return an OAuth2 query string of the form:
https://api.workos.com/sso/authorize?response_type=code&domain=${domain}&client_id=${projectID}&redirect_uri=${redirectURI}&state=${state}
For example, when used in a Flask app:
app.py
DOMAIN = '{foo-corp.com}'
REDIRECT_URI = '{redirectURI}'
@app.route('/auth')
def auth():
authorization_url = client.sso.get_authorization_url(
DOMAIN,
REDIRECT_URI,
state=''
)
return redirect(authorization_url)The user would be redirected to:
https://api.workos.com/sso/authorize?response_type=code&domain=foo-corp.com&client_id={projectID}&redirect_uri=http://localhost:4567/callback
WorkOS takes over from here, sending the user to authenticate with their IDP, and on successful login, returns the user
to your callback URL with a code parameter. You'll use workos.sso.get_profile to exchange the code for a WorkOSProfile.
workos.sso.get_profile()
Fetch a
WorkOSProfilefor an authorized user.
workos.sso.get_profile accepts the following args:
code (string)— an opaque string provided by the authorization server; will be exchanged for an Access Token when the user's profile is sent
This method will return an instance of a WorkOSProfile object with the following attributes:
Python
{
"id": "prof_01DRA1XNSJDZ19A31F183ECQW5",
"email": "[email protected]{foo-corp.com}",
"first_name": "WorkOS",
"last_name": "Demo",
"connection_type": "OktaSAML",
"idp_id": "00u1klkowm8EGah2H357",
}The Flask app can be extended to use this method:
app.py
DOMAIN = '{foo-corp.com}'
REDIRECT_URI = '{redirectURI}'
@app.route('/auth')
def auth():
authorization_url = client.sso.get_authorization_url(
DOMAIN,
REDIRECT_URI,
state=''
)
return redirect(authorization_url)
@app.route('/auth/callback')
def auth_callback():
code = request.args.get('code')
profile = client.sso.get_profile(code)
return profile.to_dict()Given the WorkOSProfile, you can now sign the user in according to your own authentication setup.