1# This is an example where we fetch all clients and their outstanding balances and export
2# them to a csv file.
3# It demostrates pagination and extra included fields.
4
5# Each csv row will contain the outstanding balance for a particular currency for a client.
6# Thus clients with multiple currencies will have multiple rows.
7# Eg.
8# 123, Bob, 200, CAD
9# 123, Bob, 100, USD
10# 456, Alice, 300, CAD
11
12import csv
13
14from freshbooks import Client as FreshBooksClient
15from freshbooks import FreshBooksError, IncludesBuilder, PaginateBuilder
16
17FB_CLIENT_ID = "<your client id>"
18ACCESS_TOKEN = "<your access token>"
19ACCOUNT_ID = "<your account id>"
20PAGE_SIZE = 100
21
22freshBooksClient = FreshBooksClient(client_id=FB_CLIENT_ID, access_token=ACCESS_TOKEN)
23
24with open("clients.csv", 'w', newline='') as csvfile:
25 writer = csv.writer(csvfile)
26 writer.writerow(["Client Id", "Organization", "Outstanding Balance", "Currency"])
27
28 print("Fetching all clients...")
29 # Setup paginator to iterate through all clients
30 paginator = PaginateBuilder(1, PAGE_SIZE)
31 # Include outstanding balances in the response
32 includes = IncludesBuilder().include("outstanding_balance")
33
34 clients = None
35 while not clients or clients.pages.page < clients.pages.pages:
36 try:
37 # Get page of clients with outstanding balance included
38 clients = freshBooksClient.clients.list(ACCOUNT_ID, builders=[paginator, includes])
39 except FreshBooksError as e:
40 print(e)
41 print(e.status_code)
42 exit(1)
43
44 for client in clients:
45 print(f"Writing client {client.organization} ({client.id}) to csv...")
46 # Clients will have a outstanding_balance for each currency
47 if not client.outstanding_balance:
48 writer.writerow([client.id, client.organization])
49 else:
50 for outstanding_balance in client.outstanding_balance:
51 writer.writerow([
52 client.id,
53 client.organization,
54 outstanding_balance.amount.amount,
55 outstanding_balance.amount.code
56 ])
57
58 # Update paginator to get next page
59 paginator.page(clients.pages.page + 1)