SDK Reference
Python SDK Reference
This page documents the public API surface of the Demandbase Python SDK. The SDK exposes a synchronous Python client, grouped API resources, Pydantic request and response models, enum values, logging configuration, and a shared API error type.
The SDK connects to the production Demandbase API.
Imports
You can use the package namespace:
import demandbase
with demandbase.DBClient() as client:
subscriptions = client.b2b_api.list_subscriptions()Or import public objects directly:
from demandbase import DBClient, DemandBaseAPIError
from demandbase.models.Common import EntityType
from demandbase.models.B2B.CompanySearch import CompanyRequestTop-Level Package
Client And Helper Imports
| Import | 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. |
API Method Groups
After creating a DBClient, call SDK methods from these 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. |
Model And Enum Namespaces
Model namespaces are case-sensitive. Use demandbase.models.B2B, demandbase.models.Export, demandbase.models.Import, and demandbase.models.Common. The top-level demandbase.B2B, demandbase.Export, demandbase.Import, and demandbase.Common names are convenience aliases for those namespaces.
| Import | 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 | Not implemented. Namespace reserved for future Admin models. |
demandbase.Common | Namespace for shared enums and common model helpers. |
Client
demandbase.DBClient
demandbase.DBClientCreates a synchronous SDK client. Use it as a context manager so the underlying HTTP resources are closed automatically.
with demandbase.DBClient(timeout=60.0, retry_count=2) as client:
result = client.b2b_api.list_subscriptions()timeout is measured in seconds. For example, timeout=60.0 allows a request to run for up to 60 seconds before timing out.
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. |
Public 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. |
Client lifecycle:
Use DBClient as a context manager when possible. If you instantiate the client without with, call client.close() when your application is done using it.
Behavior:
| Behavior | Details |
|---|---|
| Synchronous requests | SDK methods wait for the Demandbase API response before returning. |
| Authentication | The SDK uses DEMANDBASE_CLIENT_ID and DEMANDBASE_CLIENT_SECRET to authenticate requests. |
| Token refresh | If a request receives a 401 because the access token is invalid or expired, the SDK refreshes the token and retries. |
| Retries | The SDK retries 429 and selected 5xx responses up to retry_count with exponential backoff. |
| Return values | Methods return Pydantic model instances unless otherwise noted. Access values as attributes, or use .model_dump() / .model_dump_json() when you need dictionary or JSON output. |
Logging
demandbase.enable_logging
demandbase.enable_loggingEnables SDK logging.
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. |
Examples:
import sys
import demandbase
demandbase.enable_logging("INFO", stream=sys.stdout)import demandbase
log_file = open("demandbase-sdk.log", "a", encoding="utf-8")
demandbase.enable_logging("DEBUG", stream=log_file)Error Type
demandbase.DemandBaseAPIError
demandbase.DemandBaseAPIErrorRaised when the Demandbase API returns an error response or when the SDK prevents a request because required request values are missing.
Important attributes:
| Attribute | Type | Description |
|---|---|---|
request_path | str | API path associated with the failed request. |
http_status_code | int | HTTP status code. |
error_message | str | Error message returned by the API or generated by the SDK. |
request_headers | mapping or None | Request headers, when available. |
response_headers | mapping or None | Response headers, when available. Useful for rate-limit handling. |
payload | object or None | Request payload, when available. |
parameters | object or None | Query parameters, when available. |
SDK log output redacts bearer access tokens from authorization headers. Request payloads and query parameters can still contain sensitive business data, so avoid logging full error context in production unless your application has appropriate controls.
Example:
import demandbase
try:
with demandbase.DBClient() as client:
subscriptions = client.b2b_api.list_subscriptions()
except demandbase.DemandBaseAPIError as error:
print(error.http_status_code)
print(error.error_message)B2B API
Access through client.b2b_api.
Search And Retrieval
| 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:
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)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. |
csv_data can be a pandas.DataFrame, raw CSV bytes, or a local file path string. When you pass a path string, the SDK opens and reads the file. Do not pass an already-open file stream.
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:
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)Data Export API
Access through client.data_export_api.
| 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. |
Notes:
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 report types also requirefrom_dateandto_date. - Campaign and creative field discovery requires
ad_report_type.
Example:
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])Data Import API
Access through client.data_import_api.
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. |
csv_data can be a pandas.DataFrame, raw CSV bytes, or a local file path string. When you pass a path string, the SDK opens and reads the file. Do not pass an already-open file stream.
Example:
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)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:
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)Admin API
Access through client.admin_api.
The Admin API group is not implemented. It is present on the client for future compatibility, but currently exposes no public SDK methods.
Common Enums
EntityType
EntityTypeImport from demandbase.models.Common.
| Name | Value |
|---|---|
ACCOUNT | account |
PERSON | person |
ACTIVITY | activity |
CAMPAIGN | campaign |
CREATIVE | creative |
OPPORTUNITY | opportunity |
INTENT_ACTIVITY | intent_activity |
JobStatus
JobStatusImport from demandbase.models.Export.
| Name | Value |
|---|---|
ACCEPTED | accepted |
PROCESSING | processing |
FINISHED | finished |
FAILED | failed |
ALL | all |
Source
SourceImport from demandbase.models.Export.
| Name | Value |
|---|---|
DEMANDBASE | demandbase |
LINKEDIN | linkedin |
GOOGLE | google |
ALL | all |
AdReportType.Campaign
AdReportType.CampaignImport 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 |
AdReportType.Creative
AdReportType.CreativeImport from demandbase.models.Export.
| Name | Value |
|---|---|
CREATIVE_LIFETIME | creative_lifetime |
CREATIVE_ROLLUP | creative_rollup |
ImportJobState
ImportJobStateImport from demandbase.models.Import.
| Name | Value |
|---|---|
NEW | new |
PROCESSING | processing |
COMPLETED | completed |
FAILED | failed |
ImportJobListAction
ImportJobListActionImport from demandbase.models.Import.
| Name | Value |
|---|---|
REPLACE | replace |
INSERT | insert |
DELETE | delete |
NOOP | noop |
SubscriptionType
SubscriptionTypeImport from demandbase.models.B2B.
| Name | Value |
|---|---|
COMPANY | company |
COMPANY_NEWS | companyNews |
DB_PERSON | dbPerson |
COMPANY_FAMILY_TREE | companyFamilyTree |
NewsCategory
NewsCategoryImport 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 |
B2B Models
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. |
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. |
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. |
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. |
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. |
Serialization
SDK methods usually return Pydantic models. Access fields as attributes, or serialize models when you need dictionaries or JSON.
response = client.b2b_api.list_subscriptions()
print(response.subscriptions)
print(response.model_dump())
print(response.model_dump_json())Validation And Exceptions
The SDK validates some client-side inputs before sending requests:
| Case | Exception |
|---|---|
Missing DEMANDBASE_CLIENT_ID or DEMANDBASE_CLIENT_SECRET | RuntimeError |
Invalid pagination values such as page < 1 | ValueError |
| Invalid local file path for CSV upload | ValueError |
| Unsupported CSV input type | ValueError or TypeError, depending on method |
| Demandbase API error response | DemandBaseAPIError |
Related Pages
Updated 1 day ago