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 CompanyRequest

Top-Level Package

Client And Helper Imports

ImportDescription
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.

API Method Groups

After creating a DBClient, call SDK methods from these 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.

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.

ImportDescription
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.AdminNot implemented. Namespace reserved for future Admin models.
demandbase.CommonNamespace for shared enums and common model helpers.

Client

demandbase.DBClient

Creates 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)
ParameterTypeRequiredDefaultDescription
timeoutfloatNo180.0Request timeout in seconds.
retry_countOptional[int]No1Number of retry attempts for supported retry cases.

Public 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.

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:

BehaviorDetails
Synchronous requestsSDK methods wait for the Demandbase API response before returning.
AuthenticationThe SDK uses DEMANDBASE_CLIENT_ID and DEMANDBASE_CLIENT_SECRET to authenticate requests.
Token refreshIf a request receives a 401 because the access token is invalid or expired, the SDK refreshes the token and retries.
RetriesThe SDK retries 429 and selected 5xx responses up to retry_count with exponential backoff.
Return valuesMethods 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

Enables SDK logging.

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.

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

Raised when the Demandbase API returns an error response or when the SDK prevents a request because required request values are missing.

Important attributes:

AttributeTypeDescription
request_pathstrAPI path associated with the failed request.
http_status_codeintHTTP status code.
error_messagestrError message returned by the API or generated by the SDK.
request_headersmapping or NoneRequest headers, when available.
response_headersmapping or NoneResponse headers, when available. Useful for rate-limit handling.
payloadobject or NoneRequest payload, when available.
parametersobject or NoneQuery 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

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:

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

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.

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

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:

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.

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.

Notes:

  • 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 report types also require from_date and to_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

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.

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

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:

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

Import from demandbase.models.Common.

NameValue
ACCOUNTaccount
PERSONperson
ACTIVITYactivity
CAMPAIGNcampaign
CREATIVEcreative
OPPORTUNITYopportunity
INTENT_ACTIVITYintent_activity

JobStatus

Import from demandbase.models.Export.

NameValue
ACCEPTEDaccepted
PROCESSINGprocessing
FINISHEDfinished
FAILEDfailed
ALLall

Source

Import from demandbase.models.Export.

NameValue
DEMANDBASEdemandbase
LINKEDINlinkedin
GOOGLEgoogle
ALLall

AdReportType.Campaign

Import from demandbase.models.Export.

NameValue
CAMPAIGN_SUMMARYcampaign_summary
CAMPAIGN_PERFORMANCE_ROLLUPcampaign_performance_rollup
CAMPAIGN_ACCOUNT_LIFETIMEcampaign_account_lifetime
CAMPAIGN_ACCOUNT_ROLLUPcampaign_account_rollup

AdReportType.Creative

Import from demandbase.models.Export.

NameValue
CREATIVE_LIFETIMEcreative_lifetime
CREATIVE_ROLLUPcreative_rollup

ImportJobState

Import from demandbase.models.Import.

NameValue
NEWnew
PROCESSINGprocessing
COMPLETEDcompleted
FAILEDfailed

ImportJobListAction

Import from demandbase.models.Import.

NameValue
REPLACEreplace
INSERTinsert
DELETEdelete
NOOPnoop

SubscriptionType

Import from demandbase.models.B2B.

NameValue
COMPANYcompany
COMPANY_NEWScompanyNews
DB_PERSONdbPerson
COMPANY_FAMILY_TREEcompanyFamilyTree

NewsCategory

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

B2B Models

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.

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.

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.

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.

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.

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:

CaseException
Missing DEMANDBASE_CLIENT_ID or DEMANDBASE_CLIENT_SECRETRuntimeError
Invalid pagination values such as page < 1ValueError
Invalid local file path for CSV uploadValueError
Unsupported CSV input typeValueError or TypeError, depending on method
Demandbase API error responseDemandBaseAPIError

Related Pages