# Official client libraries: TypeScript, Python and PHP

> Markdown edition of https://api.fiz.co/docs/libraries. Português: https://api.fiz.co/docs/libraries.md?lang=pt. Index: https://api.fiz.co/llms.txt

Issue certified invoices in Portugal from your code with an official FIZ library: typed requests and responses, an Idempotency-Key on every write, retries that never issue twice, and errors you can branch on.

## TypeScript

Node.js 20.3 or later, server-side only. Also for JavaScript.

[npm: `@fiz-co/sdk`](https://www.npmjs.com/package/@fiz-co/sdk) · [source and README (GitHub)](https://github.com/FIZ-co/fiz-sdk-js)

```shell
npm install @fiz-co/sdk
```

The first requests: the company, a customer, an item, a draft and its PDF. Issuing is left commented out: it is fiscal and final.

```ts
import { Fiz } from '@fiz-co/sdk';

const fiz = new Fiz(); // reads FIZ_API_KEY

const company = await fiz.company.retrieve();
const cae = company.cae[0];
if (!cae) throw new Error('Add the company activity (CAE) in FIZ first.');

const customer = await fiz.customers.create({ name: 'Example customer', country: 'PT' });
const item = await fiz.items.create({ name: 'Example service', type: 'SERVICE', unitPrice: 10, vatRate: 'NORMAL' });
const draft = await fiz.invoices.create({
  type: 'INVOICE',
  cae,
  customerId: customer.id,
  items: [{ id: item.id, quantity: 1 }],
});
const pdf = await fiz.invoices.downloadPdf(draft.id); // the PDF bytes

// Issuing is fiscal and irreversible: do it after reviewing the PDF, with the
// revision you reviewed. Without a revision, do not issue.
// if (!draft.updatedAt) throw new Error('No revision');
// await fiz.invoices.issue(draft.id, { expectedUpdatedAt: draft.updatedAt });
```

## Python

Python 3.10 or later; built on httpx, typed with TypedDict.

[PyPI: `fiz-sdk`](https://pypi.org/project/fiz-sdk/) · [source and README (GitHub)](https://github.com/FIZ-co/fiz-sdk-python)

```shell
pip install fiz-sdk
```

The first requests: the company, a customer, an item, a draft and its PDF. Issuing is left commented out: it is fiscal and final.

```python
from fiz_sdk import Fiz

fiz = Fiz()  # reads FIZ_API_KEY

company = fiz.company.retrieve()
if not company["cae"]:
    raise SystemExit("Add the company activity (CAE) 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}],
    }
)
pdf = fiz.invoices.download_pdf(draft["id"])  # the PDF bytes

# Issuing is fiscal and irreversible: do it after reviewing the PDF, with the
# revision you reviewed. Without a revision, do not issue.
# if not draft["updatedAt"]: raise SystemExit("No revision")
# fiz.invoices.issue(draft["id"], {"expectedUpdatedAt": draft["updatedAt"]})
```

## PHP

PHP 8.1 or later; Guzzle 7 by default, any PSR-18 client; PHPStan array shapes.

[Packagist: `fiz-co/sdk`](https://packagist.org/packages/fiz-co/sdk) · [source and README (GitHub)](https://github.com/FIZ-co/fiz-sdk-php)

```shell
composer require fiz-co/sdk
```

The first requests: the company, a customer, an item, a draft and its PDF. Issuing is left commented out: it is fiscal and final.

```php
<?php
require 'vendor/autoload.php';

use Fiz\Fiz;

$fiz = new Fiz(); // reads FIZ_API_KEY

$company = $fiz->company->retrieve();
$cae = $company['cae'][0] ?? null;
if ($cae === null) {
    throw new RuntimeException('Add the company activity (CAE) in FIZ first.');
}

$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]],
]);
$pdf = $fiz->invoices->downloadPdf($draft['id']); // the PDF bytes

// Issuing is fiscal and irreversible: do it after reviewing the PDF, with the
// revision you reviewed. Without a revision, do not issue.
// if ($draft['updatedAt'] === null) throw new RuntimeException('No revision');
// $fiz->invoices->issue($draft['id'], ['expectedUpdatedAt' => $draft['updatedAt']]);
```

## What every library does

-   **Typed from the OpenAPI document.** Every operation of the API, with its request and response types; a new operation reaches the libraries with the next release.
-   **An `Idempotency-Key` on every write**, generated unless you pass one, and reused by every automatic retry of that call: a timeout never costs you a second invoice. Pass your own key (your order id, say) to make a retry from your queue safe too, within the 30 days a key is kept: before retrying anything older, check whether the first attempt took effect. [How idempotency works](https://api.fiz.co/docs/api/overview#idempotency).
-   **Retries that follow the API's rules:** a 429 and a write still in progress wait for `Retry-After`, up to 60 seconds (a longer wait is raised as the error, for your code to schedule); reads are retried after a 502, 503 or 504; a write whose outcome is unknown is not repeated blindly.
-   **Errors as exceptions.** An error response raises `FizApiError` (`FizApiException` in PHP), or a subclass per status, with the status, the messages, the API's `code` when it sent one (a refusal by the invoicing system; a `400` from request validation has none) and the `X-Request-Id` to quote to support. No response at all (a timeout, a dropped connection) raises `FizConnectionError` or `FizTimeoutError` (`…Exception` in PHP): no status there, but the `Idempotency-Key` to retry the write with. A file download that fails at the host storing the file (the PDF behind its link) raises the base `FizError` (`FizException` in PHP), with neither: catch that one too around a download. [Error format](https://api.fiz.co/docs/api/overview#errors).
-   **The sandbox by the key alone.** A `fiz_test_` key reaches the [sandbox](https://api.fiz.co/docs/api/overview#sandbox) (AT test services, no fiscal effect); every other key and OAuth token reaches production. The client tells you which (`environment`).
-   **Credentials stay with the API.** The libraries never follow a redirect with your key, and a PDF stored on another host is downloaded without it. In PHP, an HTTP client of your own other than Guzzle (any PSR-18 client) keeps its own redirect settings: turn its automatic redirects off.
-   **The key from `FIZ_API_KEY`** by default, the variable every snippet of these docs reads; or an OAuth access token for a registered app.

## Any other language

Generate a client from the OpenAPI document at [`/-json`](https://api.fiz.co/-json) (or [`/-yaml`](https://api.fiz.co/-yaml)) with the generator you already use. Every response, errors included, is described there. Send an `Idempotency-Key` header on every write and reuse it when you retry the same call; the [quickstart](https://api.fiz.co/docs/quickstart) shows each request with curl.

## Versions and updates

The libraries follow [semantic versioning](https://semver.org). Each one checks the API document every day and its release brings the new operations and fields; what changed in the API itself, and since when, is in the [API changelog](https://api.fiz.co/docs/changelog). Every release is approved by a FIZ maintainer before it is published.
