Export to File
Usually, the best way to retrieve the Fatture in Cloud resources is to include the related API calls in your code, but in some cases, being able to export our data from Fatture in Cloud to a file can be extremely important.
For example, when using Zapier it can be challenging to retrieve the IDs of some resources, such as Products, Clients, Suppliers, Payment Methods, Payment Accounts, etc... Knowing these IDs is mandatory when creating new documents using Zapier, but it can be complicated to retrieve them using Zapier itself.
In this guide, we'll show you a simple way to retrieve your data and store them in a Spreadsheet file. From there, you'll be able to use the extracted data as you prefer.
👮 Authentication and Company
To execute this code, you will need to replace two parameters in the code with your values. These parameters are:
- The Access Token, that will be used to authenticate your API calls
- The Company ID, which is used by our APIs to identify the Company you're working on
The Access Token can be retrieved in multiple ways, but for this use case, we strongly suggest the Manual Token.
When you create a Token, you will need to select the correct Scopes. For example, the List Products method requires the product:r
scope. Check the scopes required by your API method before creating the token.
The Company ID is the identifier of the Company, so you can retrieve it only once and use it for every API call. It can be retrieved as explained here. To make this task easier for you, we also added the code to retrieve the Company ID, but we commented it so that you can use it only if needed.
🛑 Wait a minute!
Before showing you our code, we must discuss a moment about why we decided to create this guide.
First of all, the main problem performing the export is that some of these operations are paginated; this means that the API will return only a subset of the resources (the maximum page size is 100), and you'll need to perform multiple API requests to obtain the whole set of resources.
For the List methods that don't require pagination (such as the List Payment Accounts) this operation is trivial, so we won't show it here; this code can be easily adapted to be used also for this kind of resources.
You can recognize a paginated method because it contains dedicated fields, such as page and per_page.
This operation should NOT be used to obtain the most advanced resources, such as the Issued Documents. This kind of resource usually comes in a much higher set size than the Products, and it will likely consume your quotas fast. If you still want to use this code to retrieve the documents, we suggest you at least filter the results to limit the number of exported documents as much as possible.
On this page, we decided to show you how to export the Products using the List Products method. We selected this API method because it is paginated, and its IDs can be used while creating new documents; also, you will probably have more than a single page of products, so it would be impossible to export the whole set by using a single API call.
By proceeding forward, you'll also notice that we provided only Python code. We decided to use Python because it is relatively easy to install, and also because it is one of the few languages supported by Zapier in their Actions. You can still decide to use our code as a guide to implementing the same functionality in your favorite language.
We will provide three different use cases, select the one you prefer:
🖍 Export with Zapier
Zapier is an extremely useful no-code tool, that lets users without coding competences to be able to create simple integrations.
At the same time, it can be complicated to use in slightly complicated use cases, such as the pagination management.
Our Zapier integration provides the Actions to use List API methods such as the List Products, but the pagination can make it extremely difficult (but not impossible) to retrieve the whole set of resources.
Zapier has its own limits, based on the plan you are currently using. Most probably, the free plan will NOT be enough to perform the export if you have more than one page.
You can check the limits in the Zap limits and in the Code by Zapier rate limits
The Export Zap would be composed of three different steps.
The first step is the Trigger, that is used to define then a Zap must be executed. In this case we won't use any data coming from the Trigger, so you can just use the trigger that you prefer, but we strongly suggest to use the Zapier Chrome Extension that lets you to trigger a Zap by clicking a button on your browser.
The second step is where the magic happens, this is why we decided to describe it in two different subsections:
If the method is NOT paginated, you can simply select one of the Fatture in Cloud Actions (for example the List Payment Methods) and use it to extract the data.
If the method is paginated, using one of our actions can be really complicated so we suggest to use the Code by Zapier Action.
When you test a List Action, Zap will always return just one of the elements returned to the action; this is because you can use this element to link the next steps. The whole list of resources will be returned only after the Zap publication.
The third step will let you write the retrieved resources to its final destination.
You could for example use the Google Sheets' Create Multiple Spreadsheet Rows action, or Microsoft Excel's Add Row(s) action, or one of the other actions offered by Zapier. The decision is up to you.
☁️ Fatture in Cloud's Zapier Actions
The Fatture in Cloud Actions are easy to use because they take care of some of the required details, such as the Authentication and the Company ID retrieval, but at the same time they don't take in consideration the Pagination, making this kind of actions tricky to use for this use case.
If the method is NOT paginated, the Fatture in Cloud Actions are the best solution and we strongly suggest to use them for the second step, because you just have to configure them correctly and you'll obtain the whole set of the resources.
If, instead, the method is paginated, you must repeat the API call multiple times to retrieve all the resources.
Two solutions we found to deal with pagination are:
- The Zapier Chrome Extension lets you to define some optional Input Fields to be sent to the Zap. You can use this feature to pass the current page number to the List Action: this is the easier way to manage the pages, but it requires to perform the operation manually and to trigger the Zap multiple times.
- You can try to use the Looping by Zapier action to manage the loop automatically; the problem is that you need to manage the number of iterations and to do that you need to retrieve the last_page value from the List Action itself. Most probably, you would need to perform the List Action once just to retrieve the value, and then start the loop to retrieve all the elements.
We decided to not show the details of these two operations, because they're out of the scope of this guide.
💻 Code by Zapier Action
The Code by Zapier Action is a special kind of action that makes it possible to perform custom operations by inserting Python or JavaScript code directly inside of the action. In this case, we'll use a simple Python script to perform the API calls and deal with the pagination at the same time.
First, you need to select the Code by Zapier App and choose the Run Python Action Event.
Then, in the Configure section you'll need to insert the following Python code:
import requests
import json
# You must set the company_id and token variables before running this script
company_id = 0
token = "TOKEN"
payload = {}
headers = {
'Accept': 'application/json',
'Authorization': f"Bearer {token}"
}
# # Uncomment the following lines to get the company_id from the api
# # This will make the Action slower and a timeout could occur
# url = f"https://api-v2.fattureincloud.it/user/companies"
# response = requests.request("GET", url, headers=headers, data=payload)
# m = response.json()
# company_id = m['data']['companies'][0]['id']
products = []
curr_page = 1
last_page = 1
while True:
url = f"https://api-v2.fattureincloud.it/c/{company_id}/products?fieldset=detailed&page={curr_page}&per_page=100"
response = requests.request("GET", url, headers=headers, data=payload)
m = response.json()
items = m['data']
products = products + items
if curr_page == 1:
# Get the total number of pages
last_page = m['last_page']
curr_page = curr_page + 1
if curr_page > last_page:
break
return products
This code will perform the API call multiple times, retrieving all the elements and passing them to the next Zap step.
This method is surely easier than dealing with pagination as explained previously, but some problems could occur:
- You must check Zapier limits, especially the ones regarding the memory and execution time
- You could consume Fatture in Cloud's quotas with huge sets of resources
🧁 Python Vanilla Code
We usually suggest to use our SDKs to deal with our APIs, but if you just need to export basic parameters such as the resource IDs you can also proceed with a simple HTTP Client. Also, Zapier lets you use only the requests library, so we still decided to provide this example.
In this case, we will retrieve the results as done with Zapier before, and then we will save them in an XLSX file. To do that we will use the openpyxl library (this is not necessary in Zapier, because it provides Microsoft Excel and Google Sheets integrations).
This solution can overcome Zapier's limitations, but you could still consume Fatture in Cloud's quotas with huge sets of resources.
You can find the code here: GitHub - Vanilla Code
First, you need to install Python. Then, you can create an empty folder for your project and install a Virtual Environment as follows:
mkdir exporter
cd exporter
python3 -m venv "venv"
Once you created the Virtual Environment, you'll need to activate it. This is required everytime you'll need to execute the export.
source venv/bin/activate
Now we are ready to start creating the project.
First, let's create the requirements.txt
file, that defines the project's dependencies:
requests==2.32.3
openpyxl==3.1.5
Then, let's create the main.py
file, that defines the project's logic (remember to replace the company_id, token, and filepath variables):
import requests
import json
# You must set the company_id and token variables before running this script
company_id = 0
token = "TOKEN"
filepath = "products.xlsx"
payload = {}
headers = {
'Accept': 'application/json',
'Authorization': f"Bearer {token}"
}
# # Uncomment the following lines to get the company_id from the api
# url = f"https://api-v2.fattureincloud.it/user/companies"
# response = requests.request("GET", url, headers=headers, data=payload)
# m = response.json()
# company_id = m['data']['companies'][0]['id']
# print(f"Using company id: {company_id}")
products = []
curr_page = 1
last_page = 1
while True:
url = f"https://api-v2.fattureincloud.it/c/{company_id}/products?fieldset=detailed&page={curr_page}&per_page=100"
response = requests.request("GET", url, headers=headers, data=payload)
m = response.json()
items = m['data']
products = products + items
if curr_page == 1:
# Get the total number of pages
last_page = m['last_page']
print(f"Page {curr_page} of {last_page}")
curr_page = curr_page + 1
if curr_page > last_page:
break
print(json.dumps(products, indent=4))
# Here we write the products to an excel file
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# Here we select only a few columns, but you can customize the file as you want
ws.append(["id", "name", "code"])
for product in products:
ws.append([product['id'], product['name'], product['code']])
# Save the file
wb.save(filepath)
Before launching the code we just need to install the dependencies:
pip install -r requirements.txt
Once the libraries are installed correctly, we can proceed with the export:
python3 main.py
This will download all the Products and write them in the path you specified in the filepath variable.
🐍 Python SDK Code
This example is similar to the Vanilla code, but it uses the Fatture in Cloud Python SDK instead of the HTTP Client.
In this case, we will retrieve the results as done with Zapier before, and then we will save them in an XLSX file. To do that we will use the openpyxl library (this is not necessary in Zapier, because it provides Microsoft Excel and Google Sheets integrations).
This solution can overcome Zapier's limitations, but you could still consume Fatture in Cloud's quotas with huge sets of resources.
You can find the code here: GitHub - SDK Code
First, you need to install Python. Then, you can create an empty folder for your project and install a Virtual Environment as follows:
mkdir exporter
cd exporter
python3 -m venv "venv"
Once you created the Virtual Environment, you'll need to activate it. This is required everytime you'll need to execute the export.
source venv/bin/activate
Now we are ready to start creating the project.
First, let's create the requirements.txt
file, that defines the project's dependencies:
fattureincloud-python-sdk==2.1.2
openpyxl==3.1.5
Then, let's create the main.py
file, that defines the project's logic (remember to replace the company_id, token, and filepath variables):
import fattureincloud_python_sdk
from fattureincloud_python_sdk.models.list_products_response import ListProductsResponse
from fattureincloud_python_sdk.rest import ApiException
import json
# You must set the company_id and token variables before running this script
company_id = 0
token = "TOKEN"
filepath = "products.xlsx"
configuration = fattureincloud_python_sdk.Configuration(
host = "https://api-v2.fattureincloud.it",
access_token = token
)
with fattureincloud_python_sdk.ApiClient(configuration) as api_client:
# # Uncomment the following lines to get the company_id from the api
# user_api = fattureincloud_python_sdk.UserApi(api_client)
# try:
# # List User Companies
# api_response = user_api.list_user_companies()
# company_id = api_response.data.companies[0].id
# print(f"Using company id: {company_id}")
# except Exception as e:
# print("Exception when calling UserApi->list_user_companies: %s\n" % e)
products_api = fattureincloud_python_sdk.ProductsApi(api_client)
per_page = 100
fieldset = "detailed"
try:
products = []
curr_page = 1
last_page = 1
while True:
# List Products
api_response = products_api.list_products(company_id, fieldset=fieldset, page=curr_page, per_page=per_page)
items = []
for p in api_response.data:
items.append(p.to_dict())
products = products + items
if curr_page == 1:
# Get the total number of pages
last_page = api_response.last_page
print(f"Page {curr_page} of {last_page}")
curr_page = curr_page + 1
if curr_page > last_page:
break
except Exception as e:
print("Exception when calling ProductsApi->list_products: %s\n" % e)
print(json.dumps(products, indent=4))
# Here we write the products to an excel file
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
# Here we select only a few columns, but you can customize the file as you want
ws.append(["id", "name", "code"])
for product in products:
ws.append([product['id'], product['name'], product['code']])
# Save the file
wb.save(filepath)
Before launching the code we just need to install the dependencies:
pip install -r requirements.txt
Once the libraries are installed correctly, we can proceed with the export:
python3 main.py
This will download all the Products and write them in the path you specified in the filepath variable.