# Mast API: guide

The Mast API lets your own systems work with your company's books in Mast: your back office makes
customers, products and invoices and keeps your suppliers, and your reporting tools read invoices,
payments, the ledger and the bank lines. This page says how the API works as a whole. Every call, field by field, is in the
[reference](https://mastfinance.io/developers/reference.md); the same contract for machines is [`openapi.v1.json`](https://mastfinance.io/developers/openapi.v1.json); an
AI assistant connects through [MCP](https://mastfinance.io/developers/mcp.md).

| | |
|---|---|
| Base address | `https://api.mastfinance.io/api/v1` |
| Format | JSON over HTTPS |
| Authentication | An API key of your company: `Authorization: Bearer mast_sk_…` |
| Data location | Switzerland (Zurich), as the rest of Mast |

## Getting a key

The API is opened account by account. Once it is open for yours:

1. An owner or an administrator of the account opens **Settings › API Keys** in Mast and chooses
   **Create a key**. Mast asks them to have set up two-factor authentication (an authenticator app)
   first.
2. They name the key (« Back office »), choose the **role** whose rights it will hold, and its expiry.
   They can only give it a role whose rights they hold themselves. The page proposes an expiry in one
   year, and offers 30 days, 90 days or never: Mast sets no expiry of its own, so a key made with
   « Never » has none (`expiresAt` is `null`).
3. Mast shows the key **once**. Keep it where your system keeps its secrets. Mast stores only a
   fingerprint of it and cannot show it again.

A key belongs to **one company** and acts in that company only. It can do what its role can do, and
nothing else: a key for a reporting tool takes a role that only reads. A company can have up to 20
live keys; give each system its own, so that one can be revoked without stopping the others. Revoking
a key in Settings stops it at once: every call reads the key afresh. Settings shows when each key was
last used, to within five minutes.

Mast opens the API for the whole account, and can close it again. Once it is closed, every key of the
account is refused (`403 PUBLIC_API_NOT_ENABLED`) within a minute, since each of Mast's servers reads
that setting again every 60 seconds; the keys are kept, and work again if the API is reopened.

Roles and their rights are set under **Settings › User & Permissions**. This guide names each right
as that page does: the feature (« Customer Invoices »), then the column (« Read », « Create »,
« Edit », « Post », « Delete »).

Check a new key with the one call that asks no right:

```bash
curl -s https://api.mastfinance.io/api/v1/ext/me -H "Authorization: Bearer $MAST_API_KEY"
```

```json
{
  "key": { "id": "…", "name": "Back office", "displayPrefix": "mast_sk_a1B2c3", "roleName": "Invoicing", "expiresAt": "2027-11-19T00:00:00.000Z" },
  "company": { "id": "…", "name": "Muster Handel AG" }
}
```

## From your back office to an invoice

Your back office knows your customers, their terms, your products and what you sold. It sends that to
Mast, which makes compliant invoices of it, numbers them, books them and sends them. The whole path is
six calls:

| Step | Call | Right of the key's role |
|---|---|---|
| Keep your customers up to date | `PUT /ext/customers/{externalRef}` | Customer: Create and Edit |
| Keep your products up to date | `PUT /ext/products/{externalRef}` | Product: Create and Edit |
| Prepare a draft invoice | `POST /ext/invoices` | Customer Invoices: Create |
| Correct it, or drop it | `PATCH` or `DELETE /ext/invoices/{externalRef}` | Customer Invoices: Edit, Delete |
| Issue it | `POST /ext/invoices/{externalRef}/validate` | Customer Invoices: Post |
| E-mail it to the customer | `POST /ext/invoices/{externalRef}/send` | Customer Invoices: Post |

To read back what it made, the key also needs « Read » on those three features. To follow the
payments (`GET /ext/payments`), it needs « Read » on « Cash Allocation », the one listed under
**Sales & Invoicing**: reading the invoices does not give it, and the « Cash allocation » under
**Purchases & Bills** is another feature.

Everywhere, `{externalRef}` is **your** id: the one your back office already gives this customer,
this product, this invoice. There is no id of Mast's to store.

The examples below are one scenario. Their figures are the ones Mast really answers: an automated test
plays this scenario at every release.

### Your customers, with their terms

One call makes the customer when it does not exist yet under your id, and changes it otherwise. Your
sync does not have to know whether Mast already holds it.

Does Mast already hold customers or products that a person made, or imported? Read « You already
have customers or products in Mast », below, first: they do not carry your id yet, and this call
would not find them.

```bash
curl -s -X PUT https://api.mastfinance.io/api/v1/ext/customers/crm-1042 \
  -H "Authorization: Bearer $MAST_API_KEY" -H "Content-Type: application/json" \
  -d '{
    "type": "business",
    "companyName": "Muster Handel AG",
    "email": "compta@muster-handel.example",
    "address": { "street": "Bahnhofstrasse 1", "postalCode": "8001", "city": "Zürich" },
    "language": "fr",
    "defaultDiscountPercent": 10,
    "paymentTermsDays": 20
  }'
```

Mast answers `201` the first time (the customer is made) and `200` after that (it is changed), with
the customer as it holds it:

```json
{
  "id": "cmwnsw2nz00a16muqe2qwffsl",
  "externalRef": "crm-1042",
  "number": "CUST-00046",
  "type": "business",
  "name": "Muster Handel AG",
  "email": "compta@muster-handel.example",
  "address": { "street": "Bahnhofstrasse 1", "postalCode": "8001", "city": "Zürich", "country": "Switzerland", "countryCode": "CH" },
  "language": "fr",
  "defaultDiscountPercent": 10,
  "paymentTermsDays": 20,
  "…": "…"
}
```

- **Its terms.** `defaultDiscountPercent` is the discount Mast keeps for this customer, and
  `paymentTermsDays` its payment terms in days. An invoice that names no terms takes the customer's.
  Its discount is applied only when the invoice asks for it (see the draft, below).
- **A company or a person.** `type` is `business` (named by `companyName`) or `individual` (named by
  `firstName` and `lastName`).
- **Its language** (`de`, `fr`, `it`, `en`) is the one its invoices and reminders are written in.
- **Making takes the whole, changing only what changes.** For a new customer the call gives its type,
  its name, its e-mail address and its postal address. After that it may send only what changes:
  `{ "paymentTermsDays": 30 }` changes the terms and leaves the rest. A field that may be empty (the
  phone, the VAT number, the register number) is cleared when sent as `null`; the reference says,
  field by field, which take `null`.
- **A field Mast does not know is dropped**, without a word: `{ "paymentTermDays": 30 }`, misspelt,
  changes nothing and still answers `200`. Compare the answer with what you sent (« Conventions »).
- The country, when left out, is your company's own. `number` is Mast's own customer number.

### You already have customers or products in Mast

A customer or a product that a person made in Mast, or imported, has Mast's id only: its
`externalRef` is `null`. Until it carries yours, your `PUT` does not find it. So before your first
sync, link what Mast already holds to your own records. If your account is new, go on to « Your
products ».

**Read what Mast holds.** The list serves every customer of the company, yours and the ones made in
Mast, each with both ids:

```bash
curl -s https://api.mastfinance.io/api/v1/ext/customers -H "Authorization: Bearer $MAST_API_KEY"
```

```json
{
  "data": [
    {
      "id": "cmwo41w8100a3xtuqh7n7fnpc",
      "externalRef": null,
      "number": "CUST-00010",
      "type": "business",
      "name": "Beispiel Technik GmbH",
      "email": "info@beispiel-technik.example",
      "address": { "street": "Lagerstrasse 12", "postalCode": "4051", "city": "Basel", "country": "Switzerland", "countryCode": "CH" },
      "vatNumber": "CHE-123.456.789 MWST",
      "registrationNumber": null,
      "…": "…"
    }
  ],
  "nextCursor": null
}
```

**Match them on your side.** To recognise a customer, each row gives its number in Mast (`number`),
its name (`name`, with `companyName` or `firstName` and `lastName` by its `type`), its VAT number
(`vatNumber`), its commercial-register number (`registrationNumber`), its e-mail address (`email`),
its phone (`phone`) and its address (`address`). For a product (`GET /ext/products`): its number
(`number`), its name (`name`), its code (`code`), its price (`unitPrice`, `currency`) and its unit
(`unit`). Your system decides that two records are the same: Mast never matches two customers or two
products on their name.

**Give each one your id**, naming it by Mast's id:

```bash
curl -s -X PATCH https://api.mastfinance.io/api/v1/ext/customers/by-id/cmwo41w8100a3xtuqh7n7fnpc \
  -H "Authorization: Bearer $MAST_API_KEY" -H "Content-Type: application/json" \
  -d '{ "externalRef": "crm-0318" }'
```

Mast answers `200` with the customer, which now carries your id:

```json
{
  "id": "cmwo41w8100a3xtuqh7n7fnpc",
  "externalRef": "crm-0318",
  "number": "CUST-00010",
  "type": "business",
  "name": "Beispiel Technik GmbH",
  "…": "…"
}
```

Nothing else of the customer changes. From then on `PUT /ext/customers/crm-0318` changes it, as
above, and your invoices name it by `customerExternalRef`. A product is linked the same way, with
`PATCH /ext/products/by-id/{id}`; an invoice line then names it by `productExternalRef`.

- **Repeating the call does nothing more.** Sending the id the record already carries answers `200`
  and writes nothing.
- **One id names one record.** If another customer of the company already carries it, the call
  answers `409 EXT_CUSTOMER_EXISTS` (`EXT_PRODUCT_EXISTS` for a product). If a customer deleted in
  Mast carries it, where it stays archived, the call answers `409 EXT_CUSTOMER_ARCHIVED`: restore
  that customer in Mast, or take another id.
- **A wrong link is undone.** Send `{ "externalRef": null }`: the record has Mast's id only again,
  and yours is free for the right one. Sending another id replaces the old one directly.
- **The list comes back to what you link.** A record you link has just changed: if you are reading
  the list page by page at the same time, it comes again further down, this time with your id.
- **Rights of the key.** « Read » to read the list, « Edit » to link.

**If you skip this step**, your first `PUT` finds nothing under your id and sets out to make the
record. For a customer, Mast refuses (`409 CUSTOMER_NAME_EXISTS`) when a customer of the company has
the same name, the same billing address and the same e-mail address, all three; as soon as one of
them differs, it makes a second customer beside the first. A product is always made a second time.
To put a double right, take your id away from it first (`{ "externalRef": null }`), give it to the
right record, then delete the double in Mast. In that order: a record deleted in Mast stays archived
there, and keeps the id it carried.

**Checking that both sides say the same.** A list read with `updatedSince` returns everything that
changed in Mast since an instant, whether the change came from your back office or from a person in
Mast. A nightly comparison is therefore one call per list:

```bash
curl -s "https://api.mastfinance.io/api/v1/ext/customers?updatedSince=2026-11-18T22:00:00Z" \
  -H "Authorization: Bearer $MAST_API_KEY"
```

Each row carries both ids, all its fields and `updatedAt`, the instant of its last change: compare
them with yours. A row whose `externalRef` is `null` is a customer you have not linked yet, which a
person has just made or changed in Mast. « Reading what changed », below, gives the method page by
page.

A `PUT` moves `updatedAt` even when it changes nothing: a sync that sends every customer again each
night has every one of them come back in its next read by `updatedSince`, and a change a person made
in Mast is lost among them. Send only what changed on your side, or compare with what Mast holds
before you send.

A deletion does not show there: a customer deleted in Mast drops out of the list. Reading it by your
id then answers `404 EXT_CUSTOMER_NOT_FOUND`, and a `PUT` that sends it whole again
`409 EXT_CUSTOMER_ARCHIVED`.

### Your products

The same as for your customers, one call per product:

```bash
curl -s -X PUT https://api.mastfinance.io/api/v1/ext/products/sku-conseil \
  -H "Authorization: Bearer $MAST_API_KEY" -H "Content-Type: application/json" \
  -d '{ "type": "service", "name": "Conseil", "code": "CONSEIL", "unitPrice": 180, "unit": "h", "vatRateCode": "CH_STD" }'

curl -s -X PUT https://api.mastfinance.io/api/v1/ext/products/sku-manuel \
  -H "Authorization: Bearer $MAST_API_KEY" -H "Content-Type: application/json" \
  -d '{ "type": "good", "name": "Manuel", "code": "MANUEL", "unitPrice": 19.90, "unit": "pcs", "vatRateCode": "CH_RED" }'
```

- `unitPrice` is the selling price without VAT. It is a default: an invoice line can always give its
  own.
- `vatRateCode` is one of your company's VAT codes, as **Settings › VAT** lists them. In a Swiss
  company `CH_STD` is the standard rate (8.1 %) and `CH_RED` the reduced rate (2.6 %). Mast answers
  the rate beside the code (`vatRatePercent`).
- `accountCode`, optional, is the revenue account of your chart this product is booked to. Without
  it, Mast takes the company's default sales account.

### A draft invoice

```bash
curl -s -X POST https://api.mastfinance.io/api/v1/ext/invoices \
  -H "Authorization: Bearer $MAST_API_KEY" -H "Content-Type: application/json" \
  -d '{
    "externalRef": "bo-2026-0457",
    "customerExternalRef": "crm-1042",
    "issueDate": "2026-11-19",
    "reference": "PO-7781",
    "applyCustomerDefaultDiscount": true,
    "lines": [
      { "productExternalRef": "sku-conseil", "quantity": 12.5 },
      { "productExternalRef": "sku-manuel", "quantity": 3, "discountPercent": 20 },
      { "description": "Frais de déplacement", "quantity": 1, "unitPrice": 85, "vatRateCode": "CH_STD" }
    ]
  }'
```

Mast answers `201` with the draft, its lines and its computed totals:

```json
{
  "id": "cmwnsw2sf00a76muqm4kto1cu",
  "externalRef": "bo-2026-0457",
  "documentNumber": "Draft-INV-2026-00043",
  "status": "draft",
  "customerExternalRef": "crm-1042",
  "issueDate": "2026-11-19",
  "dueDate": "2026-12-09",
  "currency": "CHF",
  "subtotal": 2382.76,
  "discountPercent": 10,
  "discountAmount": 238.28,
  "netAmount": 2144.48,
  "vatAmount": 171.34,
  "total": 2315.82,
  "amountDue": 2315.82,
  "vatRows": [
    { "ratePercent": 8.1, "netAmount": 2101.5, "vatAmount": 170.22 },
    { "ratePercent": 2.6, "netAmount": 42.98, "vatAmount": 1.12 }
  ],
  "lines": [
    { "position": 1, "description": "Conseil", "quantity": 12.5, "unit": "h", "unitPrice": 180, "discountPercent": null, "netAmount": 2250, "vatRatePercent": 8.1, "…": "…" },
    { "position": 2, "description": "Manuel", "quantity": 3, "unit": "pcs", "unitPrice": 19.9, "discountPercent": 20, "netAmount": 47.76, "vatRatePercent": 2.6, "…": "…" },
    { "position": 3, "description": "Frais de déplacement", "quantity": 1, "unit": "pcs", "unitPrice": 85, "discountPercent": null, "netAmount": 85, "vatRatePercent": 8.1, "…": "…" }
  ],
  "…": "…"
}
```

**A line** names a product (`productExternalRef`) and then takes its name, price, unit and VAT rate,
except the ones it gives itself. Or it stands alone, with its description, its price and its rate. A
price agreed with this customer is simply the `unitPrice` sent on the line. A product's price is
taken as the number it is, in the invoice's currency: a product priced 100 in EUR gives a line of
100.00 on an invoice in CHF. Mast converts nothing and refuses nothing there, so a line of an
invoice in another currency than its product's gives its own `unitPrice`.

**Discounts.** Mast applies no discount the call does not ask for. There are three, taken in this
order:

| Discount | Field | In the example |
|---|---|---|
| On a line | the line's `discountPercent` | 20 % on the manuals: 59.70 becomes 47.76 |
| On the whole invoice | the invoice's `discountPercent` or `discountAmount`, never both | (not used) |
| The customer's own | `applyCustomerDefaultDiscount: true`, when the call names no discount on the invoice | 10 % of 2,382.76, that is 238.28 |

A `discountAmount` above what the lines come to is not refused: Mast takes it as the whole of the
lines, the invoice comes to 0.00, and it can be issued so. Check the `total` Mast answers.

**Totals.** `subtotal` is the lines after their own discounts. `netAmount` is what the invoice bills
without VAT, `vatAmount` its VAT and `total` what the customer owes. `vatRows` gives the VAT per rate
as the PDF prints it: its rows add up exactly to `vatAmount`. Use these figures rather than computing
them again. An invoice whose total would fall below zero is refused (`400 INVOICE_TOTAL_NEGATIVE`):
an invoice bills, and an amount is taken back by a credit note, made in Mast.

**The rest.** With no `issueDate` the invoice is dated today. With no `dueDate` and no
`paymentTermsDays`, the due day comes from the customer's terms (20 days here). `reference` is your
customer's own reference (an order number), printed on the invoice. `title`, `introText`, `notes` and
`footerText` are the document's free texts. `priceIncludesVat: true` says your prices include VAT.
`currency` and `language`, left out, are the company's and the customer's.

A draft has **no official number and no journal entry**. You can read it, show it, correct it.
Nothing is owed yet.

### Correcting or dropping a draft

While the invoice is a draft, correct it: the fields sent replace the draft's, and `lines` replaces
every line.

```bash
curl -s -X PATCH https://api.mastfinance.io/api/v1/ext/invoices/bo-2026-0457 \
  -H "Authorization: Bearer $MAST_API_KEY" -H "Content-Type: application/json" \
  -d '{ "lines": [
        { "productExternalRef": "sku-conseil", "quantity": 14 },
        { "productExternalRef": "sku-manuel", "quantity": 3, "discountPercent": 20 },
        { "description": "Frais de déplacement", "quantity": 1, "unitPrice": 85, "vatRateCode": "CH_STD" }
      ] }'
```

With 14 hours in place of 12.5, the draft comes to 2,387.48 without VAT and 2,578.50 with it: the
customer's discount still applies. A change of discount or of `priceIncludesVat` reprices the whole
invoice, so it comes with the lines. A change is taken whatever the total comes to: a draft brought
below zero is refused when it is issued (`400 INVOICE_TOTAL_NEGATIVE`), and stays a draft.

Or, instead, drop the draft: it is gone, and its id is free again. Do not run this one to follow the
scenario, which issues the draft next.

```bash
curl -s -X DELETE https://api.mastfinance.io/api/v1/ext/invoices/bo-2026-0457 \
  -H "Authorization: Bearer $MAST_API_KEY"
```

An **issued** invoice is no longer changed or deleted (`409 EXT_INVOICE_NOT_DRAFT`): it is corrected
by a credit note, made in Mast.

### Issuing the invoice

```bash
curl -s -X POST https://api.mastfinance.io/api/v1/ext/invoices/bo-2026-0457/validate \
  -H "Authorization: Bearer $MAST_API_KEY" \
  -H "Idempotency-Key: issue-bo-2026-0457"
```

The invoice takes its **official number** in your company's series (`INV-2026-00014`) and its
**journal entry**, under the key's name. Its `status` goes from `draft` to `open`, and it now counts
in what you invoiced (`invoicedNetAmount`).

- **It is final.** The API does not cancel an issued invoice; a credit note corrects it, in Mast.
- **Issuing twice does nothing more.** A repeat answers the same invoice: one number, one entry. Send
  an `Idempotency-Key` all the same (see « Doing something once »): after a network fault, the repeat
  is answered exactly what the first call was.
- **Your books can refuse.** A closed period, for one, refuses the issue with the code the app itself
  shows. The invoice then stays a draft.

### Sending it to the customer

```bash
curl -s -X POST https://api.mastfinance.io/api/v1/ext/invoices/bo-2026-0457/send \
  -H "Authorization: Bearer $MAST_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: send-bo-2026-0457" \
  -d '{}'
```

Mast sends the invoice as a PDF **by the sender your company chose** under **Settings › Email
Configuration**: its own Microsoft 365 mailbox, or, where Mast offers it to your account, Mast itself
in your company's name. It goes to the customer's address, in the words of your « invoice sent »
template in the customer's language. A draft is issued on its way out, so the send can be your only
call after the creation.

- To write to another address, give `recipient` (and `ccRecipient` for a copy). For words of your
  own, give `subject` and `message`: each replaces the template's, and with both no template is
  needed. They go in a body sent as JSON: sent any other way, the call is refused
  (`415 EXT_JSON_BODY_REQUIRED`) and nothing is sent.
- The answer holds the invoice as it stands after the send, who it went to, and `deduplicated`:
  `true` when a send to the same addresses (`recipient` and `ccRecipient`) went out less than a minute
  before, in which case no second e-mail is sent. A send made while another send of the same invoice
  is still running is refused (`409 INVOICE_SEND_IN_FLIGHT`). After that minute, the same call sends
  the e-mail again: send an `Idempotency-Key` (« Doing something once »), so that a retry is answered
  what the first call was, and the customer receives one e-mail.
- **To set up once in Mast:** connect the company's Microsoft 365 mailbox, or choose « By Mast, in
  your company's name » where it is offered (**Settings › Email Configuration**), and check the
  e-mail template (**Settings › Templates & Reminders**). Without a mailbox, and with no other
  sender offered, the call answers `503 EMAIL_NO_ACCOUNT_CONNECTED`; without a template or words of
  your own, `422 EXT_INVOICE_EMAIL_TEMPLATE_MISSING`; with the e-mailing of invoices turned off in the
  company's settings, `403 INVOICE_EMAIL_SENDING_DISABLED_YOUR_ORGANIZATION_SETTINGS`. A cancelled
  invoice is never sent (`400 INVOICE_CANCELLED_CANNOT_BE_SENT`). Everything that can refuse the send
  is checked before anything is issued: a refused send leaves the draft as it was. The reference
  lists every refusal of the call, those of Mast sending in your name included.
- If the mailbox then does not take the e-mail, the call answers `502 EXT_INVOICE_SEND_FAILED`: the
  invoice is issued by then, and the e-mail not sent. The answer does not say what the mailbox
  answered; the call can be made again.
- Rather send it yourself? Issue it, fetch the PDF and attach it to your own e-mail.

### Fetching the PDF

```bash
curl -s https://api.mastfinance.io/api/v1/ext/invoices/bo-2026-0457/pdf \
  -H "Authorization: Bearer $MAST_API_KEY" -o invoice-bo-2026-0457.pdf
```

It is the document your customer receives, with its QR-bill for a Swiss company. A key gets one
PDF at a time: a call made while another PDF it asked for is still being made is answered
`429 RATE_LIMITED` with `Retry-After`, so fetch them one after the other. Such a call counts in the
minute's limit all the same (« Rate limits »).

### Following the payment

```bash
curl -s https://api.mastfinance.io/api/v1/ext/invoices/bo-2026-0457 -H "Authorization: Bearer $MAST_API_KEY"
```

`status` says where the invoice stands, `amountPaid` what was received and `amountDue` what is still
owed:

| `status` | What it means |
|---|---|
| `draft` | A draft: no official number, no journal entry |
| `open` | Issued, nothing received, not due yet |
| `overdue` | Issued, nothing received, past its due day |
| `partially_paid` | Something received, something still owed |
| `paid` | Settled |
| `cancelled` | Cancelled: its entry is reversed, nothing is owed |

Three more values (`paid_in_provider`, `refunded_in_provider`, `paid_outside_provider`) only concern
invoices issued by a payment provider connected to Mast.

Payments are recorded in Mast, mostly by reconciling your bank statements. The API hands them back,
to a key whose role reads « Cash Allocation » (under **Sales & Invoicing**):

```bash
# The payments of one invoice
curl -s "https://api.mastfinance.io/api/v1/ext/payments?invoiceExternalRef=bo-2026-0457" \
  -H "Authorization: Bearer $MAST_API_KEY"

# Everything that moved since your last read, to bring your back office up to date
curl -s "https://api.mastfinance.io/api/v1/ext/invoices?updatedSince=2026-11-19T06:00:00Z" \
  -H "Authorization: Bearer $MAST_API_KEY"
```

The second read, run regularly, is enough to keep the state of your invoices current in your back
office (« Reading what changed », below, gives the method). One thing to know: an invoice that becomes
`overdue` does not change in Mast, so it is not served again for that. `overdue` is judged on the day
of the read, from `dueDate`.

### What is done in Mast, and not by the API

- **Credit notes.** The API reads them (`GET /ext/credit-notes`), each with the invoice it corrects.
  They are made in Mast.
- **Recording payments**, by bank reconciliation.
- **Payment reminders**, which Mast sends as your company's settings say.
- **Where a supplier is paid.** The API makes and changes your suppliers (« Your suppliers »,
  below), never their bank account: a person enters it in Mast, on the supplier's card.
- **Notifications.** The API does not call you when something changes: read the lists by
  `updatedSince`, at your own pace.

### Your suppliers

Your back office, or the purchasing tool your company orders through, keeps your suppliers in Mast
the way it keeps your customers: one call per supplier, under your own id, which makes it the first
time and changes it after. Suppliers are not part of the path to an invoice; a key that keeps them
needs « Supplier » rights only.

| To | Call | Right of the key's role |
|---|---|---|
| Keep a supplier up to date | `PUT /ext/suppliers/{externalRef}` | Supplier: Create and Edit |
| Read one by your id | `GET /ext/suppliers/{externalRef}` | Supplier: Read |
| Read them all, or what changed | `GET /ext/suppliers` | Supplier: Read |
| Give a supplier made in Mast your id | `PATCH /ext/suppliers/by-id/{id}` | Supplier: Edit |

```bash
curl -s -X PUT https://api.mastfinance.io/api/v1/ext/suppliers/erp-7001 \
  -H "Authorization: Bearer $MAST_API_KEY" -H "Content-Type: application/json" \
  -d '{
    "name": "Muster Bureau AG",
    "email": "compta@muster-bureau.example",
    "address": { "street": "Musterweg 3", "postalCode": "3000", "city": "Bern" },
    "vatStatus": "registered",
    "vatNumber": "CHE-123.456.788 MWST",
    "paymentTermsDays": 30
  }'
```

Mast answers `201` the first time (the supplier is made) and `200` after that (it is changed), with
the supplier as it holds it:

```json
{
  "id": "cmwp2k7rx00b4suqf0a9c3lzd",
  "externalRef": "erp-7001",
  "number": "SUPP-00012",
  "name": "Muster Bureau AG",
  "businessType": "corporation_company",
  "email": "compta@muster-bureau.example",
  "address": { "street": "Musterweg 3", "postalCode": "3000", "city": "Bern", "country": "Switzerland" },
  "vatStatus": "registered",
  "vatNumber": "CHE123456788",
  "currency": "CHF",
  "paymentTermsDays": 30,
  "…": "…"
}
```

- **Making takes its name and its VAT status.** `vatStatus` is `registered` for a supplier
  registered for VAT in your company's country, `foreign_registered` for one registered there from
  abroad, each with its number in `vatNumber`; `not_registered` or `foreign_not_registered` for
  one that is not, with no number. Mast checks the number as your company's country writes it,
  keeps it compact and answers it so. A read can answer `unknown` for a supplier saved before Mast
  asked for the status; a call never writes it. After that, a call sends only what changes, and
  `null` clears a field that may be empty.
- **Left out, the company's own.** The country of an address that names none is your company's,
  the currency its bills default to is your company's base currency, its payment terms are 30 days
  and its legal form (`businessType`) is `corporation_company`.
- **Its phone** is written in its international form, `+` and its calling code first
  (`+41 44 000 00 00`): Mast does not guess the country of a national number, and refuses one
  (`422 VALIDATION_FAILED`). It keeps and answers the number without spaces (`+41440000000`).
- **One supplier per name.** As in Mast, two live suppliers of a company never share a name, an
  e-mail address or a phone number: the call answers `409 SUPPLIER_NAME_EXISTS`,
  `SUPPLIER_EMAIL_EXISTS` or `SUPPLIER_PHONE_EXISTS`. A supplier a person already made or imported
  in Mast is linked first, as a customer is (« You already have customers or products in Mast »,
  above): find it in `GET /ext/suppliers`, where its `externalRef` is `null`, give it your id with
  `PATCH /ext/suppliers/by-id/{id}` and `{ "externalRef": "erp-0042" }`, and your `PUT` then
  changes it. `null` takes the id away again.
- **Mast's own rules on the VAT status** answer `400` with codes of their own: a registered
  supplier without a number (`SUPPLIER_CH_VAT_NUMBER_REQUIRED`), a number its country does not
  write (`SUPPLIER_CH_VAT_NUMBER_FORMAT`, `SUPPLIER_CH_VAT_NUMBER_CHECKSUM`), a number beside a
  status that takes none (`SUPPLIER_CH_VAT_NUMBER_FORBIDDEN`: send `"vatNumber": null` with the
  new status). The codes are those the supplier's card in Mast meets.
- **Never its bank account.** The API does not write where a supplier is paid: not its IBAN, its
  bank or the account's holder, and not its accounting defaults, its categories or its blacklist
  mark either. A field naming one is dropped, as any field Mast does not know, and what the
  supplier held stays as it was. A key that could change where a supplier is paid could redirect a
  payment, so a person enters the bank account in Mast. The API does not serve it either.

## Conventions

- **Names** are in camelCase. A day is written `YYYY-MM-DD`; an instant is ISO 8601 in UTC
  (`2026-11-19T08:30:00.000Z`).
- **Amounts** are decimal numbers at the currency's two decimals, always beside their `currency`
  (ISO 4217). An amount in the company's base currency says so in its name.
- **Words that name a state or a kind** (`status`, `type`, `direction`) are lower case. New values can
  appear over time: treat one you do not know as you would treat « other », do not fail on it.
- **A field with no value is `null`**, never left out. New fields can appear in an answer at any
  time: ignore the ones you do not use.
- **Two ids.** Everything has Mast's own `id`. What your system makes also carries **your** id for
  it, `externalRef`, unique in the company, and is addressed by it
  (`/ext/invoices/{externalRef}`): you never have to store Mast's id to find your invoice again.
  What a person made in Mast has `externalRef: null`, and is read by Mast's id:
  `/ext/invoices/by-id/{id}`. A customer, a product or a supplier in that case is given your id by
  the same path (« You already have customers or products in Mast », « Your suppliers »).
- **No personal data in an `externalRef`.** Your id travels in the address of every call, and
  addresses are kept in logs, yours, Mast's and every proxy's between them. Use a number or a code
  (`crm-1042`), never a person's name or e-mail address.
- **A body is JSON, sent with `Content-Type: application/json`** (`application/json; charset=utf-8`
  too). A body sent with another type, or with none, is refused `415 EXT_JSON_BODY_REQUIRED`, and
  nothing is done: `curl -d` without the header sends `application/x-www-form-urlencoded`, for one.
  A call that takes no body (a read, issuing an invoice, a deletion) is sent without one, and is
  then never refused for its type.
- **A field Mast does not know is dropped**, without an error: a misspelt field name is not refused,
  it changes nothing. Read back what you wrote (every write answers the record as Mast holds it) and
  compare it with what you sent. One call is strict: giving your id by Mast's id
  (`PATCH /ext/…/by-id/{id}`) refuses any field but `externalRef`.
- **A query parameter a call does not know is ignored** the same way: `GET /ext/invoices?statut=paid`,
  misspelt, answers every invoice, as if no filter had been given. The reference lists each call's
  parameters.
- **Text is read without what it cannot mean.** Mast takes every NUL character (U+0000) out of the
  text of a body before it reads it, and writes a lone half of a UTF-16 surrogate pair as `�`
  (U+FFFD). Then each text field of a body (an `externalRef`, a code, a name) and each reference or
  id of a path is read without the spaces around it: `"crm-1042 "` is stored, and found, as
  `crm-1042`. A NUL in a path or a query string is refused (`422 VALIDATION_FAILED`).

## When a call is refused

A refused call answers its HTTP status and one JSON object:

```json
{
  "statusCode": 409,
  "error": "ConflictException",
  "message": "An invoice with this externalRef already exists in the company.",
  "code": "EXT_INVOICE_EXISTS",
  "timestamp": "2026-11-19T08:30:00.000Z",
  "path": "/api/v1/ext/invoices"
}
```

Branch on **`code`**, which is stable. `message` is English for a developer and may be reworded.
`details`, when there is one, says more (the fields a validation refused). The codes of each call are
in the reference, each with an example of the whole answer in `openapi.v1.json`; these can come from
any call:

| Status | Code | What to do |
|---|---|---|
| 422 | `VALIDATION_FAILED` | The request is not shaped as the call expects. `details.fieldErrors` names each field (`lines.0.quantity`) and why. Correct and send again |
| 400 | none | The body of the request is not valid JSON. This answer carries no `code` and no `x-request-id` (below) |
| 413 | `FILE_TOO_LARGE` | The body is over 1 MB (« request entity too large »), or its lists hold more than 20,000 elements in all. Mast read none of it and did nothing: send less in one call |
| 415 | `EXT_JSON_BODY_REQUIRED` | The body was not sent as JSON: another `Content-Type`, or none. Nothing was done. Send it again with `Content-Type: application/json` |
| 415 | `BAD_REQUEST` | Mast could not read the body: its `charset` is not a UTF one (« unsupported charset "LATIN1" »), or it came compressed (`Content-Encoding`), which Mast's firewall refuses before Mast sees it (below). Nothing was done. Send it uncompressed, in UTF-8 |
| 400 | `IDEMPOTENCY_KEY_INVALID` | On a call that writes: the `Idempotency-Key` is not 1 to 255 visible ASCII characters, or it was sent twice. Nothing was done |
| 401 | `API_KEY_REQUIRED`, `API_KEY_INVALID` | No key, or not a key Mast made: check the header |
| 401 | `API_KEY_REVOKED`, `API_KEY_EXPIRED` | Make a new key in Settings |
| 403 | `API_KEY_COMPANY_MISMATCH` | The request names another company than the key's, in an `x-company-id` header. A key acts in its own company and needs no such header: leave it out |
| 403 | `API_KEY_ROUTE_NOT_ALLOWED` | A key was sent to an address outside the API (`/api/v1/ext`): a key reaches the API only |
| 403 | `PUBLIC_API_NOT_ENABLED` | The API is not open for this account, or no longer is |
| 403 | `ACCESS_DENIED_ROLE_REQUIRED` | The key's role does not hold the right this call asks. Give the key another role, or the role that right |
| 403 | `SUBSCRIPTION_CANCELED_READ_ONLY`, `YOUR_FREE_TRIAL_EXPIRED`, `SUBSCRIPTION_REQUIRED`, `ORGANIZATION_PENDING_DELETION_READ_ONLY` and their like | Your Mast account is read-only for now: a call that writes is refused, a read answers. The account's owner sorts it out in Mast |
| 429 | `RATE_LIMITED` | Too many calls of this kind in a minute. Wait for the seconds `Retry-After` gives |
| 5xx | `INTERNAL_ERROR` or none | Mast failed. Try again later with the same `Idempotency-Key`; if it lasts, write to us with the `x-request-id` of the answer. A `503` with a code of its own names what is not set up in Mast, which no retry clears: `EMAIL_NO_ACCOUNT_CONNECTED`, for one, says the company has no mailbox to send its e-mails from (« Sending it to the customer ») |

A `RATE_LIMITED` has a second cause, in other words: an address that presents keys Mast does not
accept. Each call from one address with a key that is well formed (`mast_sk_…`, as Mast makes them)
but unknown, revoked or expired is counted; a value not shaped as a key is refused
`401 API_KEY_INVALID` and not counted. The first 31 such calls of a minute are answered `401` as
usual; from the next, every call from that address with a well-formed key is answered
`429 RATE_LIMITED`, with `Retry-After`, until the minute ends, whichever key it is. A key that called
successfully in the last ten minutes is usually still let through. Check that no forgotten system
still sends an old key.

A refusal of a call's own rule names no field today when it comes from Mast's own rules on a
customer, a product, a supplier or an invoice (`EXT_CUSTOMER_INVALID`, `EXT_PRODUCT_INVALID`,
`EXT_SUPPLIER_INVALID`, `EXT_INVOICE_INVALID`): compare what you sent with the reference.

### The headers of an answer

`openapi.v1.json` declares each of these headers (`components.headers`) on the answers that always
carry it: a client generated from it may rely on every header it is told of.

| Header | On which answers |
|---|---|
| `x-request-id` | Every answer of the application, refused or not, but the refusal of a body Mast could not read (the `400` above, the `413`, the `415 BAD_REQUEST`) and the firewall's answers (below). Quote it when you write to Mast about a call: it finds the call in our logs. You may send your own, letters, digits and `.` `_` `:` `-`, up to 128 characters: Mast answers with it |
| `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` | Every answer of a call the rate limit counted: once the key and its role's right are accepted, whatever comes after (a success, a `404`, a `409`, a `422`, the `429` of a PDF asked while another is being made). Not on an answer given before: a refused body Mast could not read, a `401`, the `403`s `API_KEY_COMPANY_MISMATCH`, `PUBLIC_API_NOT_ENABLED`, `ACCESS_DENIED_ROLE_REQUIRED` and `EXT_BANK_DATA_TWO_FACTOR_ACCOUNT`, the `415` `EXT_JSON_BODY_REQUIRED`; nor on the `429` of the limit itself, or of an address refused for the keys it presents |
| `Retry-After` | A `429` of a limit on calls (the rate limit, one PDF at a time, an address refused for its keys, the firewall): the seconds to wait. Not the `429 EMAIL_MAST_SENDER_DAILY_LIMIT` of a send, when Mast has sent the company's e-mails of the day in its name: sending resumes the next day |
| `idempotent-replayed: true` | A repeat answered from its `Idempotency-Key` |
| `x-idempotency-keys` | Every answer of a call that passed the checks of its key, its role and the rate limit: `accepted` while Mast honours `Idempotency-Key`, `unavailable` in the rare moment it cannot (a repeat is then run again: your `externalRef` still keeps it from making a second record) |

### Mast's firewall

In front of the API, a firewall answers some requests itself, before Mast sees them. Its answers carry
no `x-request-id` and no `X-RateLimit` header, and no `message`:

| Status | Body | When | What to do |
|---|---|---|---|
| 429 | `{"statusCode":429,"source":"waf-per-ip-rate-limit"}`, with `Retry-After: 60` | More than 8,000 requests from one IP address in 5 minutes, whatever the key | Wait for the seconds `Retry-After` gives. Several systems behind one address share this count |
| 403 | `{"statusCode":403,"code":"REQUEST_BLOCKED","source":"waf-blocked-request"}` | A request with no `User-Agent` header; a body or a query string whose text reads as SQL, as a path into the server's files (`../`), or as a URL holding an IP address; a script in the query string or the path; a query string over 8 KB; an address on Amazon's lists of known attackers | Send a `User-Agent` naming your system (`MyBackOffice/2.1`): most HTTP libraries send one, but not all. If a legitimate request is refused, write to Mast with the time, the call and the body |
| 415 | `{"statusCode":415,"source":"waf-compressed-request-body"}` | A request with a `Content-Encoding` header: Mast takes bodies uncompressed only | Send the body uncompressed, without the header |

## Doing something once

A network fault can leave you not knowing whether a call arrived. Two things make a retry safe.

- **Your own id decides.** A customer, a product, a supplier or an invoice is made under your
  `externalRef`, and the database itself refuses a second one under the same id (`409 …_EXISTS`). A
  retried creation can never make a duplicate.
- **`Idempotency-Key`.** Any call that writes may carry this header, a value of your own (1 to 255
  characters), unique per act. Within 24 hours, a repeat with the same key and the same request is
  answered exactly what the first was answered, with the header `idempotent-replayed: true`, and
  nothing is done twice. The same key with a different request is refused
  (`422 IDEMPOTENCY_KEY_REUSED`); a repeat that arrives while the first is still running is told to
  wait (`409 IDEMPOTENCY_REQUEST_IN_PROGRESS`). Use it for the calls that act: issuing an invoice,
  sending it.

## Rate limits

Limits are counted per key and per call, over a minute:

| Kind of call | A minute |
|---|---|
| Reading (lists, one record) | 300 |
| Computed reports and files (the trial balance, a PDF) | 60 |
| Writing (create, change, issue, send) | 60 |

An answer the limit counted says where you stand: `X-RateLimit-Limit`, `X-RateLimit-Remaining` and
`X-RateLimit-Reset` (the seconds until the minute ends); « The headers of an answer », above, says
which answers carry them. Past the limit, the answer is `429 RATE_LIMITED` with `Retry-After`
(seconds), and no `X-RateLimit` header. A PDF asked while another PDF of the key is still being made
(« Fetching the PDF ») is also answered `429 RATE_LIMITED` with `Retry-After`, but it is not the
limit's answer: the limit let that call through and counted it, so it carries the `X-RateLimit`
headers and takes one call of the minute's 60. In front of the API, Mast's firewall also counts every
request of one IP address: past 8,000 in 5 minutes, it answers `429` itself (« Mast's firewall »).
These limits are a guard against a loop, not a quota: a nightly sync or a few hundred invoices a day
stay far below them. If your volume is of another order, tell us before you start.

## Reading what changed

Every list takes the same three parameters and answers the same shape:

| Parameter | What it does |
|---|---|
| `updatedSince` | Only what changed at or after this instant, written with its offset (`2026-11-18T22:00:00Z`). Left out: everything |
| `limit` | Rows a page, 1 to 100, 50 when left out |
| `cursor` | The `nextCursor` of the previous page, to read the next |

Write `updatedSince` in UTC, with `Z`. An offset such as `+01:00` must be sent as `%2B01:00`: in a
query string an unencoded `+` reads as a space, and the call is refused (`422 VALIDATION_FAILED`).

```json
{ "data": [ … ], "nextCursor": "eyJ2IjoiMjAyNi0xMS0xOVQwODozMDowMC4wMDBaIiwiaWQiOiIuLi4ifQ" }
```

Rows come **oldest change first**. `nextCursor` is `null` when there is nothing more for now.

To keep a copy of your data up to date (a dashboard, a data warehouse):

1. The first time, read the whole list: no `updatedSince`, then follow `nextCursor` to the end.
2. Remember the newest `updatedAt` you received.
3. The next time, pass it as `updatedSince`, **a few minutes earlier**, and follow `nextCursor` again.
4. Keep each row by its `id`: a row that changes while you read comes again, later in the list. A
   sync is « at least once », never « at most once ».

A cursor is opaque and belongs to the list that gave it: pass it back as you received it, to that
list. A value that is no cursor, and a cursor of another list, are refused
(`400 EXT_CURSOR_INVALID`) rather than silently starting over. A cursor is not signed: one edited by
hand is not told from Mast's own, and the list reads on from wherever it then points.

### What you can read

Give the key of a reporting tool a role that only reads. Each read asks « Read » on its feature, as
**Settings › User & Permissions** names it:

| What | Call | Feature to read |
|---|---|---|
| The company, its base currency, its fiscal years | `GET /ext/company` | Company Profile |
| Customers | `GET /ext/customers` | Customer |
| Products | `GET /ext/products` | Product |
| Invoices, with their lines | `GET /ext/invoices?include=lines` | Customer Invoices |
| Credit notes, with their lines | `GET /ext/credit-notes?include=lines` | Customer Credit Notes |
| Payments received | `GET /ext/payments` | Cash Allocation, under Sales & Invoicing |
| The chart of accounts | `GET /ext/accounts` | Chart of Accounts |
| Journal entries, with their lines | `GET /ext/journal-entries` | Journal Entries |
| The trial balance between two days | `GET /ext/trial-balance?from=…&to=…` | Financial Statement |
| Bank accounts and their balances | `GET /ext/bank-accounts` | Bank Accounts |
| Bank lines | `GET /ext/bank-transactions` | Bank Statement |
| Suppliers | `GET /ext/suppliers` | Supplier |
| Supplier bills, with their lines | `GET /ext/bills` | Supplier Bills |

### Figures that add up

- **What was invoiced in a period.** Add `invoicedNetAmount` over the invoices and the credit notes
  whose `issueDate` falls in the period. A draft and a cancelled document are `null`: they count for
  nothing. A credit note's amounts are below zero, so the sum is already net. To add documents of
  several currencies, take `baseInvoicedNetAmount`, in the company's base currency; it is `null` for a
  foreign document with no stored rate, which Mast never converts at 1 to 1.
- **By customer or by product.** Make the same sum over the lines: each line carries its own
  `invoicedNetAmount`, its share of what its document was issued for, the document's discount
  included. The lines of a document add up exactly to what was invoiced.
- **What your customers owe.** The invoices whose `amountDue` is above zero. `status` says where each
  stands (`open`, `overdue`, `partially_paid`) and `dueDate` when it falls due.
- **What came in.** The payments (`GET /ext/payments`), each with its day (`paidOn`), its amount and
  its invoice.
- **The result and the balance sheet.** The trial balance between two days gives, per account, the
  opening balance, the period's debits and credits and the closing balance, in the base currency.
  They are the figures of Mast's own Trial Balance for the same days. Every figure is signed debit
  minus credit, so an income, liability or equity account normally reads negative.
- **Cash.** The bank accounts carry the balance of the latest statement and the balance computed from
  every line Mast holds; the bank lines give the detail. Where your account requires two-step
  verification of everyone who signs in (it does once a bank is connected to Mast), these two calls
  answer a key `403 EXT_BANK_DATA_TWO_FACTOR_ACCOUNT`, since a key signs in with no second step;
  every other call answers as usual.
- **What you bought.** Supplier bills carry their status as Mast stores it, their amounts and what is
  still to pay. The list takes no `status` filter and also serves drafts and bills still to process:
  keep on your side the statuses you count. A bill that is booked carries its `journalEntryId`. A
  supplier's credit note (`type: credit_note`) has positive amounts, and is subtracted.
- **By cost centre.** Every journal line carries its shares per cost centre (`costCenterShares`),
  whose amounts add up exactly to the line.

Start with `GET /ext/company`: it gives the base currency every ledger figure is in, and the first
and last day of each fiscal year.

## Versions and stability

The address carries the version: `/api/v1`. Within it, **only additions are made**: a new call, a new
optional field in a request, a new field or a new value in an answer. No call, no field and no
accepted value goes away, and none changes its type or becomes required. A change that would break
your code would come under a new address (`/api/v2`), announced ahead, with both served side by side.
The contract's own version (in `openapi.v1.json`) moves with each addition.

Mast checks this by machine: the contract is printed from the code that answers, and a change that
would break a client is refused before it is published.

## Where your data is

The API is Mast: the same servers, in Switzerland (AWS Zurich), the same isolation between accounts
and between companies. A key reads and writes one company; no call reaches another company, or
another account, whatever it sends.
