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 CompanyRequest

Demandbase 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
ObjectDescription
demandbase.DBClientMain SDK client. Alias for DemandbaseClient.
demandbase.DemandBaseAPIErrorException raised for Demandbase API errors.
demandbase.enable_loggingConfigures 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 groupDescription
client.b2b_apiCompany search, contact search, company/contact details, news, logos, matching, B2B bulk jobs, and subscriptions.
client.data_export_apiExport field discovery, export job creation, export job listing, and export job status checks.
client.data_import_apiImport job creation, CSV data submission, import job listing, import job status checks, activity types, and import sources.
client.admin_apiNot 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.

NamespaceDescription
demandbase.B2BNamespace for B2B request and response models. B2B API methods are available through client.b2b_api.
demandbase.ExportNamespace for Data Export models and enums. Data Export API methods are available through client.data_export_api.
demandbase.ImportNamespace for Data Import models and enums. Data Import API methods are available through client.data_import_api.
demandbase.AdminReserved for future Admin models.
demandbase.CommonNamespace 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)
ParameterTypeRequiredDefaultDescription
timeoutfloatNo180.0Request timeout in seconds.
retry_countOptional[int]No1Number 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
AttributeTypeDescription
client.b2b_apiB2BAPICompany, contact, bulk match, bulk retrieval, and subscription methods.
client.data_export_apiDataExportAPIData export field, job creation, job listing, and job status methods.
client.data_import_apiDataImportAPIData import jobs, CSV submission, activity types, and import sources.
client.admin_apiAdminAPIReserved for future administrative API methods.
Demandbase Python SDK Client Behavior
BehaviorDetails
Synchronous requestsSDK methods wait for the Demandbase API response before returning.
AuthenticationUse DEMANDBASE_CLIENT_ID and DEMANDBASE_CLIENT_SECRET
Token refreshRefreshes an invalid or expired access token after a 401 response and retries the request.
RetriesRetries 429 and supported 5xx responses up to retry_count using exponential backoff.
Return valuesMethods 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
ParameterTypeRequiredDefaultDescription
levelstrNoDEMANDBASE_LOG_LEVEL or WARNINGLogging level. Supported values are DEBUG, INFO, WARNING, and ERROR.
streamstream-like objectNosys.stderrDestination 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
MethodParametersReturnsDescription
search_companies(search_request)CompanyRequestCompanyResponseSearches the Demandbase company database.
search_contacts(search_request)ContactRequestContactResponseSearches the Demandbase contact database.
fetch_company_details(request_dto)CompanyDetailsRequestCompanyDetailsResponseFetches details for a company ID.
fetch_contact_details(fetch_request)ContactDetailsRequestContactDetailsResponseFetches details for a contact ID.
fetch_company_news_by_category(request_dto)CompanyNewsByCategoryRequestCompanyNewsByCategoryResponseFetches company news filtered by category.
fetch_company_news_feed(request_dto)CompanyNewsFeedRequestCompanyNewsFeedResponseFetches the company news feed.
fetch_company_logo(request_dto)CompanyLogoRequestbytesFetches raw company logo content.
match_companies_and_contacts(match_request)MatchCompanyAndContactRequestMatchCompanyAndContactResponseMatches 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
MethodParametersReturnsDescription
bulk_match_companies_and_contacts(*, csv_data, job_name)csv_data: pandas.DataFrame | bytes | str, job_name: strBulkJobStatusStarts a bulk company/contact match job using CSV data.
create_bulk_data_retrieval_job(*, bulk_job_request)BulkJobRequestBulkJobStatusCreates a bulk B2B data retrieval job.
get_bulk_job_status(*, job_id)job_id: strBulkJobStatusChecks 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
MethodParametersReturnsDescription
list_subscriptions(*, page=1, per_page=50, subscription_type=None)page: int, per_page: int, subscription_type: list[SubscriptionType] | NoneSubscriptionListLists subscriptions.
retrieve_subscription_details(*, subscription_id)subscription_id: strSubscriptionRetrieves one subscription.
create_new_subscription(*, subscription)SubscriptionSubscriptionJobCreates a subscription job.
update_existing_subscription(subscription)SubscriptionSubscriptionJobUpdates a subscription job.
delete_subscription(*, subscription_id)subscription_id: strSubscriptionDeleteResponseDeletes a subscription.
list_subscription_alerts(*, subscription_id, page=1, per_page=10)subscription_id: str, pagination valuesAlertResponseLists alerts for a subscription.
retrieve_specific_subscription_alert(*, subscription_id, alert_id, page=1, per_page=5000)subscription_id: str, alert_id: str, pagination valuesSubscriptionRetrieves a specific subscription alert.
get_subscription_entity_ids(*, subscription_id, page=1, per_page=5000)subscription_id: str, pagination valuesSubscriptionEntityIdsResponseLists company or person IDs for a subscription.
list_subscription_jobs(*, query_params)ListSubscriptionJobRequest or dictListSubscriptionJobResponseLists subscription jobs.
check_subscription_job_status(*, job_id)job_id: strSubscriptionJobChecks 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_job always requests CSV output.

  • job_name and fields are required for create_export_job.

  • Activity exports require from_date and to_date.

  • Campaign and creative exports require ad_report_type and source.

  • Some campaign and creative report types also require from_date and to_date.

  • Campaign and creative field discovery requires ad_report_type.

MethodParametersReturnsDescription
get_available_export_fields(*, entity_type, ad_report_type=None)EntityType, optional ad report typelist[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 optionsJobCreates an export job.
get_submitted_export_jobs(*, entity_type=None, job_status=None, page=None, per_page=None, sort=None)Optional filters and paginationExportJobSearchResultsLists submitted export jobs.
check_status_of_export_job(*, job_id)job_id: strJobChecks an export job status.
create_account_list_export_job(*, job_name, account_list_ids=None)job_name: str, optional account list IDsJobCreates an account list export job.
create_person_list_export_job(*, job_name, person_list_ids=None)job_name: str, optional person list IDsJobCreates 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
MethodParametersReturnsDescription
create_import_job(*, entity_type, data_import_name, source=None, activity_type_id=None)EntityType, import name, optional source/activity typeImportJobCreates an import job.
get_submitted_import_jobs(*, page=None, per_page=None, entity_type=None, sort=None, state=None)Optional filters and paginationImportJobListLists submitted import jobs.
submit_import_data(*, job_id, csv_data, list_action=None)job_id: int, csv_data: pandas.DataFrame | bytes | str, optional list actionImportJobSubmitResponseSubmits CSV data for an import job.
get_import_job_status(job_id)job_id: intImportJobChecks 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
MethodParametersReturnsDescription
create_new_activity_type(*, activity_details)ActivityDetailsActivityTypeResponseCreates an activity type.
update_activity_type(*, activity_type_id, activity_details)activity_type_id: int, ActivityDetailsActivityTypeResponseUpdates an activity type.
get_activity_types()Nonelist[ActivityType]Lists activity types.
get_activity_type_details(activity_type_id)activity_type_id: intActivityDetailsRetrieves one activity type.
get_sources(*, entity_type)EntityTypeImportSourceLists 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.

NameValue
ACCOUNTaccount
PERSONperson
ACTIVITYactivity
CAMPAIGNcampaign
CREATIVEcreative
OPPORTUNITYopportunity
INTENT_ACTIVITYintent_activity
Export JobStatus Values

Import from demandbase.models.Export.

NameValue
ACCEPTEDaccepted
PROCESSINGprocessing
FINISHEDfinished
FAILEDfailed
ALLall
Export Source Values

Import from demandbase.models.Export.

NameValue
DEMANDBASEdemandbase
LINKEDINlinkedin
GOOGLEgoogle
ALLall
Campaign AdReportType Values

Import from demandbase.models.Export.

NameValue
CAMPAIGN_SUMMARYcampaign_summary
CAMPAIGN_PERFORMANCE_ROLLUPcampaign_performance_rollup
CAMPAIGN_ACCOUNT_LIFETIMEcampaign_account_lifetime
CAMPAIGN_ACCOUNT_ROLLUPcampaign_account_rollup
Creative AdReportType Values

Import from demandbase.models.Export.

NameValue
CREATIVE_LIFETIMEcreative_lifetime
CREATIVE_ROLLUPcreative_rollup
ImportJobState Values

Import from demandbase.models.Import.

NameValue
NEWnew
PROCESSINGprocessing
COMPLETEDcompleted
FAILEDfailed
ImportJobListAction Values

Import from demandbase.models.Import.

NameValue
REPLACEreplace
INSERTinsert
DELETEdelete
NOOPnoop
SubscriptionType Values

Import from demandbase.models.B2B

NameValue
COMPANYcompany
COMPANY_NEWScompanyNews
DB_PERSONdbPerson
COMPANY_FAMILY_TREEcompanyFamilyTree
NewsCategory Values

Import from demandbase.models.B2B.

NameValue
LEADERSHIP_CHANGESleadership_changes
NEW_OFFERINGSnew_offerings
PARTNERSHIPSpartnerships
COMPANY_PRESENTATIONcompany_presentation
LITIGATIONlitigation
COMPLIANCEcompliance
RESEARCH_DEVELOPMENTresearch_development
DATA_SECURITYdata_security
FUNDING_DEVELOPMENTSfunding_developments
BANKRUPTCY_RESTRUCTURINGbankruptcy_restructuring
REALESTATE_DEALSrealestate_deals
REALESTATE_CONSTRUCTIONrealestate_construction
CORPORATE_CHALLENGEScorporate_challenges
ACQUISITIONSacquisitions
EXPANDING_OPERATIONSexpanding_operations
COST_CUTTINGcost_cutting
OUTPERFORMINGoutperforming
UNDERPERFORMINGunderperforming

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
ModelImportant fieldsDescription
CompanyRequestname, website, ticker, state, country, industries, subIndustries, keywords, minEmployees, maxEmployees, minRevenue, maxRevenue, naics, sicCodes, regions, sortBy, sortOrder, page, perPageCompany search request filters.
CompanyDTOname, city, state, country, companyIdCompany search result item.
CompanyResponsecompanies, totalCount, pageNo, pageSizePaginated company search response.
Contact Search Models
ModelImportant fieldsDescription
ContactRequestfirstName, lastName, email, contactCity, contactState, contactCountry, titles, companyName, companyWebsite, jobLevels, jobFunctions, active, emailRequired, phoneRequired, phoneType, page, perPageContact search request filters.
ContactResponsecontactResults, totalCount, pageNo, pageSizePaginated contact search response.
ContactResultdbPersonDetails, employmentDetailsOne contact search result.
DbPersonDetailsdbPersonId, firstName, middleName, lastName, age, mobileNumber, educationList, imageUrl, socialHandles, addressPerson profile details returned in contact responses.
EmploymentDetailscontactId, companyId, companyName, contactQualityScore, description, startDate, active, emails, phoneNumbers, jobLevels, jobFunctions, titles, employmentHistoryListEmployment details returned in contact responses.
Company Details Models
ModelImportant fieldsDescription
CompanyDetailsRequestcompanyId, fieldsRequest for company details.
CompanyDetailsResponsecompanyId, companyName, companyType, companyStatus, tickers, classification, address, phone, revenue, employeeCount, subsidiary, sic, naics, familyTree, acquisitions, techUsed, companyLogos, competitorsDetailed company profile response.
Companyname, city, state, country, companyIdCompact company object used in nested responses.
Addressstreet, city, state, zip, country, countryCode, latitude, longitudeCompany address object.
ClassificationprimaryBusiness, secondaryBusinessIndustry classification details.
Industryindustry, industryCode, subIndustry, subIndustryCodeIndustry or sub-industry entry.
FamilyTreecompany, childrenCompany hierarchy node.
TechcategoriesTechnology categories used by a company.
Contact Details Models
ModelImportant fieldsDescription
ContactDetailsRequestcontactId, fields, includeRequest for contact details.
ContactDetailsResponsedbPersonDetails, employmentDetailsDetailed contact response.
Emailemail, validationStatusEmail information.
PhoneNumberdirectNumber, corporateNumberPhone information.
JobLevelid, nameJob level entry.
JobFunctionid, nameJob function entry.
EmploymentHistoryItemcontactId, companyId, companyName, emails, phoneNumbers, active, jobLevels, jobFunctions, titlesEmployment history entry.
Company News And Logo Models
ModelImportant fieldsDescription
CompanyNewsByCategoryRequestcompanyId, newsCategories, page, perPageRequest for company news filtered by category.
CompanyNewsByCategoryResponsecompanyNews, pageNo, pageSize, totalCount, companyIdCompany news by category response.
CompanyNewsFeedRequestcompanyId, page, perPageRequest for company news feed.
CompanyNewsFeedResponsecompanyNews, pageNo, pageSize, totalCount, companyIdCompany news feed response.
NewsItemtitle, url, publicationDate, source, imageUrl, newsCategoryNews article item.
CompanyLogoRequestcompanyId, logoSizeRequest for company logo bytes.
Company and Contact Match Models
ModelImportant fieldsDescription
Requestsname, country, state, city, street, zip, websites, ticker, phone, id, firstName, lastName, title, fullName, email, isPhoneRequired, isEmailRequired, executiveLinkedInHandle, contactMatching, contactStatusOne company/contact input record for matching.
MatchCompanyAndContactRequestrequests, fields, limitResults, minimumMatchScore, matchBranch, minContactQualityScoreBatch matching request.
MatchCompanyAndContactResponsematchesMatching response.
Matchid, companyMatches, contactMatchesOne match result.
CompanyMatchmatchScore, companyMatched company result.
ContactMatchmatchScore, contactMatched contact result.
B2B Bulk Job Models
ModelFieldsDescription
BulkJobRequestjobType, jobName, fields, filters, sortOrder, sortByBulk data retrieval job request.
Filtersfield, valuesFilter used in a bulk job request.
BulkJobStatusjobName, jobStatus, jobType, jobId, createdAt, updatedAt, resultsUrl, messageBulk job status response.
Subscription Models
ModelFieldsDescription
SubscriptioncompanyIds, addCompanyIds, removeCompanyIds, dbPersonIds, addDbPersonIds, removeDbPersonIds, subscriptionId, name, description, subscriptionType, frequency, fields, newsCategories, webhook, signingSecret, createdAt, startDate, nextFireTimeSubscription request and response object.
Webhookurl, status, disableReasonMessage, signingSecretWebhook configuration for a subscription.
SubscriptionListsubscriptionsList subscriptions response.
SubscriptionJobjobId, jobStatus, subscriptionId, totalEntitiesProcessed, jobType, subscriptionType, createdAt, updatedAt, message, invalidIdsSubscription job status.
ListSubscriptionJobRequestend, jobStatus, jobType, page, perPage, period, startRequest filters for listing subscription jobs.
ListSubscriptionJobResponsesubscriptionJobs, page, pageSize, totalPages, totalCountList subscription jobs response.
SubscriptionEntityIdsResponsecompanyIds, personIds, pageNo, pageSize, totalPages, totalCountEntity IDs response.
SubscriptionDeleteResponsesubscriptionId, messageDelete subscription response.
AlertalertId, createdAtSubscription alert item.
AlertResponsealerts, pageNo, pageSize, totalPagesSubscription alerts response.
Data Export Models
ModelFieldsDescription
Fieldname, label, dataTypeMetadata for an exportable field.
JobjobName, updatedAt, jobStatus, entityType, jobId, createdAt, resultsUrl, resultsUrls, messageExport job response.
ExportJobSearchResultstotalCount, pageNo, pageSize, dataPaginated export jobs response.
Data Import Models
ModelFieldsDescription
ImportJobid, dataImportName, entityType, state, updatedAt, createdAtImport job response.
ImportJobListtotalCount, dataList import jobs response.
ImportJobSubmitResponseid, dataImportName, entityType, state, updatedAt, createdAt, source, activityTypeIdSubmit import data response.
ImportFieldfieldName, fieldDataType, defaultField, isRequiredForCsvImportImport field metadata.
ActivityTypelabel, name, description, id, activitySourceActivity type entry.
ActivityTypeResponseid, labelActivity type create/update response.
ActivityDetailsactivityType, fieldsActivity type details.
ImportSourcedataImport 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 CompanyRequest

Did this page help you?