Python SDK Quickstart
Following the steps described on this page, you'll create a simple Python application that interacts with the Fatture in Cloud API.
If you want to download the complete working example you can find it here.
0️⃣ Prerequisites
In this guide, we assume that these prerequisites are met:
- Python >= 3.6 installed
- A private app using the OAuth 2.0 Authorization Code Flow
- A Fatture in Cloud account.
1️⃣ Step One: Install the Fatture in Cloud SDK
In this quickstart, we'll use the Fatture in Cloud SDK, published to PyPI.
To install it using pip:
pip install fattureincloud-python-sdk
2️⃣ Step Two: Set up the OAuth access token retrieval
Create the file oauth.py and copy in the following code:
import json
from urllib.parse import urlparse
from urllib.parse import parse_qs
from fattureincloud_python_sdk.oauth2.oauth2 import OAuth2AuthorizationCodeManager
from fattureincloud_python_sdk.oauth2.oauth2 import Scope
class Oauth:
def get_oauth_access_token(self):
oauth = OAuth2AuthorizationCodeManager('CLIENT_ID', 'CLIENT_SECRET', 'http://localhost:8000/oauth')
query_components = parse_qs(urlparse(self.path).query)
if 'code' in query_components:
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
code = query_components['code'][0]
token = oauth.fetch_token(code)
file = open('./token.json', 'w')
file.write(json.dumps({"access_token": token.access_token})) #saving the oAuth access token in the token.json file
file.close()
self.wfile.write(bytes('Token saved succesfully in ./token.json', 'utf8'))
else:
url = oauth.get_authorization_url([Scope.ENTITY_SUPPLIERS_READ], 'EXAMPLE_STATE')
self.send_response(302)
self.send_header('Location', url)
self.end_headers()
return
To make this code work properly the only thing you need to set your client id, client secret and eventually the redirect uri at line 9.
In this QuickStart the access token and refresh token are stored in a file, this is only for educational purposes, the OAuth access token and refresh token are sensitive data and should be saved securely on your database. Also, never share your Client Secret with third-party actors, or publish it to your frontend!
4️⃣ Step Four: Set up the sample
In this example, we'll show how to retrieve your Company ID using the Python SDK. If you plan to manage only one company, you can insert it directly into your code as a variable. Check the Company-scoped Methods page for more info.
Create the files index.py and quickstart.py in your working directory and copy in the following code:
- index.py
- quickstart.py
from http.server import BaseHTTPRequestHandler, HTTPServer
from oauth import Oauth #import the Oauth class
from quickstart import Quickstart #import the Quickstart class
class testHTTPServer_RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
#url routing
if self.path.startswith('/oauth'): #oauth endpoint
Oauth.get_oauth_access_token(self)
elif self.path == '/quickstart': #quickstart endpoint
Quickstart.get_first_company_suppliers(self)
return
def run():
print('Avvio del server...')
server_address = ('127.0.0.1', 8000) #set your hostname and port
httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
print('Server in esecuzione...')
httpd.serve_forever()
run()
import fattureincloud_python_sdk
from fattureincloud_python_sdk.api import user_api
from fattureincloud_python_sdk.api import suppliers_api
from fattureincloud_python_sdk.models.list_user_companies_response import ListUserCompaniesResponse
import json
import collections
collections.Callable = collections.abc.Callable #needed if you are using python > 3.10
class Quickstart:
def get_first_company_suppliers(self):
token_file = open("./token.json")
json_file = json.load(token_file)
token_file.close()
configuration = fattureincloud_python_sdk.Configuration()
configuration.access_token = json_file["access_token"]
with fattureincloud_python_sdk.ApiClient(configuration) as api_client:
# Retrieve the first company id
user_api_instance = user_api.UserApi(api_client)
user_companies_response = user_api_instance.list_user_companies()
first_company_id = user_companies_response.data.companies[0].id
# Retrieve the list of the Suppliers
suppliers_api_instance = suppliers_api.SuppliersApi(api_client)
company_suppliers = suppliers_api_instance.list_suppliers(first_company_id)
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(bytes(str(company_suppliers.data), "utf8"))
return
Make sure your FattureInCloud app redirect URL points to the just defined /oauth endpoint (e.g. http://localhost:8000/oauth).
5️⃣ Step Five: Run the sample
From the command line, run the following command:
python3 index.py
Now visit http://localhost:8000/oauth (or whatever your URL is), you will be redirected to the Fatture in Cloud login page where you will be asked to grant some permissions, according to what scopes you specified previously. Finally, you will see the success message and the access token will be stored in the token.json file.
You can now visit http://localhost:8000/quickstart (or whatever your URL is) to test the application.
❓ What now?
In this example, we used a limited set of the available API methods to show how to use our SDK.
If you want to access the full documentation of the available methods and models, you can check the following resources:
- Python SDK GitHub Repository: the Readme file contains the full list of the available methods and models
- API Reference: it contains the list of methods and models
- OpenAPI Specification: Our OpenAPI Specification contains the full description of the available methods and models
- PyPI page: The main package page on PyPI