Demandbase Python SDK Reference
The Demandbase Python SDK provides a synchronous Python client for accessing Demandbase APIs. Use the SDK to search B2B data, manage bulk jobs and subscriptions, import and export data, configure logging, and work with typed Pydantic request and response models.
The SDK connects to the production Demandbase API.
Import the Demandbase Python SDK
You can access SDK functionality through the demandbase package namespace or import public objects directly.
Use the package namespace
import demandbase
with demandbase.DBClient() as client:
subscriptions = client.b2b_api.list_subscriptions()Import Public Objects Directly
from demandbase import DBClient, DemandBaseAPIError
from demandbase.models.Common import EntityType
from demandbase.models.B2B.CompanySearch import CompanyRequestDemandbase Python SDK Package and Module Reference
The top-level demandbase package provides the SDK client, error handling, logging configuration, API resources, and model and enum namespaces.
Demandbase Python SDK Client and Helper Objects
| Object | Description |
|---|---|
demandbase.DBClient | Main SDK client. Alias for DemandbaseClient. |
demandbase.DemandBaseAPIError | Exception raised for Demandbase API errors. |
demandbase.enable_logging | Configures SDK logging. |
demandbase.__version__ | Installed SDK package version. |
Demandbase Python SDK API Groups
After creating a DBClient, access SDK methods through the following API groups:
| API group | Description |
|---|---|
client.b2b_api | Company search, contact search, company/contact details, news, logos, matching, B2B bulk jobs, and subscriptions. |
client.data_export_api | Export field discovery, export job creation, export job listing, and export job status checks. |
client.data_import_api | Import job creation, CSV data submission, import job listing, import job status checks, activity types, and import sources. |
client.admin_api | Not implemented. Reserved for future administrative API methods and currently exposes no public SDK methods. |
Demandbase Python SDK Model and Enum Namespaces
Model namespaces are case-sensitive.
The top-level demandbase.B2B, demandbase.Export, demandbase.Import, and demandbase.Common names are convenience aliases.
| Namespace | Description |
|---|---|
demandbase.B2B | Namespace for B2B request and response models. B2B API methods are available through client.b2b_api. |
demandbase.Export | Namespace for Data Export models and enums. Data Export API methods are available through client.data_export_api. |
demandbase.Import | Namespace for Data Import models and enums. Data Import API methods are available through client.data_import_api. |
demandbase.Admin | Reserved for future Admin models. |
demandbase.Common | Namespace for shared enums and common model helpers. |
Demandbase Python SDK Data Models
Pydantic models are available under demandbase.models.
demandbase.models.B2B.CompanyRequest/CompanyResponse: Company search payloads.demandbase.models.Export.Job,ExportJobSearchResults: Export job models.demandbase.models.Import.ImportJob,ImportJobSubmitResponse: Import job models.
Initialize and Configure the Demandbase Python SDK Client
Use demandbase.DBClient to create a synchronous SDK client. Use the client as a context manager when possible so underlying HTTP resources close automatically.
Initialize the SDK Client
with demandbase.DBClient(timeout=60.0, retry_count=2) as client:
result = client.b2b_api.list_subscriptions()Configure DBClient Parameters
Signature:
demandbase.DBClient(*, timeout: float = 180.0, retry_count: Optional[int] = 1)| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
timeout | float | No | 180.0 | Request timeout in seconds. |
retry_count | Optional[int] | No | 1 | Number of retry attempts for supported retry cases. |
If you instantiate DBClient without a with statement, call client.close() when your application is finished using it.
Demandbase Python SDK Client Attributes
| Attribute | Type | Description |
|---|---|---|
client.b2b_api | B2BAPI | Company, contact, bulk match, bulk retrieval, and subscription methods. |
client.data_export_api | DataExportAPI | Data export field, job creation, job listing, and job status methods. |
client.data_import_api | DataImportAPI | Data import jobs, CSV submission, activity types, and import sources. |
client.admin_api | AdminAPI | Reserved for future administrative API methods. |
Demandbase Python SDK Client Behavior
| Behavior | Details |
|---|---|
| Synchronous requests | SDK methods wait for the Demandbase API response before returning. |
| Authentication | Use DEMANDBASE_CLIENT_ID and DEMANDBASE_CLIENT_SECRET |
| Token refresh | Refreshes an invalid or expired access token after a 401 response and retries the request. |
| Retries | Retries 429 and supported 5xx responses up to retry_count using exponential backoff. |
| Return values | Methods generally return Pydantic model instances. Access values as attributes, or use .model_dump() / .model_dump_json() when you need dictionary or JSON output. |
Configure Demandbase Python SDK Logging
Use demandbase.enable_logging() to enable SDK logging.
Important: SDK logs can contain sensitive business data. See Protect Sensitive Data in Demandbase SDK Logs for security guidance.
Configure enable_logging() Parameters
Signature:
demandbase.enable_logging(level: str = None, *, stream=None) -> None| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
level | str | No | DEMANDBASE_LOG_LEVEL or WARNING | Logging level. Supported values are DEBUG, INFO, WARNING, and ERROR. |
stream | stream-like object | No | sys.stderr | Destination for SDK logs. Use sys.stdout, a file handle, or another writable stream. |
Example: Send Logs to Standard Output
import sys
import demandbase
demandbase.enable_logging("INFO", stream=sys.stdout)Example: Send Logs to a File
import demandbase
log_file = open("demandbase-sdk.log", "a", encoding="utf-8")
demandbase.enable_logging("DEBUG", stream=log_file)Use the Demandbase Python SDK B2B API
Access B2B API methods through client.b2b_api.
Search and Retrieve Companies and Contacts
| Method | Parameters | Returns | Description |
|---|---|---|---|
search_companies(search_request) | CompanyRequest | CompanyResponse | Searches the Demandbase company database. |
search_contacts(search_request) | ContactRequest | ContactResponse | Searches the Demandbase contact database. |
fetch_company_details(request_dto) | CompanyDetailsRequest | CompanyDetailsResponse | Fetches details for a company ID. |
fetch_contact_details(fetch_request) | ContactDetailsRequest | ContactDetailsResponse | Fetches details for a contact ID. |
fetch_company_news_by_category(request_dto) | CompanyNewsByCategoryRequest | CompanyNewsByCategoryResponse | Fetches company news filtered by category. |
fetch_company_news_feed(request_dto) | CompanyNewsFeedRequest | CompanyNewsFeedResponse | Fetches the company news feed. |
fetch_company_logo(request_dto) | CompanyLogoRequest | bytes | Fetches raw company logo content. |
match_companies_and_contacts(match_request) | MatchCompanyAndContactRequest | MatchCompanyAndContactResponse | Matches company and contact input records. |
Example: Search for Companies
import demandbase
from demandbase.models.B2B.CompanySearch import CompanyRequest
with demandbase.DBClient() as client:
request = CompanyRequest(name="Demandbase", page="1", perPage="10")
response = client.b2b_api.search_companies(request)
print(response.totalCount)Manage B2B Bulk Jobs
| Method | Parameters | Returns | Description |
|---|---|---|---|
bulk_match_companies_and_contacts(*, csv_data, job_name) | csv_data: pandas.DataFrame | bytes | str, job_name: str | BulkJobStatus | Starts a bulk company/contact match job using CSV data. |
create_bulk_data_retrieval_job(*, bulk_job_request) | BulkJobRequest | BulkJobStatus | Creates a bulk B2B data retrieval job. |
get_bulk_job_status(*, job_id) | job_id: str | BulkJobStatus | Checks the status of a B2B bulk job. |
For csv_data, provide a pandas.DataFrame, raw CSV bytes, or a local file path string. When you provide a path string, the SDK opens and reads the file. Do not provide an already-open file stream.
Manage B2B Subscriptions
| Method | Parameters | Returns | Description |
|---|---|---|---|
list_subscriptions(*, page=1, per_page=50, subscription_type=None) | page: int, per_page: int, subscription_type: list[SubscriptionType] | None | SubscriptionList | Lists subscriptions. |
retrieve_subscription_details(*, subscription_id) | subscription_id: str | Subscription | Retrieves one subscription. |
create_new_subscription(*, subscription) | Subscription | SubscriptionJob | Creates a subscription job. |
update_existing_subscription(subscription) | Subscription | SubscriptionJob | Updates a subscription job. |
delete_subscription(*, subscription_id) | subscription_id: str | SubscriptionDeleteResponse | Deletes a subscription. |
list_subscription_alerts(*, subscription_id, page=1, per_page=10) | subscription_id: str, pagination values | AlertResponse | Lists alerts for a subscription. |
retrieve_specific_subscription_alert(*, subscription_id, alert_id, page=1, per_page=5000) | subscription_id: str, alert_id: str, pagination values | Subscription | Retrieves a specific subscription alert. |
get_subscription_entity_ids(*, subscription_id, page=1, per_page=5000) | subscription_id: str, pagination values | SubscriptionEntityIdsResponse | Lists company or person IDs for a subscription. |
list_subscription_jobs(*, query_params) | ListSubscriptionJobRequest or dict | ListSubscriptionJobResponse | Lists subscription jobs. |
check_subscription_job_status(*, job_id) | job_id: str | SubscriptionJob | Checks the status of a subscription job. |
Example: List Subscriptions
import demandbase
with demandbase.DBClient() as client:
subscriptions = client.b2b_api.list_subscriptions(page=1, per_page=10)
for subscription in subscriptions.subscriptions or []:
print(subscription.subscriptionId, subscription.name)Use the Demandbase Python SDK Data Export API
Access Data Export methods through client.data_export_api.
Demandbase Data Export API Methods
Requirements and behavior:
-
create_export_jobalways requests CSV output. -
job_nameandfieldsare required forcreate_export_job. -
Activity exports require
from_dateandto_date. -
Campaign and creative exports require
ad_report_typeandsource. -
Some campaign and creative report types also require
from_dateandto_date. -
Campaign and creative field discovery requires
ad_report_type.
| Method | Parameters | Returns | Description |
|---|---|---|---|
get_available_export_fields(*, entity_type, ad_report_type=None) | EntityType, optional ad report type | list[Field] | Lists fields available for export. |
create_export_job(*, entity_type, job_name=None, fields=None, from_date=None, to_date=None, source=None, ad_report_type=None, account_list_ids=None, person_list_ids=None) | Export job options | Job | Creates an export job. |
get_submitted_export_jobs(*, entity_type=None, job_status=None, page=None, per_page=None, sort=None) | Optional filters and pagination | ExportJobSearchResults | Lists submitted export jobs. |
check_status_of_export_job(*, job_id) | job_id: str | Job | Checks an export job status. |
create_account_list_export_job(*, job_name, account_list_ids=None) | job_name: str, optional account list IDs | Job | Creates an account list export job. |
create_person_list_export_job(*, job_name, person_list_ids=None) | job_name: str, optional person list IDs | Job | Creates a person list export job. |
Example: Retrieve Available Export Fields
import demandbase
from demandbase.models.Common import EntityType
with demandbase.DBClient() as client:
fields = client.data_export_api.get_available_export_fields(
entity_type=EntityType.ACCOUNT
)
print([field.name for field in fields])Use the Demandbase Python SDK Data Import API
Access Data Import methods through client.data_import_api.
Manage Data Import Jobs
| Method | Parameters | Returns | Description |
|---|---|---|---|
create_import_job(*, entity_type, data_import_name, source=None, activity_type_id=None) | EntityType, import name, optional source/activity type | ImportJob | Creates an import job. |
get_submitted_import_jobs(*, page=None, per_page=None, entity_type=None, sort=None, state=None) | Optional filters and pagination | ImportJobList | Lists submitted import jobs. |
submit_import_data(*, job_id, csv_data, list_action=None) | job_id: int, csv_data: pandas.DataFrame | bytes | str, optional list action | ImportJobSubmitResponse | Submits CSV data for an import job. |
get_import_job_status(job_id) | job_id: int | ImportJob | Checks an import job status. |
For csv_data, provide a pandas.DataFrame, raw CSV bytes, or a local file path string. When you provide a path string, the SDK opens and reads the file. Do not provide an already-open file stream.
Example: Create an Import Job
import demandbase
from demandbase.models.Common import EntityType
with demandbase.DBClient() as client:
job = client.data_import_api.create_import_job(
entity_type=EntityType.PERSON,
data_import_name="example_person_import"
)
print(job.id, job.state)Manage Data Import Activity Types and Sources
| Method | Parameters | Returns | Description |
|---|---|---|---|
create_new_activity_type(*, activity_details) | ActivityDetails | ActivityTypeResponse | Creates an activity type. |
update_activity_type(*, activity_type_id, activity_details) | activity_type_id: int, ActivityDetails | ActivityTypeResponse | Updates an activity type. |
get_activity_types() | None | list[ActivityType] | Lists activity types. |
get_activity_type_details(activity_type_id) | activity_type_id: int | ActivityDetails | Retrieves one activity type. |
get_sources(*, entity_type) | EntityType | ImportSource | Lists sources for an entity type. |
Example: List Activity Types
import demandbase
with demandbase.DBClient() as client:
activity_types = client.data_import_api.get_activity_types()
for activity_type in activity_types:
print(activity_type.id, activity_type.name)Demandbase Python SDK Admin API Availability
Access the Admin API group through client.admin_api.
The Admin API group is reserved for future compatibility and currently exposes no public SDK methods.
Demandbase Python SDK Enum Reference
Use the following enums when SDK methods require predefined values:
EntityType Values
Import from demandbase.models.Common.
| Name | Value |
|---|---|
ACCOUNT | account |
PERSON | person |
ACTIVITY | activity |
CAMPAIGN | campaign |
CREATIVE | creative |
OPPORTUNITY | opportunity |
INTENT_ACTIVITY | intent_activity |
Export JobStatus Values
Import from demandbase.models.Export.
| Name | Value |
|---|---|
ACCEPTED | accepted |
PROCESSING | processing |
FINISHED | finished |
FAILED | failed |
ALL | all |
Export Source Values
Import from demandbase.models.Export.
| Name | Value |
|---|---|
DEMANDBASE | demandbase |
LINKEDIN | linkedin |
GOOGLE | google |
ALL | all |
Campaign AdReportType Values
Import from demandbase.models.Export.
| Name | Value |
|---|---|
CAMPAIGN_SUMMARY | campaign_summary |
CAMPAIGN_PERFORMANCE_ROLLUP | campaign_performance_rollup |
CAMPAIGN_ACCOUNT_LIFETIME | campaign_account_lifetime |
CAMPAIGN_ACCOUNT_ROLLUP | campaign_account_rollup |
Creative AdReportType Values
Import from demandbase.models.Export.
| Name | Value |
|---|---|
CREATIVE_LIFETIME | creative_lifetime |
CREATIVE_ROLLUP | creative_rollup |
ImportJobState Values
Import from demandbase.models.Import.
| Name | Value |
|---|---|
NEW | new |
PROCESSING | processing |
COMPLETED | completed |
FAILED | failed |
ImportJobListAction Values
Import from demandbase.models.Import.
| Name | Value |
|---|---|
REPLACE | replace |
INSERT | insert |
DELETE | delete |
NOOP | noop |
SubscriptionType Values
Import from demandbase.models.B2B
| Name | Value |
|---|---|
COMPANY | company |
COMPANY_NEWS | companyNews |
DB_PERSON | dbPerson |
COMPANY_FAMILY_TREE | companyFamilyTree |
NewsCategory Values
Import from demandbase.models.B2B.
| Name | Value |
|---|---|
LEADERSHIP_CHANGES | leadership_changes |
NEW_OFFERINGS | new_offerings |
PARTNERSHIPS | partnerships |
COMPANY_PRESENTATION | company_presentation |
LITIGATION | litigation |
COMPLIANCE | compliance |
RESEARCH_DEVELOPMENT | research_development |
DATA_SECURITY | data_security |
FUNDING_DEVELOPMENTS | funding_developments |
BANKRUPTCY_RESTRUCTURING | bankruptcy_restructuring |
REALESTATE_DEALS | realestate_deals |
REALESTATE_CONSTRUCTION | realestate_construction |
CORPORATE_CHALLENGES | corporate_challenges |
ACQUISITIONS | acquisitions |
EXPANDING_OPERATIONS | expanding_operations |
COST_CUTTING | cost_cutting |
OUTPERFORMING | outperforming |
UNDERPERFORMING | underperforming |
Demandbase Python SDK Model Reference
The SDK uses Pydantic models for request and response data. The following summarize the primary public models and their important fields:
Company Search Models
| Model | Important fields | Description |
|---|---|---|
CompanyRequest | name, website, ticker, state, country, industries, subIndustries, keywords, minEmployees, maxEmployees, minRevenue, maxRevenue, naics, sicCodes, regions, sortBy, sortOrder, page, perPage | Company search request filters. |
CompanyDTO | name, city, state, country, companyId | Company search result item. |
CompanyResponse | companies, totalCount, pageNo, pageSize | Paginated company search response. |
Contact Search Models
| Model | Important fields | Description |
|---|---|---|
ContactRequest | firstName, lastName, email, contactCity, contactState, contactCountry, titles, companyName, companyWebsite, jobLevels, jobFunctions, active, emailRequired, phoneRequired, phoneType, page, perPage | Contact search request filters. |
ContactResponse | contactResults, totalCount, pageNo, pageSize | Paginated contact search response. |
ContactResult | dbPersonDetails, employmentDetails | One contact search result. |
DbPersonDetails | dbPersonId, firstName, middleName, lastName, age, mobileNumber, educationList, imageUrl, socialHandles, address | Person profile details returned in contact responses. |
EmploymentDetails | contactId, companyId, companyName, contactQualityScore, description, startDate, active, emails, phoneNumbers, jobLevels, jobFunctions, titles, employmentHistoryList | Employment details returned in contact responses. |
Company Details Models
| Model | Important fields | Description |
|---|---|---|
CompanyDetailsRequest | companyId, fields | Request for company details. |
CompanyDetailsResponse | companyId, companyName, companyType, companyStatus, tickers, classification, address, phone, revenue, employeeCount, subsidiary, sic, naics, familyTree, acquisitions, techUsed, companyLogos, competitors | Detailed company profile response. |
Company | name, city, state, country, companyId | Compact company object used in nested responses. |
Address | street, city, state, zip, country, countryCode, latitude, longitude | Company address object. |
Classification | primaryBusiness, secondaryBusiness | Industry classification details. |
Industry | industry, industryCode, subIndustry, subIndustryCode | Industry or sub-industry entry. |
FamilyTree | company, children | Company hierarchy node. |
Tech | categories | Technology categories used by a company. |
Contact Details Models
| Model | Important fields | Description |
|---|---|---|
ContactDetailsRequest | contactId, fields, include | Request for contact details. |
ContactDetailsResponse | dbPersonDetails, employmentDetails | Detailed contact response. |
Email | email, validationStatus | Email information. |
PhoneNumber | directNumber, corporateNumber | Phone information. |
JobLevel | id, name | Job level entry. |
JobFunction | id, name | Job function entry. |
EmploymentHistoryItem | contactId, companyId, companyName, emails, phoneNumbers, active, jobLevels, jobFunctions, titles | Employment history entry. |
Company News And Logo Models
| Model | Important fields | Description |
|---|---|---|
CompanyNewsByCategoryRequest | companyId, newsCategories, page, perPage | Request for company news filtered by category. |
CompanyNewsByCategoryResponse | companyNews, pageNo, pageSize, totalCount, companyId | Company news by category response. |
CompanyNewsFeedRequest | companyId, page, perPage | Request for company news feed. |
CompanyNewsFeedResponse | companyNews, pageNo, pageSize, totalCount, companyId | Company news feed response. |
NewsItem | title, url, publicationDate, source, imageUrl, newsCategory | News article item. |
CompanyLogoRequest | companyId, logoSize | Request for company logo bytes. |
Company and Contact Match Models
| Model | Important fields | Description |
|---|---|---|
Requests | name, country, state, city, street, zip, websites, ticker, phone, id, firstName, lastName, title, fullName, email, isPhoneRequired, isEmailRequired, executiveLinkedInHandle, contactMatching, contactStatus | One company/contact input record for matching. |
MatchCompanyAndContactRequest | requests, fields, limitResults, minimumMatchScore, matchBranch, minContactQualityScore | Batch matching request. |
MatchCompanyAndContactResponse | matches | Matching response. |
Match | id, companyMatches, contactMatches | One match result. |
CompanyMatch | matchScore, company | Matched company result. |
ContactMatch | matchScore, contact | Matched contact result. |
B2B Bulk Job Models
| Model | Fields | Description |
|---|---|---|
BulkJobRequest | jobType, jobName, fields, filters, sortOrder, sortBy | Bulk data retrieval job request. |
Filters | field, values | Filter used in a bulk job request. |
BulkJobStatus | jobName, jobStatus, jobType, jobId, createdAt, updatedAt, resultsUrl, message | Bulk job status response. |
Subscription Models
| Model | Fields | Description |
|---|---|---|
Subscription | companyIds, addCompanyIds, removeCompanyIds, dbPersonIds, addDbPersonIds, removeDbPersonIds, subscriptionId, name, description, subscriptionType, frequency, fields, newsCategories, webhook, signingSecret, createdAt, startDate, nextFireTime | Subscription request and response object. |
Webhook | url, status, disableReasonMessage, signingSecret | Webhook configuration for a subscription. |
SubscriptionList | subscriptions | List subscriptions response. |
SubscriptionJob | jobId, jobStatus, subscriptionId, totalEntitiesProcessed, jobType, subscriptionType, createdAt, updatedAt, message, invalidIds | Subscription job status. |
ListSubscriptionJobRequest | end, jobStatus, jobType, page, perPage, period, start | Request filters for listing subscription jobs. |
ListSubscriptionJobResponse | subscriptionJobs, page, pageSize, totalPages, totalCount | List subscription jobs response. |
SubscriptionEntityIdsResponse | companyIds, personIds, pageNo, pageSize, totalPages, totalCount | Entity IDs response. |
SubscriptionDeleteResponse | subscriptionId, message | Delete subscription response. |
Alert | alertId, createdAt | Subscription alert item. |
AlertResponse | alerts, pageNo, pageSize, totalPages | Subscription alerts response. |
Data Export Models
| Model | Fields | Description |
|---|---|---|
Field | name, label, dataType | Metadata for an exportable field. |
Job | jobName, updatedAt, jobStatus, entityType, jobId, createdAt, resultsUrl, resultsUrls, message | Export job response. |
ExportJobSearchResults | totalCount, pageNo, pageSize, data | Paginated export jobs response. |
Data Import Models
| Model | Fields | Description |
|---|---|---|
ImportJob | id, dataImportName, entityType, state, updatedAt, createdAt | Import job response. |
ImportJobList | totalCount, data | List import jobs response. |
ImportJobSubmitResponse | id, dataImportName, entityType, state, updatedAt, createdAt, source, activityTypeId | Submit import data response. |
ImportField | fieldName, fieldDataType, defaultField, isRequiredForCsvImport | Import field metadata. |
ActivityType | label, name, description, id, activitySource | Activity type entry. |
ActivityTypeResponse | id, label | Activity type create/update response. |
ActivityDetails | activityType, fields | Activity type details. |
ImportSource | data | Import source list response. |
Access and Serialize Demandbase Python SDK Responses
SDK methods generally return Pydantic models. Access fields directly as attributes or serialize the model when you need a Python dictionary or JSON.
Access and Serialize SDK Responses
response = client.b2b_api.list_subscriptions()
print(response.subscriptions)
print(response.model_dump())
print(response.model_dump_json())Appendix: Demandbase Python SDK Public API Index
The demandbase package provides the SDK client, API error type, logging helper, and model and enum namespaces used in request and response objects.
API methods are available through client resource attributes such as, client.b2b_api, client.data_export_api, and client.data_import_api.
You can use the package namespace or import public objects directly.
Use the Package Namespace
import demandbase
with demandbase.DBClient() as client:
...Direct Import Style
from demandbase import DBClient, DemandBaseAPIError
from demandbase.models.Common import EntityType
from demandbase.models.B2B.CompanySearch import CompanyRequestUpdated 25 days ago