This website uses cookies and other technologies

This website uses cookies and other technologies to provide you with the best possible service. By clicking on OK or by simple use of the site, you accept these data processing. You will find more information under the privacy policy.

EN | FR

         



Terms of Service    Copyright

Python Code Samples

Sending late notices by email
#!/usr/bin/python # -*- coding: utf-8 -*- import requests, sys, os, re, logging, datetime, json, unicodedata, smtplib from os.path import basename from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate #set logging file and level logging.basicConfig(filename='/var/log/lateNotice.log',level=logging.DEBUG) #------------------------------------------------ # set variables for Wealthings Horizon Webservices #------------------------------------------------ url = 'https://www.wealthings.net' #user's token which will be used to login into Horizon token = 'ffffffff-ffff-ffff-ffff-ffffffffffff' mail_server = '10.10.10.10' organization_name = 'Acme SA' nb_days_for_late_notice_1 = 20 nb_days_for_late_notice_2 = 10 nb_days_for_late_notice_3 = 5 level_of_acceptance = 3 #default email address to send email to if the maximum nb of late notices have been reach or if missing email default_email_address = 'abc@def.com' send_from_email = 'abc@def.com' #------------------------------------------------ # common functions #------------------------------------------------ def getOverdueInvoices(organizationId): headers={'User-Agent' : 'Wyzio/1.0', 'weal-token' : token, 'cache-control' : 'no-cache', 'target-organization-id' : organizationId} webservice = url + '/api-v1/late-notice/client?sizePerPage=10000&sortingField=overdueAmount&direction=DESC&organizationId=' + str(organizationId) try: overdueInvoices = requests.get(webservice, headers=headers, timeout=10).json() except: overdueInvoices = [] return overdueInvoices def getInvoiceDetails(organizationId, invoiceNumber): headers={'User-Agent' : 'Wyzio/1.0', 'weal-token' : token, 'cache-control' : 'no-cache', 'target-organization-id' : organizationId} webservice = url + '/api-v1/sales-invoice?number=' + invoiceNumber try: invoiceDetails = requests.get(webservice, headers=headers, timeout=10).json() except: invoiceDetails = [] logging.warning(str(datetime.datetime.now()) + ' - Cannot get invoice details for invoice number ' + invoiceNumber +'!') return invoiceDetails def send_mail(send_from, send_to, subject, text, email, pdf_file, server="10.10.10.10"): msg = MIMEMultipart() msg['From'] = send_from msg['To'] = send_to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(email, "html", "utf-8")) with open(pdf_file, "rb") as fil: part = MIMEApplication(fil.read(), _subtype = 'pdf') part.add_header('content-disposition', 'attachment', filename=basename(pdf_file)) msg.attach(part) smtp = smtplib.SMTP(server, 587) smtp.set_debuglevel(1) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login("system@wealthings.email", "Syst3m_2017") smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() webservice = url + '/api-v1/organization?name=' + organization_name try: response = requests.get(webservice, headers=headers, timeout=10) except: logging.warning(str(datetime.datetime.now()) + ' - Cannot connect to server!') sys.exit('Cannot connect to server!') try: organizationId = response.json()[0]['id'] except: logging.warning(str(datetime.datetime.now()) + ' - Organization ' + organization_name + ' does not exist!') sys.exit('Organization ' + organization_name + ' does not exist!') headers={'User-Agent' : 'Wyzio/1.0', 'weal-token' : token, 'cache-control' : 'no-cache', 'target-organization-id' : organizationId} deadline1 = datetime.datetime.now() - datetime.timedelta(days=nb_days_for_late_notice_1) deadline2 = datetime.datetime.now() - datetime.timedelta(days=nb_days_for_late_notice_2) deadline3 = datetime.datetime.now() - datetime.timedelta(days=nb_days_for_late_notice_3) now = datetime.datetime.now() logging.warning(str(datetime.datetime.now()) + ' - Start of late notices check!') overdueInvoices = getOverdueInvoices(organizationId) logging.info(str(datetime.datetime.now()) + ' - ' + str(len(overdueInvoices)) +' late notices to look at!') for y in range(len(overdueInvoices)): unacceptable=0 donotsend=0 logging.info(str(datetime.datetime.now()) + ' - Should generate a late notice for invoice ' + str(overdueInvoices[y]['salesInvoiceNumber']) +'!') if overdueInvoices[y]['noticeGeneratedQuantity'] == 0: deadline = deadline1 lastNoticeDate = datetime.datetime.strptime(overdueInvoices[y]['overdueDate'][:10], '%Y-%m-%d') if level_of_acceptance == 1: unacceptable=1 elif overdueInvoices[y]['noticeGeneratedQuantity'] == 1: deadline = deadline2 lastNoticeDate = datetime.datetime.strptime(overdueInvoices[y]['lastNoticeGeneratedDate'][:10], '%Y-%m-%d') if level_of_acceptance == 2: unacceptable=1 elif overdueInvoices[y]['noticeGeneratedQuantity'] == 2: deadline = deadline3 lastNoticeDate = datetime.datetime.strptime(overdueInvoices[y]['lastNoticeGeneratedDate'][:10], '%Y-%m-%d') if level_of_acceptance == 3: unacceptable=1 elif overdueInvoices[y]['noticeGeneratedQuantity'] >= 3: donotsend = 1 else: deadline = deadline1 lastNoticeDate = datetime.datetime.strptime(overdueInvoices[y]['overdueDate'][:10], '%Y-%m-%d') if lastNoticeDate < deadline and donotsend == 0: invoiceNumber = overdueInvoices[y]['salesInvoiceNumber'] logging.info(str(datetime.datetime.now()) + ' - will generate a late notice for invoice ' + str(invoiceNumber) +'!') invoiceDetails = getInvoiceDetails(organizationId,invoiceNumber) try: logging.info(str(datetime.datetime.now()) + ' - Treating invoice ' + str(invoiceNumber) +'!') currency = invoiceDetails[0]['currency'].encode('utf-8').strip() totalAmount = str(invoiceDetails[0]['totalAmount']).encode('utf-8').strip() invoiceDate = str(invoiceDetails[0]['date'])[:10].encode('utf-8').strip() invoiceStatus = invoiceDetails[0]['status'].encode('utf-8').strip() webservice = url + '/api-v1/contact?id=' + str(overdueInvoices[y]['clientContactId']) try: client = requests.get(webservice, headers=headers, timeout=10).json() webservice = url + '/api-v1/contact/' + client[0]['contactType'] + '/' + str(client[0]['id']) clientDetails = requests.get(webservice, headers=headers, timeout=10).json() if not clientDetails['email']: send_to='NONE' else: send_to = clientDetails['email'] if not clientDetails['defaultLanguage']: lang='EN' else: lang = clientDetails['defaultLanguage'] if lang == 'FR': subject = 'Rappel concernant la facture ' + invoiceNumber text = 'Cher client,
Veuillez trouver en annexe un rappel concernant une facture impayée.' footer = 'Meilleures salutations,
Votre équipe Wealthings' invoiceName = 'Facture # :' dueDate = 'Date de facture: ' status = 'Statut: ' elif lang == 'DE': subject = 'Verspätete Benachrichtigung für Rechnung ' + invoiceNumber text = 'Sehr geehrter Kunde,
Bitte finden Sie im Anhang eine Verspätungsbescheid über eine unbezahlte Rechnung.' footer = 'Besondere Grüße,
Ihr Wealthings Team' invoiceName = 'Rechnung # :' dueDate = 'Rechnungsdatum: ' status = 'Status: ' elif lang == 'IT': subject = 'Avviso in ritardo per la fattura ' + invoiceNumber text = 'Gentile cliente,
Si prega di trovare in allegato un avviso tardivo relativo a una fattura non pagata.' footer = 'Ti migliori saluti,\nIl vostro team Wealthings' invoiceName = 'Fattura # :' dueDate = 'Data fattura: ' status = 'Stato: ' else: subject = 'Late Notice for invoice ' + invoiceNumber text = 'Dear customer,
Please find attached a late notice concerning an unpaid invoice.\n\nBest regards,\nYour Wealthings Team' footer = 'Best regards,
Your Wealthings Team' invoiceName = 'Invoice # :' dueDate = 'Invoice date: ' status = 'Status: ' except: logging.warning(str(datetime.datetime.now()) + ' - Cannot get client id ' + str(overdueInvoices[y]['clientContactId']) +'!') if unacceptable == 1 or send_to=='NONE': send_to='litigation@wealthings.com' # Remove remarks to enable the formatting of the email # email = '

' + subject + '

' + text + '

  • ' + invoiceName + ' ' + invoiceNumber + '

  • Total (' + currency + '): ' + totalAmount + '

  • ' + status + invoiceStatus + '

  • ' + dueDate + '' + invoiceDate + '

' + footer + '

Try a demo

' text = text.replace('
','\n\n') + '\n\nTotal (' + currency + '): ' + totalAmount + '\n' + status.replace('','') + invoiceStatus + '\n' + dueDate + invoiceDate +'\n\n' + footer.replace('
','\n') headers={'User-Agent' : 'Wyzio/1.0', 'weal-token' : token, 'cache-control' : 'no-cache', 'target-organization-id' : organizationId} now = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%dT%H:%M:%S.000Z') webservice = url + '/api-v1/generate-pdf?useLetterhead=true&overdueDate=%3C' + now + '&id=' + str(overdueInvoices[y]['id']) + '&organizationId=' + str(organizationId) + '&type=LATE_NOTICE&lateNoticePdfType=REMINDER&increaseLateNoticeNumber=true' try: response = requests.get(webservice, headers=headers, timeout=10) if response.status_code == 200: pdf_file = '/tmp/' + invoiceDetails[0]['number'] + '.pdf' with open(pdf_file, 'wb') as fd: fd.write(response.content) except: logging.warning(str(datetime.datetime.now()) + ' - Cannot generate late notice for invoice ' + invoiceNumber +'!') logging.warning(webservice) try: send_mail(send_from_email, send_to, subject, text, email, pdf_file) logging.warning(str(datetime.datetime.now()) + ' - The late notice for invoice ' + invoiceNumber +' was sent!') except: logging.warning(str(datetime.datetime.now()) + ' - The late notice for invoice ' + invoiceNumber +' could not be sent!') try: os.remove(pdf_file) except: pass except: pass logging.warning(str(datetime.datetime.now()) + ' - End of late notices check!')
Creating a new sales invoice
#!/usr/bin/python3 # -*- coding: utf-8 -*- import requests, sys, json, logging, datetime, unicodedata, calendar logging.basicConfig(filename='/var/log/generateInterestInvoices.log',level=logging.WARNING) def getNewDetails(journalEntries,startDateRange,endDateRange,delay=0): newInvoiceLineList = [] endRange = len(journalEntries) - 1 for d in range(len(journalEntries)): principal = float(journalEntries[d]['companyTotal']) if d == 0: if delay == 0: startDate = datetime.datetime.strptime(startDateRange[:10],'%Y-%m-%d') else: startDate = datetime.datetime.strptime(startDateRange[:10],'%Y-%m-%d') + datetime.timedelta(30) else: if delay == 0: startDate = datetime.datetime.strptime(journalEntries[d]['entryDate'][:10],'%Y-%m-%d') else: startDate = datetime.datetime.strptime(journalEntries[d]['entryDate'][:10],'%Y-%m-%d') + datetime.timedelta(30) if endRange == 0 or d == endRange: endDate = datetime.datetime.strptime(endDateRange[:10],'%Y-%m-%d') else: endDate = datetime.datetime.strptime(journalEntries[d+1]['entryDate'][:10],'%Y-%m-%d') if startDate == datetime.datetime.strptime(startDateRange[:10],'%Y-%m-%d') and endDate == datetime.datetime.strptime(endDateRange[:10],'%Y-%m-%d'): nbDays = 90 else: delta = endDate - startDate nbDays = delta.days if d == endRange: nbDays = nbDays + 1 if nbDays < 0: nbDays = 0 if nbDays > 90: nbDays = 90 if principal > 0 and nbDays > 0 and rate > 0: interest = round(principal * rate * nbDays / 365 * 20)/20 newInvoiceLineList.append('Int\u00e9r\u00eats de ' + str(rate * 100) + '% sur CHF ' + '{:,}'.format(principal) + ' du ' + datetime.datetime.strftime(startDate,'%d-%m-%Y') + ' au ' + datetime.datetime.strftime(endDate,'%d-%m-%Y') + ', soit ' + str(nbDays) + ' jours') newInvoiceLineList.append(interest) return newInvoiceLineList def newLineDetail(detail,account,tempId): new_detail = { "discount" : 0, "saleAccountId" : account, "vatRateId" : None, "totalPrice" : detail['interest'], "netUnitPrice" : 1, "vat" : None, "quantity" : detail['interest'], "departmentId" : None, "lineType" : "ARTICLE", "articleId" : 65475909, "totalNet" : detail['interest'], "id" : None, "description" : detail['description'], "allocationKey" : None, "appliedAllocationRules" : [], "tempId" : str(tempId) } return new_detail, detail['interest'] def newLineLayout(tempId): new_layout = { "children" : None, "parentId" : None, "position" : tempId + 3, "name" : None, "lineType" : "NO_ARTICLE", "tempId" : str(tempId), "salesInvoiceLineId" : str(tempId + 1), "collapsed" : False, "id" : str(tempId), "leaf" : False } return new_layout #set variables for Wealthings Horizon Webservices url = 'https://www.wealthings.net' token = ‘aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' headers={'User-Agent' : 'Wyzio/1.0', 'weal-token' : token, 'cache-control' : 'no-cache'} today=datetime.datetime.now() month=int(today.strftime('%m')) year=today.strftime('%Y') time= 'T00:00:00.000Z' overdueDate = today.replace(day=calendar.monthrange(today.year, today.month)[1]) overdueDate = overdueDate.strftime('%Y-%m-%d') + time rate = float(0.05) if month <= 3: startDateRange = str(int(year)-1) + '-10-01' + time endDateRange = str(int(year)-1) + '-12-31' + time dateRange = startDateRange + '..' + endDateRange elif month <= 6: startDateRange = year + '-01-01' + time endDateRange = year + '-03-31' + time dateRange = startDateRange + '..' + endDateRange elif month <=9: startDateRange = year + '-04-01' + time endDateRange = year + '-06-30' + time dateRange = startDateRange + '..' + endDateRange else: startDateRange = year + '-07-01' + time endDateRange = year + '-09-30' + time dateRange = startDateRange + '..' + endDateRange newInvoiceDate = endDateRange webservice = url + '/api-v1/organization?name=Wealthings Horizon SA' try: response = requests.get(webservice, headers=headers, timeout=10) except: logging.warning(str(datetime.datetime.now()) + ' - Cannot connect to server!') sys.exit('Cannot connect to server!') try: organization_id = response.json()[0]['id'] except: logging.warning(str(datetime.datetime.now()) + ' - Organization Wealthings Horizon SA does not exist!') sys.exit('Organization Wealthings Horizon SA does not exist!') organizationId = '999999999999999' headers = {'User-Agent' : 'Wyzio/1.0', 'weal-token' : token, 'cache-control' : 'no-cache', 'target-organization-id' : organizationId, 'Content-Type': 'application/json'} webservice = url + '/api-v1/contact?sizePerPage=10000&isCustomer=true' try: customerList = requests.get(webservice, headers=headers, timeout=10).json() except: logging.warning(str(datetime.datetime.now()) + ' - Cannot get list of customers!') webservice = url + '/api-v1/chart-accounts?accountNumber=44021' try: response = requests.get(webservice, headers=headers, timeout=10).json() accountingAccount = str(response[0]['id']) except: logging.warning(str(datetime.datetime.now()) + ' - Cannot get accounting account detail!') webservice = url + '/api-v1/chart-accounts?accountNumber=10204' try: response = requests.get(webservice, headers=headers, timeout=10).json() BLAccount = str(response[0]['id']) except: logging.warning(str(datetime.datetime.now()) + ' - Cannot get BL account detail!') webservice = url + '/api-v1/chart-accounts?accountNumber=10011' try: response = requests.get(webservice, headers=headers, timeout=10).json() paymentAccount = str(response[0]['id']) except: logging.warning(str(datetime.datetime.now()) + ' - Cannot get accounting account detail!') numCustomers = len(customerList) logging.info(str(datetime.datetime.now()) + ' - Treating ' + str(numCustomers) + ' customer(s)') newInvoiceList = [] for n in range(len(customerList)): webservice = url + '/api-v1/ledger?contactIds=' + str(customerList[n]['id']) + '&account=10200&entryDate=' + dateRange + '&pageNumber=1&isBalanceCarried=true&sortingField=entryDate&direction=ASC&sizePerPage=10000&isAppRequest=true' try: account10200 = requests.get(webservice, headers=headers, timeout=10).json() except: logging.warning(str(datetime.datetime.now()) + ' - Cannot get total of account 10200 for customer ' + customerList[n]['name'] + '!') webservice = url + '/api-v1/ledger?contactIds=' + str(customerList[n]['id']) + '&account=10201&entryDate=' + dateRange + '&pageNumber=1&isBalanceCarried=true&sortingField=entryDate&direction=ASC&sizePerPage=10000&isAppRequest=true' try: account10201 = requests.get(webservice, headers=headers, timeout=10).json() except: logging.warning(str(datetime.datetime.now()) + ' - Cannot get total of account 10201 for customer ' + customerList[n]['name'] + '!') webservice = url + '/api-v1/ledger?contactIds=' + str(customerList[n]['id']) + '&account=10204&entryDate=' + dateRange + '&pageNumber=1&isBalanceCarried=true&sortingField=entryDate&direction=ASC&sizePerPage=10000&isAppRequest=true' try: account10204 = requests.get(webservice, headers=headers, timeout=10).json() except: logging.warning(str(datetime.datetime.now()) + ' - Cannot get total of account 10201 for customer ' + customerList[n]['name'] + '!') totalDue = 0 if len(account10200) >= 1: totalDue = totalDue + account10200[len(account10200)-1]['companyTotal'] if len(account10201) >= 1: totalDue = totalDue + account10201[len(account10201)-1]['companyTotal'] if len(account10204) >= 1: totalDue = totalDue + account10204[len(account10204)-1]['companyTotal'] if totalDue > 0: newInvoiceLineList = [] newInvoiceLineList.extend(getNewDetails(account10200,startDateRange,endDateRange)) newInvoiceLineList.extend(getNewDetails(account10201,startDateRange,endDateRange)) newInvoiceLineList.extend(getNewDetails(account10204,startDateRange,endDateRange,1)) newDetail = ([{'description': k, 'interest': v} for k, v in [newInvoiceLineList[i: i + 2] for i in range(0, len(newInvoiceLineList), 2)]]) if len(newDetail) > 0: webservice = url + '/api-v1/contact/' + str(customerList[n]['id']) + '/client' try: contactDetail = requests.get(webservice, headers=headers, timeout=10).json() except: logging.warning(str(datetime.datetime.now()) + ' - Cannot get client detail!') address = None for a in range(len(contactDetail['addresses'])): if contactDetail['addresses'][a]['id'] == contactDetail['invoiceAddressId']: address = contactDetail['addresses'][a] if address == None: address = contactDetail['addresses'][0] address['id'] = None newInvoice = [{ "id" : None, "clientAddressId": contactDetail['invoiceAddressId'], "clientId" : customerList[n]['id'], "comments" : None, "currencyId" : 1214, "date" : newInvoiceDate, "timesheetInfoItems":[], "excludedFromVat" : False, "receivableAccountId " : BLAccount, "vatTypeCodeId" : None, "clientName" : customerList[n]['name'], "description" : 'Int\u00e9r\u00eats au ' + datetime.datetime.strptime(endDateRange[:10],'%Y-%m-%d').strftime('%d-%m-%Y'), "address": address, "invoiceLines" : [], "invoiceLinesLayout" : [] , "number" : None, "reference" : None, "shipments": [], "payments" : [{ "bankCharges":0, "paidAmount":0, "requestedAmount" : 0, "overdueDate" : overdueDate, "receivableByAccountId" : paymentAccount, "id" : None, "lossOnDebtors" : 0, "requestedDate" : overdueDate, "valueDate" : None }], "warnings": None }] totalAmount = 0 index = 0 newInvoiceLine = [] newLayout = [] for d in range(len(newDetail)): index = index - 1 line, total = newLineDetail(newDetail[d],accountingAccount,index) newInvoiceLine.append(line) totalAmount = totalAmount + float(total) index = index - 1 newLayout.append(newLineLayout(index)) if totalAmount > 1: newInvoice[0]['invoiceLines'] = newInvoiceLine newInvoice[0]['invoiceLinesLayout'] = newLayout requested_amount = '{:.2f}'.format(totalAmount) newInvoice[0]['payments'][0]['requestedAmount'] = requested_amount webservice = url + '/api-v1/sales-invoice/batch' try: response = requests.post(webservice, data=json.dumps(newInvoice), headers=headers).json() if response['items'][0]['errorCode']['errorCode'] == 'NO_ERROR': logging.debug(str(datetime.datetime.now()) + ' - New interest invoice for ' + customerList[n]['name'] + ' was successfully created!') else: logging.warning(str(datetime.datetime.now()) + ' - Could not insert interest invoice for ' + customerList[n]['name'] + '!') except: logging.warning(str(datetime.datetime.now()) + ' - Could not insert interest invoice for ' + customerList[n]['name'] + '!')
Importing contacts from Excel worksheet
Excel sample file
0
#!/usr/bin/python # -*- coding: utf-8 -*- import urllib, requests, sys, logging, datetime, json, unicodedata from xlrd import open_workbook class Contact(object): def __init__(self, contact_type, default_language, company_name, last_name, first_name, phone, fax, mobile, email, web_site, address_line1, address_line2, city_name, post_code, region_code, state_name, country_code, country_id, to_the_attention_of, currency_id, payment_terms, credit_limit, client_discount_rate): self.contact_type = contact_type self.default_language = default_language self.company_name = company_name self.last_name = last_name self.first_name = first_name self.phone = phone self.fax = fax self.mobile = mobile self.email = email self.web_site = web_site self.address_line1 = address_line1 self.address_line2 = address_line2 self.city_name = city_name self.post_code = post_code self.region_code = region_code self.state_name = state_name self.country_code = country_code self.country_id = country_id self.to_the_attention_of = to_the_attention_of self.currency_id = currency_id self.payment_terms = payment_terms self.credit_limit = credit_limit self.client_discount_rate = client_discount_rate def __str__(self): return("Contact object:\n" " contactType = {0}\n" " defaultLanguage = {1}\n" " companyName = {2}\n" " lastName = {3}\n" " firstName = {4}\n" " Phone = {5}\n" " Fax = {6}\n" " Mobile = {7}\n" " Email = {8}\n" " webSite = {9}\n" " addressLine1 = {10}\n" " addressLine2 = {11}\n" " cityName = {12}\n" " postCode = {13}\n" " regionCode = {14}\n" " stateName = {15}\n" " countryCode = {16}\n" " countryId = {17}\n" " toTheAttentionOf = {18}\n" " currencyId = {19}\n" " paymentTerms = {20}\n" " creditLimit = {21}\n" " clientDiscountRate = {22}\n" .format(self.contact_type, self.default_language, self.company_name, self.last_name, self.first_name, self.phone, self.fax, self.mobile, self.email, self.web_site, self.address_line1, self.address_line2, self.city_name, self.post_code, self.region_code, self.state_name, self.country_code, self.country_id, self.to_the_attention_of, self.currency_id, self.payment_terms, self.credit_limit, self.client_discount_rate)) wb = open_workbook('Addresses_Test.xlsx') for sheet in wb.sheets(): number_of_rows = sheet.nrows number_of_columns = sheet.ncols items = [] rows = [] for row in range(1, number_of_rows): values = [] for col in range(number_of_columns): value = (sheet.cell(row,col).value) try: value = str(int(value)) except ValueError: pass finally: values.append(value) item = Contact(*values) items.append(item) organizationId = '999999999999999' url = 'https://www.wealthings.net' token = ‘aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' headers = {'User-Agent' : 'Wyzio/1.0', 'weal-token' : token, 'cache-control' : 'no-cache', 'target-organization-id' : organizationId, 'Content-Type': 'application/json'} webservice = url + '/api-v1/contact/batch' for item in items: if item.contact_type == 'ORGANIZATION': newContact = [{ "contactId": -1, "organizationId": organizationId, "warnings": {}, "contactType": item.contact_type, "defaultLanguage": item.default_language, "name": item.company_name, "type": "ContactDetailsOrganization", "webSite": item.web_site, "mobile": item.mobile, "phone": item.phone, "archived": False, "fax": item.fax, "email": item.email, "isCustomer": True, "isVendor": False, "addresses": [{ item.region_code, "id":None, "name":"Main", "line1": item.address_line1, "line2": item.address_line2, "postCode": item.post_code, "city": item.city_name, "countryCode2": item.country_code, "countryId": item.country_id, "toTheAttentionOf": item.to_the_attention_of, "position": 0 }], "banks": [], "supplier": { "paymentTerms": None }, "client": { "orderAddressId": None, "invoiceAddressId": None, "paymentTerms": None, "lateNoticeMargin": None, "creditLimit": None, "clientDiscountRate": None, "orderAddressName": "Main", "invoiceAddressName":"Main" }, "communications": [] }] else: "contactId": -1, "organizationId": organizationId, "warnings": {}, "contactType": item.contact_type, "defaultLanguage": item.default_language, "firstName": item.first_name, "lastName": item.last_name, "middleName": None, "nationalityCountryId": None, "gender": None, "birthday": None, "permissionsTree":[], "isImpersonateOthers": False, "isActive": True, "staff": { "contactId": -1, "id": None, "avsNumber": None, "payrollCurrencyId": None, "employmentStartDate": None, "employmentEndDate": None, "employeeDocumentType": None, "documentNumber": None, "documentExpiryDate": None, "contractType": None, "maritalType": None, "maritalDate": None, "isSpouseWorking": None, "familyMembers": [], "timesheetPricingLines":[], "staffPayslips":[], "workPermit": None, "permitExpiryDate": None }, "type":"ContactDetailsPerson", "webSite": item.web_site, "mobile": item.mobile, "phone": item.phone, "archived": False, "fax": item.fax, "email": item.email, "isCustomer": True, "isVendor": False, "addresses": [{ item.region_code, "id":None, "name":"Main", "line1": item.address_line1, "line2": item.address_line2, "postCode": item.post_code, "city": item.city_name, "countryCode2": item.country_code, "countryId": item.country_id, "toTheAttentionOf": item.to_the_attention_of, "position": 0 }], "banks": [], "supplier": { "paymentTerms": None }, "client": { "orderAddressId": None, "invoiceAddressId": None, "paymentTerms": None, "lateNoticeMargin": None, "creditLimit": None, "clientDiscountRate": None, "orderAddressName": "Main", "invoiceAddressName":"Main" }, "communications": [] }] try: response = requests.post(webservice, data=json.dump(newContact), headers=headers).json() if response['items'][0]['errorCode']['errorCode'] == 'NO_ERROR': newContactId = response['items'][0]['freshRow']['id'] else: print 'Could not insert new contact!' except: raise

Try a demo