How to transfer DataFrame records to HubSpot CRM system

I’m trying to upload information from a pandas DataFrame to my HubSpot CRM but running into issues. Here’s what I’ve tried so far:

from io import StringIO
import requests
import json

# Convert DataFrame to CSV format
csv_buffer = StringIO()
my_dataframe.to_csv(csv_buffer, index=False)
csv_buffer.seek(0)

# HubSpot credentials and settings
hubspot_key = 'your_api_key_here'
import_url = 'https://api.hubapi.com/crm/v3/imports'

# Request configuration
request_data = {
    'name': 'contact import',
    'files': [
        {
            'file_name': 'contacts.csv',
            'fileData': csv_buffer.read()
        }
    ]
}

request_headers = {
    'Content-Type': 'application/json',
    'Authorization': f'Bearer {hubspot_key}'
}

# Send the import request
api_response = requests.post(import_url, json=request_data, headers=request_headers)

if api_response.status_code == 200:
    print('Import completed successfully!')
else:
    print(f'Import failed - Status: {api_response.status_code}, Error: {api_response.text}')

I keep getting a 415 error (Unsupported Media Type). What’s the correct way to send DataFrame data to HubSpot’s import API?

The 415 error indicates a mismatch in content types. HubSpot’s import API requires multipart form-data for file uploads, but you are sending the CSV content as part of a JSON payload. I experienced a similar issue and found that restructuring the request is crucial. Remove the JSON wrapper and use the files parameter in requests.post to directly send the CSV file. Ensure that your DataFrame’s columns align with HubSpot’s field names to avoid import failures, and implement robust error handling for any validation issues that may arise.

yeah, they’re right about multipart. but also double-check your endpoint - /crm/v3/imports might not work with direct file uploads. try hubspot’s contact creation endpoint instead and loop through your dataframe rows. it’s slower but way more reliable.

your import api expects multipart/form-data, not json. you’re sending csv data as json - that won’t work. use the files param in requests.post instead of the json param: files={'file': ('contacts.csv', csv_buffer.getvalue(), 'text/csv')} and drop the content-type header.

Hit this same issue last month connecting our client database to HubSpot. HubSpot’s API wants file uploads as multipart encoding, not embedded JSON data. I fixed it by scrapping the JSON wrapper and sending the CSV directly as a file upload. Don’t forget to reset your StringIO buffer with seek(0) before reading - otherwise you’ll send empty data. Also, HubSpot’s super picky about column headers matching their property names exactly, so check your DataFrame columns against their docs first.