Welcome to freshbooks-sdk’s documentation!

Configuring The API Client

You can create an instance of the API client in one of two ways:

  • By providing your application’s OAuth2 client_id and client_secret and following through the auth flow, which when complete will return an access token

  • Or if you already have a valid access token, you can instantiate the client directly using that token, however token refresh flows will not function without the application id and secret.

from freshbooks import Client

freshBooksClient = Client(
    client_id=<your application id>,
    client_secret=<your application secret>,
    redirect_uri=<your redirect uri>
)

and then proceed with the auth flow (see below).

Or

from freshbooks import Client

freshBooksClient = Client(
    client_id=<your application id>,
    access_token=<a valid token>
)

Authorization Flow

This is a brief summary of the OAuth2 authorization flow and the methods in the FreshBooks API Client around them. See the FreshBooks API - Authentication documentation.

First, instantiate your Client with client_id, client_secret, and redirect_uri as above.

To get an access token, the user must first authorize your application. This can be done by sending the user to the FreshBooks authorization page. Once the user has clicked accept there, they will be redirected to your redirect_uri with an access grant code. The authorization URL can be obtained by calling freshBooksClient.get_auth_request_url(). This method also accepts a list of scopes that you wish the user to authorize your application for.

auth_url = freshBooksClient.get_auth_request_url(['user:profile:read', 'user:clients:read'])

Once the user has been redirected to your redirect_uri and you have obtained the access grant code, you can exchange that code for a valid access token.

auth_results = freshBooksClient.get_access_token(access_grant_code)

This call both sets the access_token, refresh_token, and access_token_expires_at fields on you Client instance, and returns those values.

>>> auth_results.access_token
<some token>

>>> auth_results.refresh_token
<some refresh token>

>>> auth_results.access_token_expires_at
<datetime object>

When the token expires, it can be refreshed with the refresh_token value in the Client:

>>> auth_results = freshBooksClient.refresh_access_token()
>>> auth_results.access_token
<a new token>

or you can pass the refresh token yourself:

>>> auth_results = freshBooksClient.refresh_access_token(stored_refresh_token)
>>> auth_results.access_token
<a new token>

Current User

FreshBooks users are uniquely identified by their email across our entire product. One user may act on several Businesses in different ways, and our Identity model is how we keep track of it. Each unique user has an Identity, and each Identity has Business Memberships which define the permissions they have.

See FreshBooks API - Business, Roles, and Identity and FreshBooks API - The Identity Model.

The current user can be accessed by:

>>> current_user = freshBooksClient.current_user()
>>> current_user.email
<some email>

>>> current_user.business_memberships
<list of businesses>

Making API Calls

Each resource in the client provides calls for get, list, create, update and delete calls. Please note that some API resources are scoped to a FreshBooks account_id while others are scoped to a business_id or a business_uuid. In general these fall along the lines of account_id for older accounting resources, business_id for projects/time tracking, and business_uuid for all newer resources, but that is not precise.

client = freshBooksClient.clients.get(account_id, client_user_id)
project = freshBooksClient.projects.get(business_id, project_id)
account = freshBooksClient.ledger_accounts.get(business_uuid, ledger_account_uuid)

Get and List

API calls which return a single resource return a Result object with the returned data accessible via attributes. The raw json-parsed dictionary can also be accessed via the data attribute.

client = freshBooksClient.clients.get(account_id, client_user_id)

assert client.organization == "FreshBooks"
assert client.userid == client_user_id

assert client.data["organization"] == "FreshBooks"
assert client.data["userid"] == client_user_id

vis_state returns an Enum. See FreshBooks API - Active and Deleted Objects for details.

from freshbooks import VisState

assert client.vis_state == VisState.ACTIVE
assert client.vis_state == 0
assert client.data['vis_state'] == VisState.ACTIVE
assert client.data['vis_state'] == 0

API calls which return a list of resources return a ListResult object. The resources in the list can be accessed by index and iterated over. Similarly, the raw dictionary can be accessed via the data attribute.

clients = freshBooksClient.clients.list(account_id)

assert clients[0].organization == "FreshBooks"

assert clients.data["clients"][0]["organization"] == "FreshBooks"

for client in clients:
    assert client.organization == "FreshBooks"
    assert client.data["organization"] == "FreshBooks"

Create, Update, and Delete

API calls to create and update take a dictionary of the resource data. A successful call will return a Result object as if a get call.

Create:

payload = {"email": "john.doe@abcorp.com"}
new_client = FreshBooksClient.clients.create(account_id, payload)

client_id = new_client.userid

Update:

payload = {"email": "john.doe@abcorp.ca"}
client = freshBooksClient.clients.update(account_id, client_id, payload)

assert client.email == "john.doe@abcorp.ca"

Delete:

client = freshBooksClient.clients.delete(account_id, client_id)

assert client.vis_state == VisState.DELETED

Error Handling

Calls made to the FreshBooks API with a non-2xx response are wrapped in a FreshBooksError exception. This exception class contains the error message, HTTP response code, FreshBooks-specific error number if one exists, and the HTTP response body.

Example:

from freshbooks import FreshBooksError

try:
    client = freshBooksClient.clients.get(account_id, client_id)
except FreshBooksError as e:
    assert str(e) == "Client not found."
    assert e.status_code == 404
    assert e.error_code == 1012
    assert e.error_details == [{
        "errno": 1012,
        "field": "userid",
        "message": "Client not found.",
        "object": "client",
        "value": "12345"
    }]
    assert e.raw_response ==  ("{'response': {'errors': [{'errno': 1012, "
                               "'field': 'userid', 'message': 'Client not found.', "
                               "'object': 'client', 'value': '134'}]}}")

Not all resources have full CRUD methods available. For example expense categories have list and get calls, but are not deletable. If you attempt to call a method that does not exist, the SDK will raise a FreshBooksNotImplementedError exception, but this is not something you will likely have to account for outside of development.

Pagination, Filters, and Includes, Sorting

list calls take a list of builder objects that can be used to paginate, filter, and include optional data in the response. See FreshBooks API - Parameters documentation.

Pagination

Pagination results are included in list responses in the pages attribute:

>>> clients = freshBooksClient.clients.list(account_id)
>>> clients.pages
PageResult(page=1, pages=1, per_page=30, total=6)

>>> clients.pages.total
6

To make a paginated call, first create a PaginateBuilder object that can be passed into the list method.

>>> from freshbooks import PaginateBuilder

>>> paginator = PaginateBuilder(2, 4)
>>> paginator
PaginateBuilder(page=2, per_page=4)

>>> clients = freshBooksClient.clients.list(account_id, builders=[paginator])
>>> clients.pages
PageResult(page=2, pages=3, per_page=4, total=9)

PaginateBuilder has methods page and per_page to return or set the values. When setting the values the calls can be chained.

>>> paginator = PaginateBuilder(1, 3)
>>> paginator
PaginateBuilder(page=1, per_page=3)

>>> paginator.page()
1

>>> paginator.page(2).per_page(4)
>>> paginator
PaginateBuilder(page=2, per_page=4)

ListResults can be combined, allowing your to use pagination to get all the results of a resource.

paginator = PaginateBuilder(1, 100)
clients = freshBooksClient.clients.list(self.account_id, builders=[paginator])
while clients.pages.page < clients.pages.pages:
    paginator.page(clients.pages.page + 1)
    new_clients = freshBooksClient.clients.list(self.account_id, builders=[paginator])
    clients = clients + new_clients

Filters

To filter which results are return by list method calls, construct a FilterBuilder and pass that in the list of builders to the list method.

>>> from freshbooks import FilterBuilder

>>> filter = FilterBuilder()
>>> filter.equals("userid", 123)

>>> clients = freshBooksClient.clients.list(account_id, builders=[filter])

Filters can be built with the methods: equals, in_list, like, between, and boolean, which can be chained together.

Please see FreshBooks API - Active and Deleted Objects for details on filtering active, archived, and deleted resources.

>>> f = FilterBuilder()
>>> f.in_list("clientids", [123, 456])
FilterBuilder(&search[clientids][]=123&search[clientids][]=456)

>>> f = FilterBuilder()
>>> f.like("email_like", "@freshbooks.com")
FilterBuilder(&search[email_like]=@freshbooks.com)

>>> f = FilterBuilder()
>>> f.between("amount", 1, 10)
FilterBuilder(&search[amount_min]=1&search[amount_max]=10)

>>> f = FilterBuilder()
>>> f.between("amount", min=15)  # For just minimum
FilterBuilder(&search[amount_min]=15)

>>> f = FilterBuilder()
>>> f.between("amount_min", 15)  # Alternatively
FilterBuilder(&search[amount_min]=15)

>>> f = FilterBuilder()
>>> f.between("start_date", date.today())
FilterBuilder(&search[start_date]=2020-11-21)

>>> f = FilterBuilder()
>>> f.boolean("complete", False) # Boolean filters are mostly used on Project-like resources
FilterBuilder(&complete=False)

>>> last_week = date.today() - timedelta(days=7)
>>> f = FilterBuilder()
>>> f.equals("vis_state", VisState.ACTIVE).between("updated", last_week, date.today()) # Chaining filters
FilterBuilder(&search[vis_state]=0&search[updated_min]=2020-11-14&search[updated_max]=2020-11-21)

Includes

To include additional relationships, sub-resources, or data in a response an IncludesBuilder can be constructed.

>>> from freshbooks import IncludesBuilder

>>> includes = IncludesBuilder()
>>> includes.include("outstanding_balance")
IncludesBuilder(&include[]=outstanding_balance)

Which can then be passed into list or get calls:

>>> clients = freshBooksClient.clients.list(account_id, builders=[includes])
>>> clients[0].outstanding_balance
[{'amount': {'amount': '100.00', 'code': 'USD'}}]

>>> client = freshBooksClient.clients.get(account_id, client_id, includes=includes)
>>> client.outstanding_balance
[{'amount': {'amount': '100.00', 'code': 'USD'}}]

Includes can also be passed into create and update calls to include the data in the response of the updated resource:

>>> payload = {"email": "john.doe@abcorp.com"}
>>> new_client = FreshBooksClient.clients.create(account_id, payload, includes=includes)
>>> new_client.outstanding_balance
[]  # New client has no balance

Sorting

To sort the results of a list call by supported fields (see the documentation for that resource) a SortBuilder can be used.

>>> from freshbooks import SortBuilder

>>> sort = SortBuilder()
>>> sort.ascending("invoice_date")
SortBuilder(&sort=invoice_date_asc)

to sort by the invoice date in ascending order, or:

>>> from freshbooks import SortBuilder

>>> sort = SortBuilder()
>>> sort.descending("invoice_date")
SortBuilder(&sort=invoice_date_desc)

for descending order.

invoices = freshBooksClient.invoices.list(account_id, builders=[sort])

Dates and Times

For historical reasons, some resources in the FreshBooks API (mostly accounting-releated) return date/times in “US/Eastern” timezone. Some effort is taken to return datetime objects as zone-aware and normalized to UTC. In these cases, the raw response string will differ from the attribute. For example:

from datetime import datetime, timezone

assert client.data["updated"] == "2021-04-16 10:31:59"  # Zone-naive string in "US/Eastern"
assert client.updated.isoformat() == '2021-04-16T14:31:59+00:00'  # Zone-aware datetime in UTC
assert client.updated == datetime(year=2021, month=4, day=16, hour=14, minute=31, second=59, tzinfo=timezone.utc)

Changelog

# FreshBooks Python SDK Changelog

## Unreleased

- Add Ledger Accounts resource
- Properly handle some project error messages
- `access_token_expires_at` is now  set as UTC

## 1.2.1

- Improved error messages on authorization failures

## 1.2.0

- Add includes parameter to project-like `get` calls
- Allow API version header configuration
- Handle new API version accounting errors

## 1.1.0

- Added upload attachment and image resources
- Fixed `invoice_payment_options` create call (was not creating)
- Updated webhook event error handling for new FreshBooks API error strcuture
- Added list sort builder

## 1.0.1

- Fixed Identity "business_memberships" attribute to return Result objects

## 1.0.0

- Drop support for python 3.6 as it is end of life
- Added Bill Payments resource
- Added Service Rates resource
- Added Online Payments resource
- Additional configuration validation

## 0.8.0

- Added Bills and Bill Vendors APIs
- Allow includes for create, updates of accounting resources

## 0.7.1

- Fix equals filters for project-like resource

## 0.7.0

- (**BREAKING**) `client.current_user` is now a method, not a property for more consistency.
- Joining of ListResult objects with `__add__` to aid pagination of results, with example in README.

## 0.6.1

- Update documentation
- Minor test fixture updates
- Mark as Beta in pypi

## 0.6.0

- Date strings in Result objects now return as date and datetime objects. datetimes are zone-aware and normalized to UTC.

Examples and Sample Code

If you checkout the project, these files should be runnable locally after installing.

pip install .

python ./examples/create_invoice.py

Be sure to update the example files with your own credentials in place of <your account id> and <your access token>.

Authorization Flow

 1# This is an example where we run through the OAuth flow,
 2# select a business, and display a client from that business.
 3
 4from types import SimpleNamespace
 5from freshbooks import Client as FreshBooksClient
 6
 7FB_CLIENT_ID = "<your client id>"
 8SECRET = "<your client secret>"
 9REDIRECT_URI = "<your redirect uri>"
10
11freshBooksClient = FreshBooksClient(
12    client_id=FB_CLIENT_ID,
13    client_secret=SECRET,
14    redirect_uri=REDIRECT_URI
15)
16
17authorization_url = freshBooksClient.get_auth_request_url(
18    scopes=['user:profile:read', 'user:clients:read']
19)
20print(f"Go to this URL to authorize: {authorization_url}")
21
22# Going to that URL will prompt the user to log into FreshBooks and authorize the application.
23# Once authorized, FreshBooks will redirect the user to your `redirect_uri` with the authorization
24# code will be a parameter in the URL.
25auth_code = input("Enter the code you get after authorization: ")
26
27# This will exchange the authorization code for an access token
28token_response = freshBooksClient.get_access_token(auth_code)
29print(f"This is the access token the client is now configurated with: {token_response.access_token}")
30print(f"It is good until {token_response.access_token_expires_at}")
31print()
32
33# Get the current user's identity
34identity = freshBooksClient.current_user()
35businesses = []
36
37# Display all of the businesses the user has access to
38for num, business_membership in enumerate(identity.business_memberships, start=1):
39    business = business_membership.business
40    businesses.append(
41        SimpleNamespace(name=business.name, business_id=business.id, account_id=business.account_id)
42    )
43    print(f"{num}: {business.name}")
44business_index = int(input("Which business do you want to use? ")) - 1
45print()
46
47business_id = businesses[business_index].business_id  # Used for project-related calls
48account_id = businesses[business_index].account_id  # Used for accounting-related calls
49
50# Get a client for the business to show successful access
51client = freshBooksClient.clients.list(account_id)[0]
52print(f"'{client.organization}' is a client of {businesses[business_index].name}")

Create Invoice

 1# This is an example where we create a new client and an invoice for them.
 2
 3from datetime import date
 4from freshbooks import Client as FreshBooksClient
 5from freshbooks import FreshBooksError
 6
 7FB_CLIENT_ID = "<your client id>"
 8ACCESS_TOKEN = "<your access token>"
 9ACCOUNT_ID = "<your account id>"
10
11freshBooksClient = FreshBooksClient(client_id=FB_CLIENT_ID, access_token=ACCESS_TOKEN)
12
13# Create the client
14print("Creating client...")
15try:
16    client_data = {"organization": "Python SDK Test Client"}
17    client = freshBooksClient.clients.create(ACCOUNT_ID, client_data)
18except FreshBooksError as e:
19    print(e)
20    print(e.status_code)
21    exit(1)
22
23print(f"Created client {client.id}")
24
25# Create the invoice
26line1 = {
27    "name": "Fancy Dishes",
28    "description": "They're pretty swanky",
29    "qty": 6,
30    "unit_cost": {
31        "amount": "27.00",
32        "code": "CAD"
33    }
34}
35line2 = {
36    "name": "Regular Glasses",
37    "description": 'They look "just ok"',
38    "qty": 8,
39    "unit_cost": {
40        "amount": "5.95",
41        "code": "CAD"
42    }
43}
44invoice_data = {
45    "customerid": client.id,
46    "create_date": date.today().isoformat(),
47    "due_offset_days": 5,  # due 5 days after create_date
48    "lines": [line1, line2],
49}
50print("Creating invoice...")
51try:
52    invoice = freshBooksClient.invoices.create(ACCOUNT_ID, invoice_data)
53except FreshBooksError as e:
54    print(e)
55    print(e.status_code)
56    exit(1)
57
58print(f"Created invoice {invoice.invoice_number} (Id: {invoice.id})")
59print(f"Invoice total is {invoice.amount.amount} {invoice.amount.code}")
60
61# Invoices are created in draft status, so we need to mark it as sent
62print("Marking invoice as sent...")
63invoice_data = {
64    "action_mark_as_sent": True
65}
66try:
67    invoice = freshBooksClient.invoices.update(ACCOUNT_ID, invoice.id, invoice_data)
68except FreshBooksError as e:
69    print(e)
70    print(e.status_code)
71    exit(1)

Create Invoice - Extended

  1# This is an example where we create a customized invoice with logos and attachments,
  2# and a payment gateway, then send it by email to your address.
  3
  4from datetime import date
  5from freshbooks import Client as FreshBooksClient
  6from freshbooks import FreshBooksError
  7
  8FB_CLIENT_ID = "<your client id>"
  9ACCESS_TOKEN = "<your access token>"
 10ACCOUNT_ID = "<your account id>"
 11DESTINATION_EMAIL = "<your email>"  # Don't use the same email as the account owner.
 12
 13freshBooksClient = FreshBooksClient(client_id=FB_CLIENT_ID, access_token=ACCESS_TOKEN)
 14
 15# Create the client
 16print("Creating client...")
 17try:
 18    client_data = {
 19        "email": DESTINATION_EMAIL,
 20        "organization": "Python SDK Test Client"
 21    }
 22    client = freshBooksClient.clients.create(ACCOUNT_ID, client_data)
 23except FreshBooksError as e:
 24    print(e)
 25    print(e.status_code)
 26    exit(1)
 27
 28print(f"Created client {client.id}")
 29
 30# Upload a logo and attachment with examples of file_path and file_stream.
 31try:
 32    print("Uploading invoice logo")
 33    # We upload a file by providing the path to the file.
 34    logo = freshBooksClient.images.upload(ACCOUNT_ID, file_path="./assets/sample_logo.png")
 35
 36    print("Uploading invoice attachment")
 37    # We upload a file by opening it and providing the file stream.
 38    attachment = freshBooksClient.attachments.upload(
 39        ACCOUNT_ID, file_stream=open("./assets/sample_attachment.pdf", "rb")
 40    )
 41except FreshBooksError as e:
 42    print(e)
 43    print(e.status_code)
 44    exit(1)
 45
 46# Create the invoice with taxed line items, a custom colour and logo, and an attachment.
 47
 48# Taxed line items
 49line1 = {
 50    "name": "A Taxed Item",
 51    "description": "These things are taxed",
 52    "qty": 2,
 53    "taxAmount1": "13",
 54    "taxName1": "HST",
 55    "unit_cost": {
 56        "amount": "27.00",
 57        "code": "CAD"
 58    }
 59}
 60line2 = {
 61    "name": "Another Taxed ItemRegular Glasses",
 62    "description": "With a different tax",
 63    "qty": 4,
 64    "taxAmount1": "5",
 65    "taxName1": "GST",
 66    "unit_cost": {
 67        "amount": "6.95",
 68        "code": "CAD"
 69    }
 70}
 71
 72presentation = {
 73    "theme_primary_color": "#1fab13",
 74    "theme_layout": "simple",
 75    "theme_font_name": "modern",
 76    "image_logo_src": f"/uploads/images/{logo.jwt}"  # The logo uplad response contains a jwt token
 77}
 78
 79invoice_data = {
 80    "customerid": client.id,
 81    "create_date": date.today().isoformat(),
 82    "due_offset_days": 5,
 83    "lines": [line1, line2],
 84    "attachments": [
 85        {
 86            "jwt": attachment.jwt,
 87            "media_type": attachment.media_type
 88        }
 89    ],
 90    "presentation": presentation
 91}
 92print("Creating invoice...")
 93try:
 94    invoice = freshBooksClient.invoices.create(ACCOUNT_ID, invoice_data)
 95except FreshBooksError as e:
 96    print(e)
 97    print(e.status_code)
 98    exit(1)
 99
100print(f"Created invoice {invoice.invoice_number} (Id: {invoice.id})")
101print(f"Invoice total is {invoice.amount.amount} {invoice.amount.code}")
102
103# Once the invoice is created, a payment option can be added to it.
104print("Adding fbpay payment option...")
105payment_option_data = {
106    "gateway_name": "fbpay",
107    "entity_id": invoice.id,
108    "entity_type": "invoice",
109    "has_credit_card": True
110}
111try:
112    freshBooksClient.invoice_payment_options.create(ACCOUNT_ID, invoice.id, payment_option_data)
113except FreshBooksError as e:
114    print(e)
115    print(e.status_code)
116    exit(1)
117
118# Invoices are created in draft status, so we need to send it.
119print("Sending the invoice by email...")
120invoice_data = {
121    "action_email": True,
122    "email_recipients": [destination_email],
123    "email_include_pdf": False,
124    "invoice_customized_email": {
125        "subject": "Test Styled Invoice",
126        "body": "This was an example",
127    }
128}
129try:
130    invoice = freshBooksClient.invoices.update(ACCOUNT_ID, invoice.id, invoice_data)
131except FreshBooksError as e:
132    print(e)
133    print(e.status_code)
134    exit(1)

Export Clients Outstanding Balance

 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)

Client

class freshbooks.client.Client(client_id, client_secret=None, redirect_uri=None, access_token=None, refresh_token=None, user_agent=None, api_version=None, timeout=30, auto_retry=True)

Bases: object

property attachments: UploadsResource

FreshBooks attachment upload resource with call to upload, get

property bill_payments: AccountingResource

FreshBooks bill_payments resource with calls to get, list, create, update, delete

property bill_vendors: AccountingResource

FreshBooks bill_vendors resource with calls to get, list, create, update, delete

property bills: AccountingResource

FreshBooks bills resource with calls to get, list, create, update, delete

property callbacks: EventsResource

FreshBooks callbacks (webhook callbacks) resource with calls to get, list, create, update, delete, resend_verification, verify

property clients: AccountingResource

FreshBooks clients resource with calls to get, list, create, update, delete

property credit_notes: AccountingResource

FreshBooks credit_notes resource with calls to get, list, create, update, delete

current_user()

The identity details of the currently authenticated user.

See FreshBooks API - Business, Roles, and Identity

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Identity

property estimates: AccountingResource

FreshBooks estimates resource with calls to get, list, create, update, delete

property expenses: AccountingResource

FreshBooks expenses resource with calls to get, list, create, update, delete

property expenses_categories: AccountingResource

FreshBooks expenses categories resource with calls to get and list

property gateways: AccountingResource

FreshBooks gateways resource with calls to list, delete

get_access_token(code)

Makes a call to the FreshBooks token URL to get an access_token.

This requires the access_grant code obtained after the user is redirected by the authorization step. See freshbooks.client.Client.get_auth_request_url.

This call sets the access_token, refresh_token, and access_token_expires_at attributes on the Client instance and also returns those values in an object.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~types.SimpleNamespace

Parameters:

code – access_grant code from the authorization redirect

Returns:

Simple namespace containing access_token, refresh_token, and access_token_expires_at

Raises:
get_auth_request_url(scopes=None)

Returns the url that a client needs to request an oauth grant from the server.

To get an oauth access token, send your user to this URL. The user will be prompted to log in to FreshBooks, after which they will be redirected to the redirect_uri set on the client with the access grant as a parameter. That grant can then be used to fetch an access token by calling get_access_token.

Note: The redirect_uri must be one of the URLs your application is registered for.

If scopes are not specified, then the access token will be given the default scopes your application is registered for.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``str

Parameters:

scopes – List of scopes if your want an access token with only a subset of your registered scopes

Returns:

The URL for the authorization request

Raises:

FreshBooksClientConfigError – If redirect_uri is not set on the client instance.

property images: UploadsResource

FreshBooks image upload resource with call to upload, get

property invoice_payment_options: PaymentsResource

FreshBooks default payment options resource with calls to defaults, get, create

property invoice_profiles: AccountingResource

FreshBooks invoice_profiles resource with calls to get, list, create, update, delete

property invoices: AccountingResource

FreshBooks invoices resource with calls to get, list, create, update, delete

property items: AccountingResource

FreshBooks items resource with calls to get, list, create, update, delete

property ledger_accounts: AccountingBusinessResource

FreshBooks accounts resource with calls to get, list

property other_income: AccountingResource

FreshBooks other_incomes resource with calls to get, list, create, update, delete

property payments: AccountingResource

FreshBooks payments resource with calls to get, list, create, update, delete

property projects: ProjectsResource

FreshBooks projects resource with calls to get, list, create, update, delete

refresh_access_token(refresh_token=None)

Makes a call to the FreshBooks token URL to refresh an access_token.

If refresh_token is provided, it will call to refresh it, otherwise it will use the refresh_token on the Client instance.

This call sets the access_token, refresh_token, and access_token_expires_at attributes on the Client instance to the new values from the refresh call, and also returns those values in an object.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~types.SimpleNamespace

Parameters:

refresh_token – (Optional) refresh_token from initial get_access_token call

Returns:

Simple namespace containing access_token, refresh_token, and access_token_expires_at

Raises:

FreshBooksClientConfigError – If refresh_token is not set on the client instance and is not provided.

property service_rates: CommentsSubResource

FreshBooks service_rates resource with calls to get, list, create, update

property services: CommentsResource

FreshBooks services resource with calls to get, list, create, update, delete

property staff: AccountingResource

FreshBooks staff resource with calls to get, list, update, delete

property systems: AccountingResource

FreshBooks systems resource with calls to get only

property tasks: AccountingResource

FreshBooks tasks resource with calls to get, list, create, update, delete

Note: There is a lot of overlap between Services and Tasks. In general services are used to add categories of work to projects, and tasks are used to add billable work to invoices.

Creating a task should create the corresponding service and vice versa.

property taxes: AccountingResource

FreshBooks taxes resource with calls to get, list, create, update, delete

property time_entries: TimetrackingResource

FreshBooks time_entries resource with calls to get, list, create, update, delete

freshbooks.client.DEFAULT_TIMEOUT = 30

Default request timeout to FreshBooks

Resources

Accounting

class freshbooks.api.accounting.AccountingResource(client_config, accounting_path, single_name, list_name, delete_via_update=True, missing_endpoints=None)

Handles resources under the /accounting/account/ endpoints.

API_RETRIES = 3

Default number of retries

create(account_id, data, includes=None)

Create a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • account_id – The alpha-numeric account id

  • data – Dictionary of data to populate the resource

  • builders – (Optional) IncludesBuilder object for including additional data, sub-resources, etc.

Returns:

Result object with the new resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

delete(account_id, resource_id)

Delete a resource.

Note: Most FreshBooks resources are soft-deleted, See FreshBooks API - Active and Deleted Objects

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • account_id – The alpha-numeric account id

  • resource_id – Id of the resource to delete

Returns:

An empty Result object.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

get(account_id, resource_id, includes=None)

Get a single resource with the corresponding id.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • account_id – The alpha-numeric account id

  • resource_id – Id of the resource to return

  • includes – (Optional) IncludesBuilder object for including additional data, sub-resources, etc.

Returns:

Result object with the resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

headers(method, has_data)

Get headers required for API calls

Return type:

:sphinx_autodoc_typehints_type:``:py:class:``~typing.Dict`[str, str]`

list(account_id, builders=None)

Get a list of resources.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.ListResult

Parameters:
  • account_id – The alpha-numeric account id

  • builders – (Optional) List of builder objects for filters, pagination, etc.

Returns:

ListResult object with the resources response data.

Return type:

ListResult

Raises:

FreshBooksError – If the call is not successful.

update(account_id, resource_id, data, includes=None)

Update a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • account_id – The alpha-numeric account id

  • resource_id – Id of the resource to update

  • data – Dictionary of data to update the resource to

  • builders – (Optional) IncludesBuilder object for including additional data, sub-resources, etc.

Returns:

Result object with the updated resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

class freshbooks.api.accounting_business.AccountingBusinessResource(client_config, path, resource_name, missing_endpoints=None)

Handles resources under the /accounting/businesses/ endpoints.

API_RETRIES = 3

Default number of retries

create(business_uuid, data)

Create a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_uuid – The business uuid

  • data – Dictionary of data to populate the resource

Returns:

Result object with the new resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

delete(business_uuid, resource_uuid)

Delete a resource.

Note: Most FreshBooks resources are soft-deleted, See FreshBooks API - Active and Deleted Objects

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_uuid – The business uuid

  • resource_uuid – Id of the resource to return

Returns:

An empty Result object.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

get(business_uuid, resource_uuid)

Get a single resource with the corresponding id.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_uuid – The business uuid

  • resource_uuid – Id of the resource to return

Returns:

Result object with the resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

headers(method, has_data)

Get headers required for API calls

Return type:

:sphinx_autodoc_typehints_type:``:py:class:``~typing.Dict`[str, str]`

list(business_uuid)

Get a list of resources.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.ListResult

Parameters:

business_uuid – The business uuid

Returns:

ListResult object with the resources response data.

Return type:

ListResult

Raises:

FreshBooksError – If the call is not successful.

update(business_uuid, resource_uuid, data)

Update a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_uuid – The business uuid

  • resource_uuid – Id of the resource to return

  • data – Dictionary of data to update the resource to

Returns:

Result object with the updated resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

Auth

class freshbooks.api.auth.AuthResource(client_config)

Handles resources under the /auth endpoints.

API_RETRIES = 3

Default number of retries

headers(method, has_data)

Get headers required for API calls

Return type:

:sphinx_autodoc_typehints_type:``:py:class:``~typing.Dict`[str, str]`

me_endpoint()

Get the identity details of the currently authenticated user.

See FreshBooks API - Business, Roles, and Identity

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Identity

Returns:

Result object with the authenticated user’s identity and business details.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

Projects

class freshbooks.api.projects.ProjectsResource(client_config, list_resource_path, single_resource_path, list_name=None, single_name=None, missing_endpoints=None)

Bases: ProjectsBaseResource

Handles resources under the /projects endpoints.

create(business_id, data)

Create a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • data – Dictionary of data to populate the resource

Returns:

Result object with the new resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

delete(business_id, resource_id)

Delete a resource.

Note: Most FreshBooks resources are soft-deleted, See FreshBooks API - Active and Deleted Objects

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • resource_id – Id of the resource to delete

Returns:

An empty Result object.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

get(business_id, resource_id, includes=None)

Get a single resource with the corresponding id.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • resource_id – Id of the resource to return

  • includes – (Optional) IncludesBuilder object for including additional data, sub-resources, etc.

Returns:

Result object with the resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

list(business_id, builders=None)

Get a list of resources.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.ListResult

Parameters:
  • business_id – The business id

  • builders – (Optional) List of builder objects for filters, pagination, etc.

Returns:

ListResult object with the resources response data.

Return type:

ListResult

Raises:

FreshBooksError – If the call is not successful.

update(business_id, resource_id, data)

Update a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • resource_id – Id of the resource to update

  • data – Dictionary of data to update the resource to

Returns:

Result object with the updated resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

Comments

class freshbooks.api.comments.CommentsResource(client_config, list_resource_path, single_resource_path, list_name=None, single_name=None, missing_endpoints=None)

Bases: ProjectsResource

Handles resources under the /comments endpoints.

These are handled identically to /projects endpoints. Refer to freshbooks.api.projects.ProjectsResource.

API_RETRIES = 3

Default number of retries

create(business_id, data)

Create a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • data – Dictionary of data to populate the resource

Returns:

Result object with the new resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

delete(business_id, resource_id)

Delete a resource.

Note: Most FreshBooks resources are soft-deleted, See FreshBooks API - Active and Deleted Objects

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • resource_id – Id of the resource to delete

Returns:

An empty Result object.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

get(business_id, resource_id, includes=None)

Get a single resource with the corresponding id.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • resource_id – Id of the resource to return

  • includes – (Optional) IncludesBuilder object for including additional data, sub-resources, etc.

Returns:

Result object with the resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

headers(method, has_data)

Get headers required for API calls

Return type:

:sphinx_autodoc_typehints_type:``:py:class:``~typing.Dict`[str, str]`

list(business_id, builders=None)

Get a list of resources.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.ListResult

Parameters:
  • business_id – The business id

  • builders – (Optional) List of builder objects for filters, pagination, etc.

Returns:

ListResult object with the resources response data.

Return type:

ListResult

Raises:

FreshBooksError – If the call is not successful.

update(business_id, resource_id, data)

Update a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • resource_id – Id of the resource to update

  • data – Dictionary of data to update the resource to

Returns:

Result object with the updated resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

class freshbooks.api.comments.CommentsSubResource(client_config, list_resource_path, single_resource_path, single_resource_sub_path=None, list_name=None, single_name=None, missing_endpoints=None)

Bases: ProjectsBaseResource

Handles sub-resources under the /comments endpoints.

Eg. /comments/business/{business_id}/services/{service_id}/rate

These are handled similarly to /projects endpoints. Refer to freshbooks.api.projects.ProjectsResource.

API_RETRIES = 3

Default number of retries

create(business_id, resource_id, data)

Create a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • resource_id – Id of the parent resource to create this resource under

  • data – Dictionary of data to populate the resource

Returns:

Result object with the new resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

delete(business_id, resource_id)

Delete a resource.

Note: Most FreshBooks resources are soft-deleted, See FreshBooks API - Active and Deleted Objects

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • resource_id – Id of the resource to delete

Returns:

An empty Result object.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

get(business_id, resource_id)

Get a single resource with the corresponding id.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • resource_id – Id of the resource to return

Returns:

Result object with the resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

headers(method, has_data)

Get headers required for API calls

Return type:

:sphinx_autodoc_typehints_type:``:py:class:``~typing.Dict`[str, str]`

list(business_id, builders=None)

Get a list of resources.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.ListResult

Parameters:
  • business_id – The business id

  • builders – (Optional) List of builder objects for filters, pagination, etc.

Returns:

ListResult object with the resources response data.

Return type:

ListResult

Raises:

FreshBooksError – If the call is not successful.

update(business_id, resource_id, data)

Update a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • resource_id – Id of the resource to update

  • data – Dictionary of data to update the resource to

Returns:

Result object with the updated resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

Time-Tracking

class freshbooks.api.timetracking.TimetrackingResource(client_config, list_resource_path, single_resource_path, list_name=None, single_name=None, missing_endpoints=None)

Bases: ProjectsResource

Handles resources under the /timetracking endpoints.

These are handled identically to /projects endpoints. Refer to freshbooks.api.projects.ProjectsResource.

API_RETRIES = 3

Default number of retries

create(business_id, data)

Create a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • data – Dictionary of data to populate the resource

Returns:

Result object with the new resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

delete(business_id, resource_id)

Delete a resource.

Note: Most FreshBooks resources are soft-deleted, See FreshBooks API - Active and Deleted Objects

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • resource_id – Id of the resource to delete

Returns:

An empty Result object.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

get(business_id, resource_id, includes=None)

Get a single resource with the corresponding id.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • resource_id – Id of the resource to return

  • includes – (Optional) IncludesBuilder object for including additional data, sub-resources, etc.

Returns:

Result object with the resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

headers(method, has_data)

Get headers required for API calls

Return type:

:sphinx_autodoc_typehints_type:``:py:class:``~typing.Dict`[str, str]`

list(business_id, builders=None)

Get a list of resources.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.ListResult

Parameters:
  • business_id – The business id

  • builders – (Optional) List of builder objects for filters, pagination, etc.

Returns:

ListResult object with the resources response data.

Return type:

ListResult

Raises:

FreshBooksError – If the call is not successful.

update(business_id, resource_id, data)

Update a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • business_id – The business id

  • resource_id – Id of the resource to update

  • data – Dictionary of data to update the resource to

Returns:

Result object with the updated resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

Payments

class freshbooks.api.payments.PaymentsResource(client_config, path, single_name, sub_path=None, defaults_path=None, static_params=None, missing_endpoints=None)

Handles resources under the /payments endpoints.

API_RETRIES = 3

Default number of retries

create(account_id, resource_id, data)

Create a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • account_id – The alpha-numeric account id

  • resource_id – Id of the resource to create payment details for

  • data – Dictionary of data to populate the resource

Returns:

Result object with the new resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

defaults(account_id)

Get the default settings for an account resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:

account_id – The alpha-numeric account id

Returns:

Result object with the default data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

get(account_id, resource_id)

Get a single resource with the corresponding id.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • account_id – The alpha-numeric account id

  • resource_id – Id of the resource to return payment details for

Returns:

Result object with the resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

headers(method, has_data)

Get headers required for API calls

Return type:

:sphinx_autodoc_typehints_type:``:py:class:``~typing.Dict`[str, str]`

Events

class freshbooks.api.events.EventsResource(client_config, accounting_path, single_name, list_name, delete_via_update=True, missing_endpoints=None)

Bases: AccountingResource

Handles resources under the /events endpoints.

These are handled almost similarly to /accounting endpoints. Refer to freshbooks.api.accounting.AccountingResource.

API_RETRIES = 3

Default number of retries

create(account_id, data, includes=None)

Create a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • account_id – The alpha-numeric account id

  • data – Dictionary of data to populate the resource

  • builders – (Optional) IncludesBuilder object for including additional data, sub-resources, etc.

Returns:

Result object with the new resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

delete(account_id, resource_id)

Delete a resource.

Note: Most FreshBooks resources are soft-deleted, See FreshBooks API - Active and Deleted Objects

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • account_id – The alpha-numeric account id

  • resource_id – Id of the resource to delete

Returns:

An empty Result object.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

get(account_id, resource_id, includes=None)

Get a single resource with the corresponding id.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • account_id – The alpha-numeric account id

  • resource_id – Id of the resource to return

  • includes – (Optional) IncludesBuilder object for including additional data, sub-resources, etc.

Returns:

Result object with the resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

headers(method, has_data)

Get headers required for API calls

Return type:

:sphinx_autodoc_typehints_type:``:py:class:``~typing.Dict`[str, str]`

list(account_id, builders=None)

Get a list of resources.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.ListResult

Parameters:
  • account_id – The alpha-numeric account id

  • builders – (Optional) List of builder objects for filters, pagination, etc.

Returns:

ListResult object with the resources response data.

Return type:

ListResult

Raises:

FreshBooksError – If the call is not successful.

resend_verification(account_id, resource_id)

Tell FreshBooks to resend the verification webhook for the callback

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • account_id – The alpha-numeric account id

  • resource_id – Id of the resource to update

Returns:

Result object with the resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

update(account_id, resource_id, data, includes=None)

Update a resource.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • account_id – The alpha-numeric account id

  • resource_id – Id of the resource to update

  • data – Dictionary of data to update the resource to

  • builders – (Optional) IncludesBuilder object for including additional data, sub-resources, etc.

Returns:

Result object with the updated resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

verify(account_id, resource_id, verifier)

Verify webhook callback by making a put request

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.models.Result

Parameters:
  • account_id – The alpha-numeric account id

  • resource_id – Id of the resource to update

  • verifier – The string verifier received by the webhook callback URI

Returns:

Result object with the resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

Uploads

class freshbooks.api.uploads.UploadsResource(client_config, upload_path, single_name)

Bases: Resource

Handles resources under the /uploads endpoints.

API_RETRIES = 3

Default number of retries

get(jwt)

Get an uploaded file. This returns a requests.Response object to provide flexibility in handling the data.

Requests Binary Response

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~requests.Response

Parameters:

jwt – JWT provided by FreshBooks when the file was uploaded.

Returns:

The requests Response object.

Return type:

requests.Response

Raises:

FreshBooksError – If the call is not successful.

headers(method, has_data)

Get headers required for API calls

Return type:

:sphinx_autodoc_typehints_type:``:py:class:``~typing.Dict`[str, str]`

upload(account_id, file_stream=None, file_path=None)

Upload a file to FreshBooks’ file storage. This returns a Result object with the JWT required to access the file, and in the case of an image, a link to the image itself.

The file to upload can be either a byte stream, or a path to the file itself.

Eg.

:rtype: :sphinx_autodoc_typehints_type:`\:py\:class\:\`\~freshbooks.models.Result\``

>>> uploaded = freshBooksClient.images.upload(account_id, file_path="/path/to/image.png")
>>> uploaded = freshBooksClient.images.upload(account_id, file_stream=open("/path/to/image.png", "rb")

>>> print(uploaded.jwt)
<some jwt>

>>> print(uploaded.link)
https://my.freshbooks.com/service/uploads/images/<some jwt>
Parameters:
  • account_id – The alpha-numeric account id

  • file_stream – (Optional) Byte stream of the file

  • file_path – (Optional) Path to the file

Returns:

Result object with the new resource’s response data.

Return type:

Result

Raises:

FreshBooksError – If the call is not successful.

Models

class freshbooks.models.Identity(data)

Bases: Result

An Identity is a freshbooks.models.Result object with additional properties and helper methods to make accessing the current user’s identity easier.

Example:

>>> current_user = freshBooksClient.current_user()
>>> current_user.email
<some email>

>>> current_user.business_memberships
<list of businesses>
property business_memberships: dict

The authenticated user’s businesses and their role in that business.

property full_name: str

The authenticated user’s name

property identity_id: int

The authenticated user’s identity_id

class freshbooks.models.ListResult(name, single_name, data, include_pages=True)

Bases: object

Result object from API calls with a list of resources returned.

Data in the API can be accessed via attributes.

Example:

clients = freshBooksClient.clients.list(account_id)
assert clients[0].organization == "FreshBooks"

The json-parsed dictionary can also be directly accessed via the data attribute.

Example:

assert clients.data["clients"][0]["organization"] == "FreshBooks"

The list can also be iterated over to access the individual resources as Result obejcts.

Example:

for client in clients:
    assert client.organization == "FreshBooks"
    assert client.data["organization"] == "FreshBooks"

Pagination results are included in the pages attribute:

>>> clients.pages
PageResult(page=1, pages=1, per_page=30, total=6)
>>> clients.pages.total
6

For including pagination in requests, see freshbooks.builders.paginator.PaginateBuilder.

class freshbooks.models.Result(name, data)

Bases: object

Result object from API calls with a single resource returned.

Data in the API can be accessed via attributes.

Example:

client = freshBooksClient.clients.get(account_id, user_id)
assert client.organization == "FreshBooks"
assert client.userid == user_id

The json-parsed dictionary can also be directly accessed via the data attribute.

Example:

assert client.data["organization"] == "FreshBooks"
assert client.data["userid"] == user_id
enum freshbooks.models.VisState(value)

Bases: IntEnum

Enum of FreshBooks entity vis_status values

Member Type:

int

Valid values are as follows:

ACTIVE = <VisState.ACTIVE: 0>
DELETED = <VisState.DELETED: 1>
ARCHIVED = <VisState.ARCHIVED: 2>

Builders

Paginator

class freshbooks.builders.paginator.PaginateBuilder(page=None, per_page=None)

Bases: Builder

Builder for making paginated list queries.

Has two attributes, page and per_page. When a PaginateBuilder object is passed to a .list() call, the call will fetch only the per_page number of results and will fetch the results offset by page.

>>> from freshbooks import PaginateBuilder

>>> paginator = PaginateBuilder(2, 4)
>>> paginator
PaginateBuilder(page=2, per_page=4)

>>> clients = freshBooksClient.clients.list(account_id, builders=[paginator])
>>> clients.pages
PageResult(page=2, pages=3, per_page=4, total=9)
build(resource_name=None)

Builds the query string parameters from the PaginateBuilder.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``str

Parameters:

resource_name – The type of resource to generate the query string for. Eg. AccountingResource, ProjectsResource

Returns:

The built query string

page(page=None)

Set the page you wish to fetch in a list call, or get the currently set the page. When setting, can be chained.

>>> paginator = PaginateBuilder(1, 3)
:rtype: :sphinx_autodoc_typehints_type:`\:py\:data\:\`\~typing.Union\`\\ \\\[\:py\:class\:\`int\`\, \:py\:obj\:\`None\`\, \:py\:class\:\`\~freshbooks.builders.Builder\`\]`

>>> paginator
PaginateBuilder(page=1, per_page=3)

>>> paginator.page()
1

>>> paginator.page(2).per_page(4)
>>> paginator
PaginateBuilder(page=2, per_page=4)
Parameters:

page – (Optional) The page of results to return in the API call

Returns:

The PaginateBuilder instance if a page value is provided, otherwise returns the current page value.

per_page(per_page=None)

Set the number of results you wish to fetch in a page of a list call, or get the currently set per_page. When setting, can be chained.

The page size is capped at 100.

>>> paginator = PaginateBuilder(1, 3)
:rtype: :sphinx_autodoc_typehints_type:`\:py\:data\:\`\~typing.Union\`\\ \\\[\:py\:class\:\`int\`\, \:py\:obj\:\`None\`\, \:py\:class\:\`\~freshbooks.builders.Builder\`\]`

>>> paginator
PaginateBuilder(page=1, per_page=3)

>>> paginator.per_page()
3

>>> paginator.per_page(4).page(2)
>>> paginator
PaginateBuilder(page=2, per_page=4)
Parameters:

per_page – (Optional) The number of results to return in each API call

Returns:

The PaginateBuilder instance if a per_page value is provided, otherwise the current per_page value.

Filters

class freshbooks.builders.filter.FilterBuilder

Bases: Builder

Builder for making filtered list queries.

Filters can be builts with the methods: equals, in_list, like, between, and boolean, date_time which can be chained together.

>>> from freshbooks import FilterBuilder

>>> f = FilterBuilder()
>>> f.like("email_like", "@freshbooks.com")
FilterBuilder(&search[email_like]=@freshbooks.com)

>>> f = FilterBuilder()
>>> f.in_list("clientids", [123, 456]).boolean("active", False)
FilterBuilder(&search[clientids][]=123&search[clientids][]=456&active=False)

>>> f = FilterBuilder()
>>> f.boolean("active", False).in_list("clientids", [123, 456])
FilterBuilder(&active=False&search[clientids][]=123&search[clientids][]=456)

>>> f = FilterBuilder()
>>> f.between("amount", 1, 10)
FilterBuilder(&search[amount_min]=1&search[amount_max]=10)

>>> f = FilterBuilder()
>>> f.between("start_date", date.today())
FilterBuilder(&search[start_date]=2020-11-21)
between(field, min=None, max=None)

Filters results where the provided field is between two values.

In general ‘between’ filters end in a _min or _max (as in amount_min or amount_max) or _date (as in start_date, end_date). If the provided field does not end in _min/_max or _date, then the appropriate _min/_max will be appended.

For date fields, you can pass the iso format 2020-10-17 or a datetime or date object, which will be converted to the proper string format.

Examples: :rtype: :sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.builders.Builder

  • filter.between("amount", 1, 10) will yield filters &search[amount_min]=1&search[amount_max]=10

  • filter.between("amount_min", min=1) will yield filter &search[amount_min]=1

  • filter.between("amount_max", max=10) will yield filter &search[amount_max]=10

  • filter.between("start_date", "2020-10-17") will yield filter &search[start_date]=2020-10-17

  • filter.between("start_date", date(year=2020, month=10, day=17)) yields &search[start_date]=2020-10-17

Parameters:
  • field – The API response field to filter on

  • min – (Optional) The value the field should be greater than (or equal to)

  • max – (Optional) The value the field should be less than (or equal to)

Returns:

The FilterBuilder instance

boolean(field, value)

Filters results where the field is equal to true or false.

Example: filter.boolean("active", False) will yield the filter &active=false

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.builders.Builder

Parameters:
  • field – The API response field to filter on

  • value – True or False

Returns:

The FilterBuilder instance

build(resource_name=None)

Builds the query string parameters from the FilterBuilder.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``str

Parameters:

resource_name – The type of resource to generate the query string for. Eg. AccountingResource, ProjectsResource

Returns:

The built query string

date_time(field, value)

Filters for entries that come before or after a particular time, as specified by the field. Eg. “updated_since” on Time Entries will return time entries updated after the provided time.

The url parameter must be in ISO 8601 format (eg. 2010-10-17T05:45:53Z)

Example: :rtype: :sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.builders.Builder

  • filter.date_time("updated_since", "2020-10-17T13:14:07") will yield &updated_since=2020-10-17T13:14:07

Parameters:
  • field – The API response field to filter on

  • value – The datetime, or ISO 8601 format string value

Returns:

The FilterBuilder instance

equals(field, value)

Filters results where the field is equal to the provided value.

Example: filter.equals("username", "Bob") will yield the filter &search[username]=Bob

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.builders.Builder

Parameters:
  • field – The API response field to filter on

  • value – The value the field should equal

Returns:

The FilterBuilder instance

in_list(field, values)

Filters if the provided field matches a value in a list.

In general, an ‘in’ filter will be bound to the plural form of the field. Eg. userid for an equal filter, userids for a list filter.

Here we only append an ‘s’ to the field name if it doesn’t have one yet. This way we can be as forgiving as possible for developers by accepting: filter.in_list("userid", [1, 2]) or filter.in_list("userids", [1, 2]).

Of course the FreshBooks API is not 100% consistent, so there are a couple of unique cases that may not be handled.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.builders.Builder

Parameters:
  • field – The API response field to filter on

  • values – List of values the field should one of

Returns:

The FilterBuilder instance

like(field, value)

Filters for a match contained within the field being searched. For example, “leaf” will Like-match “aleaf” and “leafy”, but not “leav”, and “leafs” would not Like-match “leaf”.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.builders.Builder

Parameters:
  • field – The API response field to filter on

  • value – The value the field should contain

Returns:

The FilterBuilder instance

Includes

class freshbooks.builders.includes.IncludesBuilder

Bases: Builder

Builder for including relationships, sub-resources, or additional data in the response.

>>> from freshbooks import IncludesBuilder

>>> includes = IncludesBuilder()
>>> includes.include("late_reminders")
IncludesBuilder(&include[]=late_reminders)
build(resource_name=None)

Builds the query string parameters from the IncludesBuilder.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``str

Parameters:

resource_name – The type of resource to generate the query string for. Eg. AccountingResource, ProjectsResource

Returns:

The built query string

include(key)

Add an include key to the builder.

Example: includes.include("late_reminders") will yield the filter &include[]=late_reminders

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.builders.Builder

Parameters:

key – The key for the resource or data to include

Returns:

The IncludesBuilder instance

Sort

class freshbooks.builders.sort.SortBuilder

Bases: Builder

Builder for including sort by field data in a list request.

>>> from freshbooks import SortBuilder

>>> sort = SortBuilder()
>>> sort.ascending("invoice_date")
SortBuilder(&sort=invoice_date_asc)
asc(key)

Alias for .ascending()

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.builders.Builder

ascending(key)

Add a sort by the field in ascending order.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.builders.Builder

Parameters:

key – The field for the resource list to be sorted by

build(resource_name=None)

Builds the query string parameter from the SortBuilder.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``str

Parameters:

resource_name – The type of resource to generate the query string for. Eg. AccountingResource, ProjectsResource

Returns:

The built query string

desc(key)

Alias for .descending()

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.builders.Builder

descending(key)

Add a sort by the field in descending order.

Return type:

:sphinx_autodoc_typehints_type:\:py\:class\:\``~freshbooks.builders.Builder

Parameters:

key – The field for the resource list to be sorted by

Errors

exception freshbooks.errors.FreshBooksClientConfigError

Bases: Exception

Exception thrown when optional client parameters are not set, but and required.

with_traceback()

Exception.with_traceback(tb) – set self.**traceback** to tb and return self.

exception freshbooks.errors.FreshBooksError(status_code, message, raw_response=None, error_code=None, error_details=None)

Bases: Exception

Exception thrown when FreshBooks returns a non-2xx response or when the response is missing expected content.

Example:

try:
    client = freshBooksClient.clients.get(self.account_id, client_id)
except FreshBooksError as e:
    assert str(e) == "Client not found."
    assert e.status_code == 404
    assert e.error_code == 1012
message

Error message

status_code

HTTP status code from the server.

raw_response

Content response from the server.

error_code

(Optional) FreshBooks specific error code, if available

error_details

(Optional) Details of the error, if available

with_traceback()

Exception.with_traceback(tb) – set self.**traceback** to tb and return self.

exception freshbooks.errors.FreshBooksNotImplementedError(resource_name, method_name)

Bases: Exception

Exception thrown when making a resource call that does not exist. Eg.

>>> freshBooksClient.staff.create()
with_traceback()

Exception.with_traceback(tb) – set self.**traceback** to tb and return self.

Indices and tables