FIZ SDK for Python
Issue AT-certified invoices in Portugal from your code. FIZ is invoicing software certified by the Autoridade Tributária (No. 3041): it numbers each document in its series, adds the ATCUD and the QR code, reports it to the AT when it is issued and returns the number and the PDF.
This is the official client for the FIZ API: every operation typed from the API's OpenAPI document, with safe retries built in.
Português · API reference · Quickstart · Changelog
pip install fiz-sdk
Python 3.10 or later (CI tests 3.10 to 3.13). Keep the key on your server: an API key acts for the whole company, so it must never ship inside an app or page that other people run.
Quickstart
Run it with a sandbox key: create one at app.fiz.co → Settings → Integrations
and put it in FIZ_API_KEY. A key starting with fiz_test_ sends documents
to the AT test services, with no fiscal effect. Both steps below stop on any
other key, because the second one issues a real invoice with a production key.
Step 1: a draft and its PDF. A draft has no number and no fiscal effect.
from pathlib import Path
from fiz_sdk import Fiz
fiz = Fiz() # reads FIZ_API_KEY
if fiz.environment != "sandbox":
raise SystemExit("Use a sandbox key (fiz_test_…) for this walkthrough.")
# Which company is this, and can it issue yet?
company = fiz.company.retrieve()
if not company["readiness"]["ready"]:
print(company["readiness"]["reasons"])
# Every invoice states one of the company's activity codes (CAE).
if not company["cae"]:
raise SystemExit("The company has no CAE yet: add its activity in FIZ first.")
cae = company["cae"][0]
customer = fiz.customers.create({"name": "Example customer", "country": "PT"})
item = fiz.items.create(
{"name": "Example service", "type": "SERVICE", "unitPrice": 10, "vatRate": "NORMAL"}
)
draft = fiz.invoices.create(
{
"type": "INVOICE",
"cae": cae,
"customerId": customer["id"],
"items": [{"id": item["id"], "quantity": 1}],
}
)
Path("draft.pdf").write_bytes(fiz.invoices.download_pdf(draft["id"]))
# The revision pins what you are about to look at. Without one there is nothing
# to check the issue against: stop rather than issue whatever the draft is by then.
if not draft["updatedAt"]:
raise SystemExit("The draft came back without its revision.")
print("Look at draft.pdf, then issue:", draft["id"], draft["updatedAt"])
Step 2, once you have looked at the PDF: issue that draft. Issuing is
fiscal and irreversible with a production key: numbered, ATCUD, reported to
the AT. expectedUpdatedAt issues exactly the draft you looked at, and the
API refuses it if anyone changed it since.
import sys
from fiz_sdk import Fiz
fiz = Fiz()
if fiz.environment != "sandbox":
raise SystemExit("Use a sandbox key (fiz_test_…) for this walkthrough.")
draft_id, revision = sys.argv[1], sys.argv[2] # what step 1 printed
invoice = fiz.invoices.issue(draft_id, {"expectedUpdatedAt": revision})
print(invoice["number"], invoice["atcud"])
The same two steps as one runnable script are in
examples/quickstart.py: its first run creates the
draft and saves its PDF, and a second run with --issue issues that draft.
What it covers
fiz.invoices |
invoices, simplified invoices, invoice-receipts: create, list, list_all, retrieve, update, delete, issue, pay, cancel, pdf, download_pdf |
fiz.credit_notes |
full or per-line credit notes (issued at once unless "issue": False) |
fiz.recurring_invoices |
invoices FIZ issues on a schedule |
fiz.proposals |
pro formas (no fiscal effect) |
fiz.transport_documents |
guias de transporte (GR, GT, GA, GC, GD) |
fiz.customers, fiz.items |
customers and the item catalogue |
fiz.series, fiz.templates |
invoice series, PDF templates |
fiz.company, fiz.vat |
the company and issuance readiness, VAT rules |
fiz.expenses, fiz.bank |
e-Fatura expenses, bank transactions |
fiz.exports |
SAF-T PT export |
Methods marked fiscal and irreversible in their documentation (issue,
pay, cancel, credit notes) report to the AT when used with a production
key.
Requests and responses are plain dicts with the API's own field names
(customerId, updatedAt), typed as TypedDicts. Any operation of the API
is also reachable by its OpenAPI operationId, typed the same way, including
ones this SDK version does not wrap in a method yet:
series = fiz.call("SeriesController_getAll")
Errors
Every failed request raises a FizApiError subclass. Branch on status and
code; the message is for people and its wording may change.
from fiz_sdk import FizApiError, FizNotFoundError
try:
fiz.invoices.retrieve(invoice_id)
except FizNotFoundError:
... # 404
except FizApiError as error:
print(error.status, error.code, error.messages)
print("Quote to support:", error.request_id)
raise
| Class | Status |
|---|---|
FizBadRequestError |
400 — refused as invalid; messages has one line per field |
FizAuthenticationError |
401 — key or token missing, invalid or revoked |
FizPermissionError |
403 — scope, plan or permission |
FizNotFoundError |
404 |
FizConflictError |
409 — see Retries |
FizUnprocessableEntityError |
422 — Idempotency-Key reused with a different request |
FizRateLimitError |
429 |
FizServerError |
5xx |
FizConnectionError, FizTimeoutError |
no response |
All of them derive from FizError.
Retries and idempotency
Every write carries an Idempotency-Key. The API remembers it for 30 days
and answers a repeat with the original response, so a timeout never costs a
duplicate invoice. The SDK generates one per call (a UUID) and reuses it for
its own retries. Pass yours to make retries safe across restarts too, for
example the id of the order the invoice is for:
fiz.invoices.create(draft, idempotency_key=f"order-{order.id}-invoice")
The SDK retries (default max_retries=2) only what is safe to repeat:
- no response at all, on a read or a write carrying a key;
429, afterRetry-After(a wait longer than a minute is not taken: the error is raised);409withRetry-After: the first attempt is still running, and the same key returns its result;502,503,504on a read.
It does not retry a 409 without Retry-After or a 5xx on a write:
the first attempt may have taken effect. Check whether it did (list the
documents), then repeat with a new key. error.idempotency_key tells you
which key was spent.
Pagination
list returns one page. list_all walks every page as you iterate:
for listed in fiz.invoices.list_all({"status": "ISSUED"}):
print(listed["number"])
OAuth apps
A registered app calls the API on behalf of the companies that installed it, with an OAuth access token:
fiz = Fiz(access_token=access_token)
Getting and refreshing the token is your app's part of the flow; see the partner guide.
Options
import httpx
fiz = Fiz(
api_key="fiz_…", # default: the FIZ_API_KEY environment variable
# access_token="…", # instead of api_key
base_url="https://api.fiz.co",
max_retries=2,
timeout=60.0, # per attempt, seconds
http_client=httpx.Client(), # proxies, custom transport; never follows redirects
app_info={"name": "my-shop", "version": "1.2.0"}, # added to the User-Agent
on_response=lambda r: print(r.operation_id, r.status, r.request_id), # every response
)
on_response is called with every response to an API operation, retries
included (the file download behind download_pdf is not an operation and is
not reported). It receives the operation, status, request_id, the
Idempotency-Key, whether the API replayed an earlier result, the attempt
number and the time to the response headers: enough to log the request id of
every invoice you issue. Whatever it raises is ignored.
Each method also takes per-call keyword options: idempotency_key,
max_retries, timeout and headers. Fiz is a context manager
(with Fiz() as fiz:) and has close(), which closes its connection pool.
Types
Request and response types come from the API's OpenAPI document. Named
aliases cover the common ones (Invoice, Customer, Item, Company, …);
every schema is in fiz_sdk.types, by its name in the document:
from fiz_sdk.types import CreateInvoiceDto, InvoiceItemDto
def invoice_for(customer_id: str, cae: str, lines: list[InvoiceItemDto]) -> CreateInvoiceDto:
return {"type": "INVOICE", "cae": cae, "customerId": customer_id, "items": lines}
The package ships py.typed; mypy and pyright check your requests and
responses against these types.
Coding agents
Using Claude Code, Cursor or Codex? Point the agent at
api.fiz.co/llms.txt: it routes the agent by
task and states the fiscal rules first. The FIZ connector for Claude and
ChatGPT is described at api.fiz.co/docs/mcp.
Development
With uv:
uv sync
uv run python scripts/update_spec.py # download https://api.fiz.co/-json and regenerate
./scripts/check.sh # lint, types, README examples, unit tests, build
FIZ_TEST_API_KEY=fiz_test_… uv run pytest -m sandbox
src/fiz_sdk/generated/ is generated from openapi/openapi.json
(uv run python scripts/generate.py); never edit it by hand. When the API
adds an operation, the tests fail until a resource method wraps it.
Releasing. Bump VERSION in src/fiz_sdk/version.py and add the version
to CHANGELOG.md, merge, and push a tag (git tag v0.1.1 && git push origin v0.1.1): the Release workflow runs the checks, builds, and publishes to PyPI
through trusted publishing, with no token. One-time setup is at the top of
.github/workflows/release.yml.
Português
Faturação certificada em Portugal a partir do seu código. O FIZ é um programa de faturação certificado pela AT (n.º 3041): numera cada documento na série, junta o ATCUD e o código QR, comunica-o à AT no momento da emissão e devolve o número e o PDF. Este é o cliente oficial da API FIZ para Python.
pip install fiz-sdk
- Crie uma chave API em app.fiz.co → Definições → Integrações
e guarde-a em
FIZ_API_KEY. Uma chavefiz_test_usa o sandbox: serviços de teste da AT, sem efeito fiscal. - Siga o exemplo do Quickstart com uma chave de sandbox: cliente e artigo → rascunho e PDF → emissão. Um rascunho não tem efeito fiscal; com uma chave de produção, a emissão é irreversível e comunicada à AT.
- Cada escrita leva uma
Idempotency-Key, reutilizada nas repetições automáticas: um timeout nunca dá origem a uma fatura duplicada.
Os erros trazem status, code e request_id (indique-o ao suporte). Guia
completo em api.fiz.co/docs/quickstart?lang=pt.
License
MIT
Metadata
Release files for fiz-sdk 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fiz_sdk-0.1.0.tar.gz | 48.8 kB | With provenance | Details for fiz_sdk-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fiz_sdk-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for fiz_sdk-0.1.0-py3-none-any.whl |
Total release size: 104.0 kB
Release files / fiz_sdk-0.1.0.tar.gz
| Download URL | fiz_sdk-0.1.0.tar.gz |
|---|---|
| Size | 48.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0ed9edb18d1c1244d1234b6c62596b002de0305abc14f16e3fa21d2316203207
|
|
BLAKE2b-256 checksum How to use checksums |
6499c26ebcf7714eb967ef1d00e87408a9dd0baa54122fdfa9d3f62ca7d08a0a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logRelease files / fiz_sdk-0.1.0-py3-none-any.whl
| Download URL | fiz_sdk-0.1.0-py3-none-any.whl |
|---|---|
| Size | 55.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9925d3a1fa5cac9800cfdc0f10bfa2754e879d1bc078d00b0f14ec08454cebb8
|
|
BLAKE2b-256 checksum How to use checksums |
5bdb4b5f674dbf2e4922335b90e661c8e8d1f106608935d6cbb7553d1842b7b2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logSecurity for fiz-sdk 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for fiz_sdk-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.