servicepytan package

Submodules

servicepytan.auth module

Authenticating with ServiceTitan API

class servicepytan.auth.ApiEnvironment(value)[source]

Bases: StrEnum

Enumeration for ServiceTitan API environments.

This enum defines the available API environments for ServiceTitan, allowing users to switch between production and integration environments.

PRODUCTION

Production environment for live data

INTEGRATION

Integration environment for testing

PRODUCTION = 'production'
INTEGRATION = 'integration'
servicepytan.auth.get_auth_root_url(env='production')[source]

Get the authentication root URL for the specified environment.

Parameters:

env (str) – The API environment (production or integration)

Returns:

The authentication root URL for the specified environment

Return type:

str

Raises:

ValueError – If the environment is not recognized

Examples

>>> get_auth_root_url(ApiEnvironment.PRODUCTION)
'https://auth.servicetitan.io'
>>> get_auth_root_url(ApiEnvironment.INTEGRATION)
'https://auth-integration.servicetitan.io'
servicepytan.auth.get_api_root_url(env='production')[source]

Get the API root URL for the specified environment.

Parameters:

env (str) – The API environment (production or integration)

Returns:

The API root URL for the specified environment

Return type:

str

Raises:

ValueError – If the environment is not recognized

Examples

>>> get_api_root_url(ApiEnvironment.PRODUCTION)
'https://api.servicetitan.io'
>>> get_api_root_url(ApiEnvironment.INTEGRATION)
'https://api-integration.servicetitan.io'
servicepytan.auth.servicepytan_connect(api_environment=ApiEnvironment.PRODUCTION, app_key=None, tenant_id=None, client_id=None, client_secret=None, app_id=None, timezone='UTC', config_file=None)[source]

Establish connection configuration for ServiceTitan API.

This function creates a configuration object with all necessary credentials and settings for connecting to the ServiceTitan API. It can source credentials from function parameters, a config file, or environment variables.

Parameters:
  • api_environment (str) – The API environment to use (production or integration)

  • app_key (str) – ServiceTitan application key

  • tenant_id (str) – ServiceTitan tenant identifier

  • client_id (str) – OAuth client ID for authentication

  • client_secret (str) – OAuth client secret for authentication

  • app_id (str) – ServiceTitan application ID (optional)

  • timezone (str) – Timezone for date operations (defaults to “UTC”)

  • config_file (str) – Path to JSON configuration file containing credentials

Returns:

Configuration object containing all necessary authentication settings

Return type:

dict

Examples

>>> # Using parameters
>>> conn = servicepytan_connect(
...     api_environment="production",
...     app_key="your_app_key",
...     tenant_id="your_tenant_id",
...     client_id="your_client_id",
...     client_secret="your_client_secret"
... )
>>> # Using config file
>>> conn = servicepytan_connect(config_file="credentials.json")
>>> # Using environment variables (will auto-load from .env)
>>> conn = servicepytan_connect()
servicepytan.auth.request_auth_token(auth_root_url, client_id, client_secret)[source]

Fetches Auth Token.

Retrieves authentication token for completing a request against the API

Parameters:
  • client_id – String, provided from the integration settings

  • client_secret – String, provided from the integration settings

Returns:

Authentication token

Raises:

TBD

servicepytan.auth.get_auth_token(conn)[source]

Fetches Auth Token using the connection configuration.

Retrieves the CLIENT_ID and CLIENT_SECRET entries from the connection object and requests an authentication token from the ServiceTitan API.

Parameters:

conn – Dictionary containing the credential configuration

Returns:

Authentication token

Return type:

str

Raises:

requests.HTTPError – If the authentication request fails

servicepytan.auth.get_app_key(conn)[source]

Fetches App Key from the connection configuration.

Retrieves the APP_KEY entry from the connection object.

Parameters:

conn – Dictionary containing the credential configuration

Returns:

ServiceTitan App Key

Return type:

str

Raises:

KeyError – If the APP_KEY is not found in the connection configuration

servicepytan.auth.get_tenant_id(conn)[source]

Fetches Tenant ID from the connection configuration.

Retrieves the TENANT_ID entry from the connection object.

Parameters:

conn – Dictionary containing the credential configuration

Returns:

ServiceTitan Tenant ID

Return type:

str

Raises:

KeyError – If the TENANT_ID is not found in the connection configuration

servicepytan.auth.get_auth_headers(conn)[source]

Generates the Authentication Headers for each API request.

Creates a dictionary that includes the auth token and app key formatted to create the authentication headers required by the ServiceTitan API.

Parameters:

conn – Dictionary containing the credential configuration

Returns:

Dictionary containing Authorization and ST-App-Key headers

Return type:

dict

Raises:

Examples

>>> headers = get_auth_headers(conn)
>>> # headers = {
>>> #     "Authorization": "Bearer your_token_here",
>>> #     "ST-App-Key": "your_app_key_here"
>>> # }

servicepytan.data module

Provides methods for simplified and opininated ways of retrieving data from the ServiceTitan API

class servicepytan.data.DataService(conn=None)[source]

Bases: object

Primary class for executing data methods.

The DataService class retrieves the configuration file and authentication settings. The methods included are a selection of common data pulls with a simplified API generally based on retrieving data between a date range.

conn

a dictionary containing the credential config.

__init__(conn=None)[source]

Inits DataService with configuration file and authentication settings.

get_jobs_completed_between(start_date, end_date, job_status=['Completed', 'Scheduled', 'InProgress', 'Dispatched'])[source]

Retrieve all jobs completed between the start and end date.

Fetches jobs that were completed within the specified date range. Can filter by multiple job statuses simultaneously.

Parameters:
  • start_date – Start date for the query (string or datetime object)

  • end_date – End date for the query (string or datetime object)

  • job_status – List of job statuses to include (default includes most common statuses)

Returns:

Combined list of all jobs matching the criteria

Return type:

list

Examples

>>> data_service = DataService(conn)
>>> jobs = data_service.get_jobs_completed_between("2024-01-01", "2024-01-31")
>>> completed_only = data_service.get_jobs_completed_between(
...     "2024-01-01", "2024-01-31", job_status=["Completed"]
... )
get_jobs_created_between(start_date, end_date)[source]

Retrieve all jobs created between the start and end date.

Fetches jobs that were originally created within the specified date range, regardless of their current status or completion date.

Parameters:
  • start_date – Start date for the query (string or datetime object)

  • end_date – End date for the query (string or datetime object)

Returns:

List of all jobs created in the date range

Return type:

list

Examples

>>> data_service = DataService(conn)
>>> new_jobs = data_service.get_jobs_created_between("2024-01-01", "2024-01-31")
get_appointments_between(start_date, end_date, appointment_status=['Scheduled', 'Dispatched', 'Working', 'Done'])[source]

Retrieve all appointments that start between the start and end date.

Fetches appointments scheduled to start within the specified date range. Can filter by multiple appointment statuses simultaneously.

Parameters:
  • start_date – Start date for the query (string or datetime object)

  • end_date – End date for the query (string or datetime object)

  • appointment_status – List of appointment statuses to include

Returns:

Combined list of all appointments matching the criteria

Return type:

list

Examples

>>> data_service = DataService(conn)
>>> appointments = data_service.get_appointments_between("2024-01-01", "2024-01-31")
>>> scheduled_only = data_service.get_appointments_between(
...     "2024-01-01", "2024-01-31", appointment_status=["Scheduled"]
... )
get_sold_estimates_between(start_date, end_date)[source]

Retrieve all sold estimates that were sold between the start and end date.

Fetches estimates that were marked as sold within the specified date range. Only includes active (not cancelled) estimates.

Parameters:
  • start_date – Start date for the query (string or datetime object)

  • end_date – End date for the query (string or datetime object)

Returns:

List of all sold estimates in the date range

Return type:

list

Examples

>>> data_service = DataService(conn)
>>> sold_estimates = data_service.get_sold_estimates_between("2024-01-01", "2024-01-31")
get_total_sales_between(start_date, end_date)[source]

Retrieves total sales dollar amount between start and end date.

Calculates the total sales amount by summing all sold estimate items within the specified date range. This provides a quick way to get revenue totals for reporting.

Parameters:
  • start_date – Start date for the query (string or datetime object)

  • end_date – End date for the query (string or datetime object)

Returns:

Total sales amount for the period

Return type:

float

Examples

>>> data_service = DataService(conn)
>>> total_sales = data_service.get_total_sales_between("2024-01-01", "2024-01-31")
>>> print(f"Total sales: ${total_sales:,.2f}")
get_purchase_orders_created_between(start_date, end_date)[source]

Retrieve all purchase orders created between the start and end date.

Fetches purchase orders that were created within the specified date range, useful for tracking procurement activity and spend.

Parameters:
  • start_date – Start date for the query (string or datetime object)

  • end_date – End date for the query (string or datetime object)

Returns:

List of all purchase orders created in the date range

Return type:

list

Examples

>>> data_service = DataService(conn)
>>> pos = data_service.get_purchase_orders_created_between("2024-01-01", "2024-01-31")
get_jobs_modified_between(start_date, end_date)[source]

Retrieve all jobs modified between the start and end date.

Fetches jobs that were updated or modified within the specified date range, useful for tracking changes and updates to existing jobs.

Parameters:
  • start_date – Start date for the query (string or datetime object)

  • end_date – End date for the query (string or datetime object)

Returns:

List of all jobs modified in the date range

Return type:

list

Examples

>>> data_service = DataService(conn)
>>> modified_jobs = data_service.get_jobs_modified_between("2024-01-01", "2024-01-31")
get_employees(active='True')[source]

Retrieve employee list.

Fetches the list of employees from ServiceTitan. Can filter to show only active employees or include inactive ones as well.

Parameters:

active – String indicating whether to show only active employees (“True” or “False”)

Returns:

List of employee records

Return type:

list

Examples

>>> data_service = DataService(conn)
>>> active_employees = data_service.get_employees()
>>> all_employees = data_service.get_employees(active="False")
get_technicians(active='True')[source]

Retrieve technician list.

Fetches the list of technicians from ServiceTitan. Technicians are a subset of employees who perform field work.

Parameters:

active – String indicating whether to show only active technicians (“True” or “False”)

Returns:

List of technician records

Return type:

list

Examples

>>> data_service = DataService(conn)
>>> active_techs = data_service.get_technicians()
>>> all_techs = data_service.get_technicians(active="False")
get_tag_types(active='True')[source]

Retrieve tag types list.

Fetches the list of tag types configured in ServiceTitan. Tag types are used to categorize and organize jobs, customers, and other entities.

Parameters:

active – String indicating whether to show only active tag types (“True” or “False”)

Returns:

List of tag type records

Return type:

list

Examples

>>> data_service = DataService(conn)
>>> tag_types = data_service.get_tag_types()
get_business_units(active='True')[source]

Retrieve business units list.

Fetches the list of business units configured in ServiceTitan. Business units are used to organize operations by service type, location, or other criteria.

Parameters:

active – String indicating whether to show only active business units (“True” or “False”)

Returns:

List of business unit records

Return type:

list

Examples

>>> data_service = DataService(conn)
>>> business_units = data_service.get_business_units()

servicepytan.reports module

servicepytan.reports.get_report_categories(conn=None)[source]

Get a list of report categories from ServiceTitan.

Retrieves all available report categories from the ServiceTitan reporting API. These categories are used to organize reports and are required for accessing specific reports.

Parameters:

conn – Dictionary containing the credential configuration

Returns:

JSON response containing list of report categories

Return type:

dict

Raises:

requests.HTTPError – If the API request fails

Examples

>>> categories = get_report_categories(conn)
>>> for category in categories['data']:
...     print(category['name'])
servicepytan.reports.get_report_list(report_category, conn=None)[source]

Get a list of reports for a given report category.

Retrieves all available reports within a specific category from the ServiceTitan reporting API.

Parameters:
  • report_category – The category ID or name to retrieve reports for

  • conn – Dictionary containing the credential configuration

Returns:

JSON response containing list of reports in the category

Return type:

dict

Raises:

requests.HTTPError – If the API request fails

Examples

>>> reports = get_report_list("jobs", conn)
>>> for report in reports['data']:
...     print(f"{report['id']}: {report['name']}")
servicepytan.reports.get_dynamic_set_list(dynamic_set_id, conn=None)[source]

Get a list of dynamic value sets for report parameters.

Retrieves the available values for dynamic parameters in ServiceTitan reports. Dynamic sets contain the possible values that can be selected for certain report parameters.

Parameters:
  • dynamic_set_id – The ID of the dynamic value set to retrieve

  • conn – Dictionary containing the credential configuration

Returns:

JSON response containing the dynamic value set data

Return type:

dict

Raises:

requests.HTTPError – If the API request fails

Examples

>>> dynamic_values = get_dynamic_set_list("employees", conn)
>>> for value in dynamic_values['data']:
...     print(f"{value['id']}: {value['name']}")
class servicepytan.reports.Report(category, report_id, conn=None)[source]

Bases: object

Primary class for retrieving Reporting Endpoint Data.

Provides a comprehensive interface for working with ServiceTitan reports, including parameter management, metadata retrieval, and data extraction.

category

A string representing the report category. Find list of categories with get_report_categories().

report_id

A string representing the report id. Find list of report_id using get_report_list().

conn

a dictionary containing the credential config.

__init__(category, report_id, conn=None)[source]

Initialize Report with category, report ID, and connection configuration.

Parameters:
  • category – The report category (e.g., “jobs”, “customers”)

  • report_id – The specific report ID within the category

  • conn – Dictionary containing the credential configuration

add_params(name, value)[source]

Add or update a parameter for the report.

Adds a new parameter to the report’s parameter list. If the parameter already exists, it updates the existing value.

Parameters:
  • name – The parameter name as defined in the report metadata

  • value – The value to set for the parameter

Examples

>>> report = Report("jobs", "job-summary", conn)
>>> report.add_params("StartDate", "2024-01-01")
>>> report.add_params("BusinessUnit", "12345")
update_params(name, value)[source]

Update an existing parameter in the report.

Updates the value of an existing parameter. If the parameter doesn’t exist, it will be added to the parameter list.

Parameters:
  • name – The parameter name to update

  • value – The new value for the parameter

Examples

>>> report.update_params("StartDate", "2024-02-01")
get_params()[source]

Get the current report parameters.

Returns the current parameter configuration for the report.

Returns:

Dictionary containing the report parameters

Return type:

dict

Examples

>>> current_params = report.get_params()
>>> print(current_params)
get_metadata()[source]

Get report metadata including available parameters and their types.

Retrieves comprehensive metadata about the report, including parameter definitions, data types, required fields, and available values.

Returns:

JSON response containing report metadata

Return type:

dict

Raises:

requests.HTTPError – If the API request fails

Examples

>>> metadata = report.get_metadata()
>>> for param in metadata['parameters']:
...     print(f"{param['name']}: {param['dataType']}")
show_param_types()[source]

Display parameter types and requirements in a formatted way.

Prints a formatted list of all report parameters showing their names, data types, whether they’re required, and any available values.

Examples

>>> report.show_param_types()
>>> # Output:
>>> # [*] - StartDate: DateTime
>>> # [ ] - BusinessUnit: Long (dynamicSetId: 123)
>>> #   - Business Unit 1
>>> #   - Business Unit 2
get_data(params='', page=1, page_size=5000)[source]

Get report data for a specific page.

Retrieves report data from ServiceTitan for a single page. Used internally by get_all_data() for pagination, but can be used directly for custom pagination handling.

Parameters:
  • params – Parameter configuration (uses instance params if empty)

  • page – Page number to retrieve (1-based)

  • page_size – Number of records per page (max 5000)

Returns:

JSON response containing report data and pagination info

Return type:

dict

Raises:

requests.HTTPError – If the API request fails

Examples

>>> report.add_params("StartDate", "2024-01-01")
>>> page_data = report.get_data(page=1, page_size=1000)
>>> print(f"Retrieved {len(page_data['data'])} records")
get_all_data(params='', page_size=5000, timeout_min=60)[source]

Get all report data with automatic pagination.

Retrieves all available data from the report by automatically handling pagination. Includes intelligent page size optimization and timeout protection to prevent excessively long-running requests.

Parameters:
  • params – Parameter configuration (uses instance params if empty)

  • page_size – Number of records per page (max 5000)

  • timeout_min – Maximum time in minutes before aborting the request

Returns:

Dictionary containing ‘data’ (list of records) and ‘fields’ (metadata)

Return type:

dict

Raises:

requests.HTTPError – If any API request fails

Examples

>>> report = Report("jobs", "job-summary", conn)
>>> report.add_params("StartDate", "2024-01-01")
>>> report.add_params("EndDate", "2024-01-31")
>>> all_data = report.get_all_data()
>>> print(f"Retrieved {len(all_data['data'])} total records")
>>> # For large datasets, use smaller timeout
>>> large_report_data = report.get_all_data(timeout_min=30)

servicepytan.requests module

class servicepytan.requests.Endpoint(folder, endpoint, conn=None)[source]

Bases: object

Primary class for interacting with the API by establishing an endpoint object.

The core way of getting and changing data in ServiceTitan using the library is to create an endpoint object. Each method pulls the data in a different way and may or may not apply to a certain endpoint. You will need to consult the developer docs to identify the exact parameters needed for a given endpoint and which methods will apply.

folder

A string indicating the group of endpoints you want to address.

endpoint

A string indicating the endpoint you want to address.

conn

a dictionary containing the credential config.

__init__(folder, endpoint, conn=None)[source]

Inits Endpoint with folder, endpoint and allows for getting necessary credentials from the config file.

get_one(id, modifier='', query={})[source]

Retrieve one record using the record id.

Fetches a single record from the API endpoint using its unique identifier. Optionally supports modifiers to access sub-resources and query parameters for additional filtering.

Parameters:
  • id – The unique identifier of the record to retrieve

  • modifier – Optional sub-resource path (e.g., “notes” to get job notes)

  • query – Optional dictionary of query parameters for filtering

Returns:

JSON response containing the requested record data

Return type:

dict

Raises:

requests.HTTPError – If the API request fails

Examples

>>> endpoint = Endpoint("jpm", "jobs", conn)
>>> job = endpoint.get_one(id="12345678")
>>> job_notes = endpoint.get_one(id="12345678", modifier="notes")
get_many(query={}, id='', modifier='')[source]

Retrieve one page of results with query options to customize.

Fetches a single page of results from the API endpoint. Even though this is a “get_many” request, it can still use an id and modifier for accessing sub-resources (e.g., getting Notes for a specific Job).

Parameters:
  • query – Dictionary of query parameters for filtering and pagination

  • id – Optional record ID for accessing sub-resources

  • modifier – Optional sub-resource path

Returns:

JSON response containing paginated results with ‘data’ and ‘hasMore’ fields

Return type:

dict

Raises:

requests.HTTPError – If the API request fails

Examples

>>> endpoint = Endpoint("jpm", "jobs", conn)
>>> page_data = endpoint.get_many(query={"pageSize": 50, "page": 1})
>>> job_notes = endpoint.get_many(id="12345678", modifier="notes")
get_all(query={}, id='', modifier='')[source]

Retrieve all pages of results for your query.

Automatically handles pagination by making multiple API calls to fetch all available records that match the query criteria. This method continues fetching pages until no more data is available.

Parameters:
  • query – Dictionary of query parameters for filtering (page parameter will be managed automatically)

  • id – Optional record ID for accessing sub-resources

  • modifier – Optional sub-resource path

Returns:

Combined list of all records from all pages

Return type:

list

Raises:

requests.HTTPError – If any API request fails

Examples

>>> endpoint = Endpoint("jpm", "jobs", conn)
>>> all_jobs = endpoint.get_all(query={"jobStatus": "Completed"})
>>> all_job_notes = endpoint.get_all(id="12345678", modifier="notes")
create(payload)[source]

Create a new record via POST request.

Sends a POST request to create a new resource in the API endpoint. The payload should contain all required fields for the resource type.

Parameters:

payload – Dictionary containing the data for the new record

Returns:

JSON response from the API, typically containing the created record

Return type:

dict

Raises:

requests.HTTPError – If the API request fails

Examples

>>> endpoint = Endpoint("jpm", "jobs", conn)
>>> new_job = {
...     "summary": "New Job",
...     "customerId": 12345,
...     "businessUnitId": 67890
... }
>>> created_job = endpoint.create(new_job)
update(id, payload, modifier='', request_type='PUT')[source]

Update an existing record via PUT or PATCH request.

Sends a PUT or PATCH request to update an existing resource. PUT is used for complete updates while PATCH can be used for partial updates.

Parameters:
  • id – The unique identifier of the record to update

  • payload – Dictionary containing the updated data

  • modifier – Optional sub-resource path for updating specific parts

  • request_type – HTTP method type (“PUT” or “PATCH”), defaults to “PUT”

Returns:

JSON response from the API

Return type:

dict

Raises:

requests.HTTPError – If the API request fails

Examples

>>> endpoint = Endpoint("jpm", "jobs", conn)
>>> updates = {"summary": "Updated Job Summary"}
>>> updated_job = endpoint.update("12345678", updates)
>>> updated_job = endpoint.update("12345678", updates, request_type="PATCH")
delete(id, modifier='')[source]

Delete a record via DELETE request.

Sends a DELETE request to remove a resource from the API endpoint.

Parameters:
  • id – The unique identifier of the record to delete

  • modifier – Optional sub-resource path for deleting specific parts

Returns:

JSON response from the API

Return type:

dict

Raises:

requests.HTTPError – If the API request fails

Examples

>>> endpoint = Endpoint("jpm", "jobs", conn)
>>> result = endpoint.delete("12345678")
delete_subitem(id, modifier_id, modifier)[source]

Delete a sub-item of a record via DELETE request.

Sends a DELETE request to remove a specific sub-resource that belongs to a parent resource. This is useful for deleting nested items like notes, attachments, or other related records.

Parameters:
  • id – The unique identifier of the parent record

  • modifier_id – The unique identifier of the sub-item to delete

  • modifier – The sub-resource type (e.g., “notes”, “attachments”)

Returns:

JSON response from the API

Return type:

dict

Raises:

requests.HTTPError – If the API request fails

Examples

>>> endpoint = Endpoint("jpm", "jobs", conn)
>>> result = endpoint.delete_subitem("12345678", "note_id", "notes")
export_one(export_endpoint, export_from='', include_recent_changes=False)[source]

Export one page of data from an export endpoint.

Retrieves one page of export data from ServiceTitan’s export endpoints, which are optimized for bulk data extraction and typically return larger datasets than regular API endpoints.

Parameters:
  • export_endpoint – The specific export endpoint to call

  • export_from – Continuation token from previous export call for pagination

  • include_recent_changes – Whether to include recent changes in the export

Returns:

JSON response containing export data and pagination information

Return type:

dict

Raises:

requests.HTTPError – If the API request fails

Examples

>>> endpoint = Endpoint("jpm", "export", conn)
>>> export_data = endpoint.export_one("jobs")
>>> next_page = endpoint.export_one("jobs", export_from=export_data["continueFrom"])
export_all(export_endpoint, export_from='', include_recent_changes=False)[source]

Export all data from an export endpoint.

Retrieves all available data from ServiceTitan’s export endpoints by automatically handling pagination. This method continues making requests until all data has been retrieved.

Parameters:
  • export_endpoint – The specific export endpoint to call

  • export_from – Starting continuation token (empty string to start from beginning)

  • include_recent_changes – Whether to include recent changes in the export

Returns:

Combined list of all exported records

Return type:

list

Raises:

requests.HTTPError – If any API request fails

Examples

>>> endpoint = Endpoint("jpm", "export", conn)
>>> all_jobs = endpoint.export_all("jobs")
>>> recent_jobs = endpoint.export_all("jobs", include_recent_changes=True)
download(id, modifier='', filename=None)[source]

Download a file from the specified endpoint.

Sends a GET request to download a file associated with the record. The modifier can specify the type of file to download (e.g., “attachments”).

Parameters:
  • id – The unique identifier of the record

  • modifier – Optional sub-resource path for downloading specific files

  • filename – Optional filename to save the downloaded file as

Returns:

The content of the downloaded file

Return type:

bytes

Raises:

requests.HTTPError – If the API request fails

Examples

>>> endpoint = Endpoint("forms", "jobs/attachment", conn)
>>> file_content = endpoint.download("12345678")

servicepytan.summary module

Summary functions for ServiceTitan data analysis and reporting.

servicepytan.summary.get_booked_jobs_by_agent(start_date, end_date, conn=None)[source]

Get jobs booked by agent within a date range.

Retrieves jobs created within the specified date range and employee data to analyze job booking performance by agent. This function is currently incomplete and needs implementation to return meaningful results.

Parameters:
  • start_date – Start date for the query (string or datetime object)

  • end_date – End date for the query (string or datetime object)

  • conn – Dictionary containing the credential configuration

Returns:

Function is currently incomplete and needs implementation

Return type:

None

Note

This function is a placeholder and requires completion to provide meaningful job booking analysis by agent.

Examples

>>> # Function needs implementation
>>> result = get_booked_jobs_by_agent("2024-01-01", "2024-01-31", conn)

servicepytan.utils module

Utility Functions for Supporting Other Modules

servicepytan.utils.request_json(url, options={}, payload={}, conn=None, request_type='GET', json_payload={})[source]

Makes the request to the API and returns JSON.

Sends HTTP requests to the ServiceTitan API with proper authentication headers and handles various request types including GET, POST, PUT, PATCH, and DELETE.

Parameters:
  • url – The complete URL for the API request

  • options – Dictionary of query parameters to add to the URL for filtering

  • payload – Dictionary containing form data for the request body

  • conn – Dictionary containing the credential configuration

  • request_type – HTTP method type (“GET”, “POST”, “PUT”, “PATCH”, “DEL”)

  • json_payload – Dictionary containing JSON data for the request body

Returns:

JSON response from the API

Return type:

dict

Raises:

requests.HTTPError – If the API request fails

Examples

>>> response = request_json(
...     "https://api.servicetitan.io/jpm/v2/tenant/123/jobs",
...     options={"pageSize": 100},
...     conn=connection_config
... )
servicepytan.utils.check_default_options(options)[source]

Add sensible defaults to options when not defined.

Ensures that API request options have reasonable defaults to prevent issues with pagination and data retrieval.

Parameters:

options – Dictionary of request options/parameters

Returns:

Options dictionary with defaults applied

Return type:

dict

Examples

>>> options = check_default_options({})
>>> # Returns: {"pageSize": 100}
>>> options = check_default_options({"pageSize": 50})
>>> # Returns: {"pageSize": 50} (unchanged)
servicepytan.utils.endpoint_url(folder, endpoint, id='', modifier='', conn=None, tenant_id='')[source]

Constructs API request URL based on key parameters.

Builds the complete ServiceTitan API URL using the standard URL structure and allows for various endpoint configurations including specific IDs and modifiers.

Parameters:
  • folder – The API endpoint category/folder (e.g., “jpm”, “sales”, “inventory”)

  • endpoint – The specific endpoint within the folder (e.g., “jobs”, “estimates”)

  • id – Optional specific record ID to append to the URL

  • modifier – Optional additional path segment for specialized endpoints

  • conn – Dictionary containing the credential configuration

  • tenant_id – Optional manual override for the tenant ID

Returns:

Complete API URL ready for requests

Return type:

str

Raises:

KeyError – If required connection information is missing

Examples

>>> url = endpoint_url("jpm", "jobs", conn=conn)
>>> # Returns: "https://api.servicetitan.io/jpm/v2/tenant/12345/jobs"
>>> url = endpoint_url("jpm", "jobs", id="67890", modifier="notes", conn=conn)
>>> # Returns: "https://api.servicetitan.io/jpm/v2/tenant/12345/jobs/67890/notes"
servicepytan.utils.create_credential_file(name='servicepytan_config.json')[source]

Creates and saves an unfilled configuration file template.

Generates a JSON configuration file with empty credential fields that can be filled in with actual ServiceTitan API credentials.

Parameters:

name – Filename for the configuration file

Returns:

Path to the created configuration file

Return type:

str

Examples

>>> filepath = create_credential_file("my_config.json")
>>> # Creates a file with empty credential template
servicepytan.utils.get_timezone_by_file(conn=None)[source]

Retrieves timezone from the connection configuration.

Extracts the timezone setting from the connection configuration object, defaulting to “UTC” if no timezone is specified.

Parameters:

conn – Dictionary containing the credential configuration

Returns:

Timezone string (e.g., “America/New_York”, “UTC”)

Return type:

str

Examples

>>> tz = get_timezone_by_file(conn)
>>> # Returns: "America/New_York" or "UTC" if not specified
servicepytan.utils.sleep_with_countdown(sleep_time)[source]

Sleeps for a given amount of time with a countdown display.

Provides a visual countdown timer during sleep periods, typically used when handling rate limiting or waiting between API requests.

Parameters:

sleep_time – Number of seconds to sleep

Examples

>>> sleep_with_countdown(30)
>>> # Displays: "Trying again in 30 seconds...", "29 seconds...", etc.
servicepytan.utils.request_json_with_retry(url, options={}, payload='', conn=None, request_type='GET', json_payload='')[source]

Makes the request to the API and returns JSON with automatic retry for rate limits.

Enhanced version of request_json that automatically handles rate limiting by detecting 429 status codes and retrying after the specified wait time.

Parameters:
  • url – The complete URL for the API request

  • options – Dictionary of query parameters to add to the URL for filtering

  • payload – Dictionary containing form data for the request body

  • conn – Dictionary containing the credential configuration

  • request_type – HTTP method type (“GET”, “POST”, “PUT”, “PATCH”, “DEL”)

  • json_payload – Dictionary containing JSON data for the request body

Returns:

JSON response from the API

Return type:

dict

Raises:

requests.HTTPError – If the API request fails (non-rate-limit errors)

Examples

>>> response = request_json_with_retry(
...     "https://api.servicetitan.io/jpm/v2/tenant/123/jobs",
...     options={"pageSize": 100},
...     conn=connection_config
... )
>>> # Automatically retries if rate limited
servicepytan.utils.request_contents(url, options={}, conn=None)[source]

Fetches the contents of a URL with optional query parameters.

Parameters:
  • url – The complete URL for the API request

  • options – Dictionary of query parameters to add to the URL

  • conn – Dictionary containing the credential configuration

Returns:

JSON response from the API

Return type:

dict

Raises:

requests.HTTPError – If the API request fails

Module contents

A high-level package for ineracting with the ServiceTitan API v2.

ServicePytan provides an API for easily constructing requests to the ServiceTitan API v2. The Endpoint class is the primary means to constructing requests based on the organization detailed on developer site.

Resources:
Examples:
>>> import servicepytan
>>> servicetitan_endpoint = servicepytan.Endpoint("jpm","jobs")
>>> data = servicetitan_endpoint.get_one(id=12345678)