# Getting started The Omono API lets your software read and change the records your organisation keeps in Omono. You can work with companies and their contacts and addresses, quotes, sales orders and the dispatches that ship them, credit notes, purchase orders and the deliveries you receive against them, stock items, tasks and documents. You can also read the reference lists, such as tax rates, currencies and workflow statuses, that those records point to. This guide takes you from no access to your first successful request. It explains how your organisation gets access, how to create an API key, which host to call, and where to test safely. > **Note:** The Omono API is in beta. Until it's generally available, any > part of it can change. A change takes effect when the > [changelog](/docs/changelog) lists it, with no notice in advance, and that > stays true after general availability. The > [compatibility policy](/docs/compatibility) explains what can change and > when a change takes effect. Changes you make through the API are real and > take effect at once, so test on a [sandbox organisation](/docs/getting-started#sandbox) first, > and don't make a critical process depend on the API alone yet. ## Ask Omono to switch on the API Omono switches the API on separately for each organisation, when the organisation asks. To ask, an admin of your organisation sends a message through Omono's in-app chat. Until access is on, the **API** page of **Settings** in Omono says so, nobody can create a key, and every request fails with a `403` error and the code `api-access-disabled`. Once access is on, an admin can also pause every key at once with the **API Access** switch on the same page, for example while they look into a problem. While the switch is off, every request fails with the same `403` error. The keys aren't revoked, so they work again as soon as the switch is back on. ## Create an API key An admin of your organisation creates API keys on the **API** page of **Settings** in Omono. Give each key the name of the integration that will use it, because Omono shows that name next to every change the key makes, as [How your changes appear in Omono](/docs/getting-started#how-your-changes-appear-in-omono) explains. When you create a key, you choose its scopes: the kinds of data it can read and change. The form starts with only `reference:read` ticked, so tick what your integration needs, and nothing more. | Scope | What it covers | | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `companies:read`, `companies:write` | Companies, with their contacts and addresses, and the list of all your contacts. | | `sales:read`, `sales:write` | Quotes, sales orders and their dispatches, invoices, credit notes, the list of sales order lines, and the dashboard figures (sales and output against target). | | `purchasing:read`, `purchasing:write` | Purchase orders and their deliveries. With a stock scope as well, your stock items' suppliers: `purchasing:read` reads them and `purchasing:write` changes them. | | `stock:read`, `stock:write` | Stock items, and the costs and margins on quote and sales order line items and on invoices. | | `tasks:read`, `tasks:write` | Tasks. | | `documents:read`, `documents:write` | Documents, which are the files attached to records. | | `reference:read` | Your organisation's details and its reference lists, such as users (with their email addresses), tax rates and currencies. | | `pricing:read` | Your customers' price lists, and the price and discount Omono fills in on a line. | Each scope also covers the notes of its records. A read scope lets the key read those records, and a write scope lets it create and change them. A write scope includes reading, so a key with `sales:write` can also read quotes, sales orders and credit notes. When you tick a write scope on the form, Omono ticks its read scope too, and the list of keys shows both. A scope covers only its own kind of record: for example, `sales:write` doesn't let a key read companies, and no scope but `pricing:read` lets a key read your customers' prices. The form leaves `pricing:read` unticked. Each operation in the API reference names the scopes that let a key call it, and so does its `security` in the [OpenAPI document](/api/v1/openapi.json): any one of the scopes it lists is enough. So you can check, before you deploy, that your key's scopes cover every operation your integration calls. An admin can change a key's scopes after you create it. On Settings → API, click the pencil icon (**Edit access**) on the key's row, change the ticks, then save. The key has its new scopes from its next request, so the integration keeps using the same key. Omono emails your admins about every change. A key's name, expiry date and secret can't change: to replace a key, create a new one, move your integration to it, then revoke the old one. If your integration reads [deletes from `GET /events`](/docs/syncing#deletes), read what to do after a change in [Keeping in sync](/docs/syncing#details). Omono shows the full key only once, straight after you create it. Copy it into your secret manager before you close the window. After that, Omono shows only the start of the key and its last four characters. A key starts with its platform's prefix, such as `omk_live_`, followed by 49 letters and digits. The last six characters are a checksum of the rest of the key, so Omono refuses a mistyped key at once, and secret scanners can tell a real key from other text. The checksum is the CRC-32 of everything before it, written in base 62 with the digits `0-9A-Za-z` and padded with `0` to six characters. Keys created before the checksum was added have 43 characters after the prefix and no checksum, and they keep working. Store and send the whole key exactly as Omono shows it, and don't check its length in your code. A few more things to know about keys: - Your organisation can have up to 25 active keys. A key is active until it is revoked or it expires. - You can give a key an expiry date. It stops working at 00:00 UTC on that day. If you leave the date blank, the key doesn't expire. - Keys belong to your organisation, not to the person who created them. A key keeps working when the admin who created it leaves, and any admin can revoke any key. - Every admin gets an email when a key is created, revoked or has its access changed, and when API access is switched on or off. To rotate a key, create a second key, move your integration over to it, and then revoke the old one. That way, your integration never stops working. ## Make your first request Every path in the [API reference](/docs) is relative to `https:///api/v1`. The host depends on the Omono platform your organisation uses, and each platform has its own keys: | Platform | Host | Keys start with | | -------------------------------------------- | ------------------- | --------------- | | Production | `api.omono.co` | `omk_live_` | | Demo, which also hosts sandbox organisations | `api-demo.omono.co` | `omk_demo_` | If Omono runs a private platform for your organisation, Omono gives you its host and key prefix. A key works only on the platform where it was created. If you send it to another platform's host, the request fails with a `401` error. For a production key or a demo key, the error's `detail` says which host to use. To check that everything works, ask for your five newest companies. This request needs a key with the `companies:read` scope. Test on a sandbox organisation first, with your `omk_demo_` key on `api-demo.omono.co`, as here. For your live organisation, call `api.omono.co` with your `omk_live_` key instead. ```bash curl "https://api-demo.omono.co/api/v1/companies?limit=5" \ -H "Authorization: Bearer omk_demo_yourKeyHere" ``` The response is a page of companies. The records are in `data`, and `hasMore` tells you whether there are more to fetch: ```json { "data": [ { "id": "b2FpLmNvbXBhbnkQQ", "companyName": "Acme Engineering Ltd", "accountNo": "ACME01", … } ], "hasMore": true, "nextCursor": "eyJ2IjoxLCJz…" } ``` To learn how to get the next page, read [Page through a list](/docs/reading#pagination). ## Authenticate your requests Send your key in the `Authorization` header of every request, as a bearer token: ```http Authorization: Bearer omk_live_yourKeyHere ``` The key also tells Omono which organisation you belong to, so you never send an organisation ID, and you only ever see and change your own organisation's data. If the key is missing, wrong, expired or revoked, the request fails with a `401` error and the code `unauthenticated`. When Omono recognises the key, the error's `detail` says what's wrong with it, for example that it has been revoked, or that it's a production key sent to the demo host. > **Warning:** Never put a key in a URL. If a request to the API carries a > key in its path or its query string, Omono refuses the request with a > `401` error and revokes the key at once, because URLs end up in proxy > logs and browser histories. This happens whatever the request is for, including the > OpenAPI document, and even while the API is switched off. Every admin of > your organisation gets an email about it. If a key ever appears in any > other URL, revoke it yourself on the **API** page of **Settings**. Send the key only in the `Authorization` header. A request that carries a key in its `X-Request-Id` header fails with a `400` error and the code `malformed-request`, and Omono doesn't store the header's value or send it back. The key isn't revoked in this case. Call the API from your own servers. It's built for server-to-server use, so it doesn't send CORS headers or answer `OPTIONS` requests, and a web page running in a browser can't call it directly. ## Test on a sandbox organisation Build and test your integration against a sandbox organisation on the demo platform, not against your live data. A sandbox is a separate organisation, so nothing you do there can change your live data. Omono sets one up when an admin of your organisation asks, and you can choose between two kinds: - **A copy of your own data.** Omono copies your organisation from production into a new sandbox, so you can test against your real customers, orders and stock. This is the best choice when you want to check how your integration handles your actual data. - **A sandbox with demo data.** Omono creates a new organisation filled with demo data, and you become its admin. This is the best choice when you're just getting started, or when you don't want your real data on the demo platform. In either kind of sandbox, you create your own keys on the **API** page of **Settings**, and Omono switches on API access for it in the same way as for your own organisation. Keys from production don't work in a sandbox. Its rate limits are the same as on production. ### What a copy of your data includes A copy holds your organisation's records as they were when Omono made it. It doesn't stay in step with production, so changes you make on either side stay there. Some things work differently in a copy: - **Your users sign in as usual.** Each user signs in on the demo platform with the same email address, password and authenticator app as on production. A password changed on one platform doesn't change on the other. - **IDs are the same as on production.** Every record keeps its production ID, which makes it easy to compare the two. It also means that you should keep your sandbox data and your production data in separate stores, so that a sandbox record never overwrites a live one. - **Some records aren't copied.** The copy doesn't include files attached to records, so the document list starts empty, and you upload test files yourself if you need them. It also leaves out API keys, the request log, the events list and, unless you ask for them, notes. - **Nothing reaches your customers or suppliers.** A sandbox never sends email to your customers or suppliers, even if you ask it to. Your own users can still get account emails from the demo platform, such as a password reset, or a notice when someone creates or revokes an API key. - **Xero isn't available.** A sandbox can't connect to Xero, so nothing you do there can reach your accounts. Omono shows a banner across the top of every page in a copy, so nobody mistakes it for your live system. ### Refresh or remove a sandbox Omono can refresh or remove a sandbox when you ask. Refreshing a copy of your data gives you a new copy of your organisation as it is on production at that time, with the same IDs. Resetting a sandbox with demo data gives you a brand-new organisation, with new IDs for every record. Either way, the sandbox gets new keys and a new sequence of events, so delete your copy of the sandbox data and start again with an [initial load](/docs/syncing#initial-load). ## How your changes appear in Omono Omono shows every change a key makes as the work of `API · `, in notes, in the activity feed and in task history. Documents that a key uploads show `API` as the uploader. Because staff see the key's name, name each key after the integration that uses it, such as "Web shop" or "Warehouse sync". ## Get help Contact Omono through the in-app chat, or email support@omono.co. So that Omono can find your request quickly, include: - your organisation's name - the host you called - the key's name and its last four characters, but never the whole key - the `requestId` from the response - the time of the request, in UTC Your admins can see the requests from the last 7 days in the **Request Log** panel on the **API** page of **Settings**. The log never shows a whole key: if a key appears in a request's path, the log shows only its start and its last four characters. The log keeps at most 300 characters of a path. When a key's requests are refused over and over in the same way, for example with the same `429` error, the log keeps at least the first 10 of them in each minute rather than every one. When a key gets any other `4xx` error from the same operation over and over, the log keeps at least the first 30 of them in each minute. The **Usage** panel on the same page still counts them all. For any request that failed, **View** shows what Omono received and what it sent back: the path and query, the headers that matter for debugging (such as `Content-Type` and `Idempotency-Key`), and the request and response bodies, up to 8 KB each. A header you sent with no value shows as `(empty)`. A body that isn't valid JSON is kept up to 1 KB. The `Authorization` header is never stored, and a key in a body is masked the same way. Admins can filter the log by method, error code or `requestId`, and export it to CSV or Excel. Omono doesn't keep the bodies of every failed request. When one key gets the same error from the same operation many times in a minute, the log keeps the bodies of the first 10 only. When an organisation's failed requests reach a very high volume in a day, the log stops keeping bodies until midnight UTC. In both cases the log still lists the requests that it keeps, and **View** says why the bodies weren't kept. If your code closes the connection before Omono answers, for example because its own timeout ran out, Omono still finishes the work, and the log shows the result, so you can see whether a write was saved. When the write succeeded, a retry with the same `Idempotency-Key` returns the stored response and doesn't do the work again. Omono sets up sandbox organisations and raises limits only when an admin of your organisation asks, or confirms the request in writing. ## Next steps - Follow the [recipes](/docs/recipes) for the most common jobs, step by step. - Generate a [client library](/docs/clients) for your language from the OpenAPI document, and learn the traps of each generator. - Learn how to [keep a copy of your data in sync](/docs/syncing) and how to [write data safely](/docs/writing). - Plan your integration around the [rate limits](/docs/limits), and decide how it will [handle errors](/docs/errors). --- # Build with AI assistants AI assistants and coding tools, which run on large language models (LLMs), can help you build your Omono integration faster, as long as they read the right documentation. Every guide page and every section of the API reference is also available as Markdown, a plain-text format that AI tools read well, so you can give your assistant exactly the pages it needs. ## Copy a page for your assistant At the top of every guide page, every error page and every section of the [API reference](/docs), there are two buttons: - **Copy for LLM** copies the page as Markdown. Paste it into a chat with your assistant, and it has the same information you see on the page. - **View as Markdown** opens the Markdown in your browser, so you can read it or link to it. Each operation in the API reference also has a **Copy as Markdown** button, which copies that one operation. ## Point your tools at llms.txt [`/docs/llms.txt`](/docs/llms.txt) lists every Markdown page of these docs, with a short description of each one. It follows the [llms.txt](https://llmstxt.org) convention, which some AI tools look for. Give your assistant its full address on the host you use, for example `https://api.omono.co/docs/llms.txt`, and it can fetch the pages it needs. ## Give it everything at once [`/docs/llms-full.txt`](/docs/llms-full.txt) holds every guide, the whole API reference and every error code in one file. It's more than 100,000 words long, so use it with tools that can read long documents, or when you want your assistant to search the whole API. ## Generate code from the OpenAPI document The [OpenAPI document](/api/v1/openapi.json) describes every operation, parameter and field in a form that software can read. Code generators and many AI coding tools can use it to build a client for the API, with a type for every object. [Client libraries](/docs/clients) lists the generators that Omono has tested, with the command and a short example for each, and the traps to avoid. Give that page to your assistant when it writes code with a generated client. Every list of values in a response is open, because Omono can add a value at any time. So in the OpenAPI document, a response field such as a `status` is a plain string. Its description lists the values known today, and they're also in a separate schema whose name starts with `Known`, such as `KnownOrderStatus`. Requests use the `Known` schema, so they still accept only the known values. A generated client reads these fields as strings, so it doesn't fail on a value it doesn't recognise, but make sure your own code copes with one. Each list has a schema of its own, such as `CompanyList`, so a generated client gets a type for each list, with `data` as an array of its records. Once the API is generally available, the `operationId` of each stable operation, and the names of the schemas and tags that stable operations use, stay the same within version 1, so a client you generate again keeps its method and type names. Until then, any of these names can change, and a beta operation's names can change at any time. The changelog lists each change. The [compatibility policy](/docs/compatibility#stable-strings) explains what stays stable. You don't need an API key to fetch the OpenAPI document, so never add one to its URL. As with any API request, Omono revokes a key at once if it finds one in the URL, as [Authenticate your requests](/docs/getting-started#authentication) explains. ## Use your assistant safely - **Give it the pages for the job.** For example, give it the recipe you're following and the reference sections of the resources it uses, rather than the whole API. - **Check what it writes.** Compare the requests it builds with the [API reference](/docs), and try them on a [sandbox organisation](/docs/getting-started#sandbox) before you use your live data. - **Never paste an API key into a chat.** Keep your keys in a secrets manager, and let your code read them from there. Check that the code your assistant writes sends the key only in the `Authorization` header, never in a URL or in `X-Request-Id`. - **Fetch the Markdown again when you start new work.** It changes whenever these docs change, so an old copy can miss new fields or rules. The [changelog](/docs/changelog) lists every change to the API, so check it for anything that's changed since you last fetched the pages. --- # Client libraries You can generate a client library for the Omono API in your own language, from the API's OpenAPI document. This page lists the generators that Omono has tested. For each one, it gives the command, a short example and the traps to avoid. ## Generate a client Each Omono platform serves its OpenAPI document at `https:///api/v1/openapi.json`, on the same host as its API and these docs: | Platform | OpenAPI document | | -------------------------------------------- | ----------------------------------------------- | | Production | `https://api.omono.co/api/v1/openapi.json` | | Demo, which also hosts sandbox organisations | `https://api-demo.omono.co/api/v1/openapi.json` | If Omono runs a private platform for your organisation, use its host instead. Generate your client from the platform that your integration calls, because each platform's document describes the API that the platform serves. The document gives that platform's address as its server, so a client you generate from it calls that platform unless you set another host. You don't need an API key to fetch the document, so never add one to its URL. As with any request, Omono revokes a key at once if it finds one in the URL, as [Authenticate your requests](/docs/getting-started#authentication) explains. Generate your client again when the API changes. The [changelog](/docs/changelog) lists every change. Once the API is generally available, the method and type names that come from a stable operation stay the same within v1, as [Which names and text you can rely on](/docs/compatibility#stable-strings) explains. ## Tested generators Omono tested each of these generators. For each one, it generated a client from the OpenAPI document, built it, and used it to list, retrieve, create and change records through the API. | Language | Generator | Versions tested | | ---------- | ---------------------------------------------------------- | --------------- | | Python | [openapi-generator, `python`](/docs/clients#python) | 7.26.0 | | Python | [openapi-python-client](/docs/clients#openapi-python-client) | 0.29.1 | | TypeScript | [openapi-generator, `typescript-fetch`](/docs/clients#typescript-fetch) | 7.26.0 | | TypeScript | [openapi-typescript with openapi-fetch](/docs/clients#openapi-fetch) | 7.13 and 0.17 | | Java | [openapi-generator, `java`](/docs/clients#java) | 7.26.0 | | C# | [openapi-generator, `csharp`](/docs/clients#csharp) | 7.26.0 | Other generators can work too, but Omono hasn't tested them. When openapi-generator runs, it warns that its support for OpenAPI 3.1 is in beta. You can ignore that warning for the generators in this table. Omono has also generated a TypeScript client with [Kiota](/docs/clients#kiota) and built it, but hasn't used it against the API yet. ## What the examples do Each example on this page does the same five things, so you can compare them: 1. It lists every company, one page at a time. It sends `nextCursor` as `cursor` until `hasMore` is `false`, as [Page through a list](/docs/reading#pagination) explains. 2. It retrieves one company and keeps the `ETag` from the response. 3. It changes the company's `website`, and sends the `ETag` in `If-Match`. If someone changed the company after the example read it, the change fails with a `412` error, as [Avoid overwriting changes with ETags](/docs/writing#etags) explains. 4. It handles that error. Every error has a body in the same format, which the OpenAPI document calls a `Problem`, and the example checks its `code`. [What an error looks like](/docs/errors#the-error-format) describes the format. 5. It adds a contact to the company, with an `Idempotency-Key`, so a retry can't add the contact twice, as [Retry requests safely](/docs/writing#idempotency) explains. The examples change data, so they call the demo platform. Run them on a [sandbox organisation](/docs/getting-started#sandbox). They read your API key from the `OMONO_API_KEY` environment variable, and the key needs the `companies:write` scope. Each example makes a new idempotency key for each request. In your own code, keep the key, so that you can send it again if you retry the request. ## Python with openapi-generator Generate the client with Docker, then install it: ```bash docker run --rm -v "$PWD:/local" openapitools/openapi-generator-cli:v7.26.0 generate \ -i https://api-demo.omono.co/api/v1/openapi.json \ -g python -o /local/omono-python \ --additional-properties=packageName=omono_client pip install ./omono-python ``` The client needs Python 3.10 or later. Any status other than a `2xx` raises `ApiException`, or a subclass of it such as `NotFoundException`, and `e.data` holds the `Problem`. A `304` raises it too, with `e.status` set to `304`. ```python import os import uuid from omono_client import (ApiClient, ApiException, CompaniesApi, CompanyUpdate, Configuration, ContactCreate, ContactsApi, Problem) config = Configuration( host="https://api-demo.omono.co/api/v1", access_token=os.environ["OMONO_API_KEY"], ) with ApiClient(config) as client: companies = CompaniesApi(client) # List every company, one page at a time. page = companies.list_companies(limit=200) everyone = list(page.data) while page.has_more: page = companies.list_companies(limit=200, cursor=page.next_cursor) everyone += page.data company_id = everyone[0].id # Read one company and keep its ETag. read = companies.get_company_with_http_info(company_id) etag = (read.headers or {})["etag"] # Change it, unless someone else changed it first. try: companies.update_company( company_id, CompanyUpdate(website="https://example.com"), idempotency_key=str(uuid.uuid4()), if_match=etag, ) except ApiException as e: if not (isinstance(e.data, Problem) and e.data.code == "precondition-failed"): raise # Someone changed the company first: read it again and retry. # Add a contact. Send the same Idempotency-Key if you retry. ContactsApi(client).create_company_contact( company_id, ContactCreate(first_name="Ada", last_name="Lovelace", email="ada@example.com"), idempotency_key=str(uuid.uuid4()), ) ``` Watch out for these: - **Build a `PATCH` body with the model's constructor.** `CompanyUpdate(website=...)` sends only the fields you set. Don't build a `PATCH` body with `from_dict()` or `from_json()`. They send `null` for each field you leave out that can be cleared, such as a company's `eoriNumber`, and `null` clears the field. - **Read headers with the `_with_http_info` methods.** `get_company()` returns only the company. `get_company_with_http_info()` also returns `headers`, a plain dictionary whose names are case-sensitive. Omono sends header names in lower case, so read `headers["etag"]`, not `headers["ETag"]`. - **Use datetimes with a time zone.** A naive `datetime` goes out without an offset, and Omono refuses it with a `422` error. Send one with a time zone, such as `datetime(2026, 9, 1, tzinfo=timezone.utc)`. - **Read an error's field as `var_field`.** The generator renames the `field` of each entry in `errors[]`, so read `e.data.errors[0].var_field`. The JSON still says `field`. ## Python with openapi-python-client Generate the client, then install it: ```bash pip install openapi-python-client==0.29.1 openapi-python-client generate --url https://api-demo.omono.co/api/v1/openapi.json pip install ./omono-api-client ``` The package is `omono_api_client`, and it needs Python 3.11 or later. Each operation is a module with four functions. `sync()` and `asyncio()` return the parsed body, and `sync_detailed()` and `asyncio_detailed()` also return the status code and the headers. An error doesn't raise an exception: instead, the call returns the `Problem`. ```python import os import uuid from omono_api_client import AuthenticatedClient from omono_api_client.api.companies import get_company, list_companies, update_company from omono_api_client.api.contacts import create_company_contact from omono_api_client.models import CompanyList, CompanyUpdate, ContactCreate, Problem client = AuthenticatedClient( base_url="https://api-demo.omono.co/api/v1", token=os.environ["OMONO_API_KEY"], ) # List every company, one page at a time. page = list_companies.sync(client=client, limit=200) assert isinstance(page, CompanyList) everyone = list(page.data) while page.has_more and page.next_cursor: page = list_companies.sync(client=client, limit=200, cursor=page.next_cursor) assert isinstance(page, CompanyList) everyone += page.data company_id = everyone[0].id # Read one company and keep its ETag. read = get_company.sync_detailed(company_id, client=client) etag = read.headers["ETag"] # Change it, unless someone else changed it first. result = update_company.sync( company_id, client=client, body=CompanyUpdate(website="https://example.com"), idempotency_key=str(uuid.uuid4()), if_match=etag, ) if isinstance(result, Problem) and result.code == "precondition-failed": pass # Someone changed the company first: read it again and retry. # Add a contact. Send the same Idempotency-Key if you retry. create_company_contact.sync( company_id, client=client, body=ContactCreate(first_name="Ada", last_name="Lovelace", email="ada@example.com"), idempotency_key=str(uuid.uuid4()), ) ``` Watch out for this: - **Check the type of every result with `isinstance`.** A call returns the record, a `Problem` or `None`. A read that can answer `304` is typed `Any` as well, and its result is `None` on a `304`, because a `304` has no body. So check the type before you use a result. ## TypeScript with typescript-fetch Generate the client into your project's source folder: ```bash docker run --rm -v "$PWD:/local" openapitools/openapi-generator-cli:v7.26.0 generate \ -i https://api-demo.omono.co/api/v1/openapi.json \ -g typescript-fetch -o /local/src/omono ``` The client uses the global `fetch`. The example runs on Node.js 20 or later, as an ES module. ```typescript import { CompaniesApi, Configuration, ContactsApi, ProblemFromJSON, ResponseError, } from './omono'; const config = new Configuration({ basePath: 'https://api-demo.omono.co/api/v1', accessToken: process.env.OMONO_API_KEY, }); const companies = new CompaniesApi(config); // List every company, one page at a time. let page = await companies.listCompanies({ limit: 200 }); const everyone = [...page.data]; while (page.hasMore) { page = await companies.listCompanies({ limit: 200, cursor: page.nextCursor!, }); everyone.push(...page.data); } const id = everyone[0].id; // Read one company and keep its ETag. const read = await companies.getCompanyRaw({ id }); const etag = read.raw.headers.get('ETag')!; // Change it, unless someone else changed it first. try { await companies.updateCompany({ id, ifMatch: etag, idempotencyKey: crypto.randomUUID(), companyUpdate: { website: 'https://example.com' }, }); } catch (e) { if (!(e instanceof ResponseError)) throw e; const problem = ProblemFromJSON(await e.response.json()); if (problem.code !== 'precondition-failed') throw e; // Someone changed the company first: read it again and retry. } // Add a contact. Send the same Idempotency-Key if you retry. await new ContactsApi(config).createCompanyContact({ id, idempotencyKey: crypto.randomUUID(), contactCreate: { firstName: 'Ada', lastName: 'Lovelace', email: 'ada@example.com', }, }); ``` Watch out for these: - **Read headers with the `Raw` methods.** `getCompany()` returns only the company. `getCompanyRaw()` returns `raw`, which is the fetch `Response`, so `raw.headers.get('ETag')` works, and `value()` returns the company. - **Any status other than a `2xx` throws `ResponseError`, and so does a `304`.** Read the `Problem` with `ProblemFromJSON(await e.response.json())`. A `304` has no body, so check `e.response.status` before you read the body. - **A line item's `delete` field is `_delete` in the model.** To delete a line, send `{ id, _delete: true }`, and the client sends it as `"delete": true`. ## TypeScript with openapi-typescript and openapi-fetch Generate the types, then install openapi-fetch: ```bash npx openapi-typescript@7.13.0 https://api-demo.omono.co/api/v1/openapi.json -o src/omono.d.ts npm install openapi-fetch@0.17 ``` openapi-typescript generates types only, and openapi-fetch uses them to check each call. A call returns `data` when it works, or `error`, typed as a `Problem`, when it fails, and `response` in both cases. The example runs on Node.js 20 or later, as an ES module. ```typescript import createClient from 'openapi-fetch'; import type { paths } from './omono'; const omono = createClient({ baseUrl: 'https://api-demo.omono.co/api/v1', headers: { Authorization: `Bearer ${process.env.OMONO_API_KEY}` }, }); // List every company, one page at a time. async function listCompanies(cursor?: string) { const { data, error } = await omono.GET('/companies', { params: { query: { limit: 200, cursor } }, }); if (error) throw new Error(`${error.code}: ${error.title}`); return data; } let page = await listCompanies(); const everyone = [...page.data]; while (page.hasMore) { page = await listCompanies(page.nextCursor!); everyone.push(...page.data); } const id = everyone[0].id; // Read one company and keep its ETag. const read = await omono.GET('/companies/{id}', { params: { path: { id } } }); const etag = read.response.headers.get('ETag')!; // Change it, unless someone else changed it first. const { error } = await omono.PATCH('/companies/{id}', { params: { path: { id }, header: { 'If-Match': etag, 'Idempotency-Key': crypto.randomUUID() }, }, body: { website: 'https://example.com' }, }); if (error && error.code !== 'precondition-failed') { throw new Error(`${error.code}: ${error.title}`); } // On precondition-failed, someone changed the company first: read it again and retry. // Add a contact. Send the same Idempotency-Key if you retry. await omono.POST('/companies/{id}/contacts', { params: { path: { id }, header: { 'Idempotency-Key': crypto.randomUUID() } }, body: { firstName: 'Ada', lastName: 'Lovelace', email: 'ada@example.com' }, }); ``` Watch out for this: - **Check for a `304` yourself.** On a `304`, `data` is `undefined` and `error` holds no `Problem`. So when you send `If-None-Match`, check `response.status === 304` before you use either of them. ## Java Generate the client with Docker: ```bash docker run --rm -v "$PWD:/local" openapitools/openapi-generator-cli:v7.26.0 generate \ -i https://api-demo.omono.co/api/v1/openapi.json \ -g java -o /local/omono-java \ --additional-properties=containerDefaultToNull=true ``` This makes a Maven and Gradle project that uses the default library, okhttp-gson, with its classes in `org.openapitools.client`. To choose your own package names, add `--api-package`, `--model-package` and `--invoker-package` to the command. Omono tested it on Java 17. ```java import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.openapitools.client.*; import org.openapitools.client.api.*; import org.openapitools.client.model.*; public class Example { public static void main(String[] args) throws ApiException { ApiClient client = new ApiClient(); client.setBasePath("https://api-demo.omono.co/api/v1"); client.setBearerToken(System.getenv("OMONO_API_KEY")); CompaniesApi companies = new CompaniesApi(client); // List every company, one page at a time. CompanyList page = companies.listCompanies().limit(200).execute(); List everyone = new ArrayList<>(page.getData()); while (page.getHasMore()) { page = companies.listCompanies().limit(200).cursor(page.getNextCursor()).execute(); everyone.addAll(page.getData()); } String id = everyone.get(0).getId(); // Read one company and keep its ETag. ApiResponse read = companies.getCompanyWithHttpInfo(id, null, null); String etag = read.getHeaders().get("ETag").get(0); // Change it, unless someone else changed it first. try { companies.updateCompany(id, new CompanyUpdate().website("https://example.com"), UUID.randomUUID().toString(), etag); } catch (ApiException e) { Problem problem = JSON.getGson().fromJson(e.getResponseBody(), Problem.class); if (!"precondition-failed".equals(problem.getCode())) throw e; // Someone changed the company first: read it again and retry. } // Add a contact. Send the same Idempotency-Key if you retry. new ContactsApi(client).createCompanyContact(id, new ContactCreate().firstName("Ada").lastName("Lovelace").email("ada@example.com"), UUID.randomUUID().toString()); } } ``` Watch out for these: - **Read headers with the `WithHttpInfo` methods.** `getCompanyWithHttpInfo()` returns an `ApiResponse`, and its `getHeaders()` holds the `ETag`. `getCompany()` returns only the company. - **Any status other than a `2xx` throws `ApiException`, and so does a `304`.** Read the `Problem` from `e.getResponseBody()` with `JSON.getGson().fromJson(body, Problem.class)`. A `304` has an empty body, so check `e.getCode()` first. - **A list method returns a request builder.** Chain the filters you use, such as `.limit(200).cursor(...)`, then call `execute()`. `executeWithHttpInfo()` also gives you the headers. - **Keep `containerDefaultToNull=true` in the command.** Without it, every list in a request body starts as an empty list. An update then sends `lineItems`, `lineItemOrder` or `bom` as `[]` although you never set them, and Omono refuses the request with a `422` error. - **To clear a field, use the jersey3 library.** okhttp-gson leaves every field that's `null` out of the request, so it can't clear a field such as a company's `eoriNumber`. To clear fields, add `--library jersey3 --additional-properties=openApiNullable=true,containerDefaultToNull=true` to the command, in place of the `--additional-properties` above. Then `new CompanyUpdate().eoriNumber(null)` sends `"eoriNumber": null`, and fields you don't set stay out of the request. Jersey needs the Java option `--add-opens java.base/java.net=ALL-UNNAMED` to send a `PATCH`. With jersey3, header names are case-sensitive, so read `getHeaders().get("etag")`, and `e.getErrorEntity()` returns the `Problem`. ## C# Generate the client with Docker: ```bash docker run --rm -v "$PWD:/local" openapitools/openapi-generator-cli:v7.26.0 generate \ -i https://api-demo.omono.co/api/v1/openapi.json \ -g csharp -o /local/omono-csharp \ --additional-properties=packageName=Omono,useDateTimeOffset=true ``` This makes a .NET 10 project that uses the default library, generichost, which you set up with dependency injection. An error doesn't throw an exception. Each response has `IsOk` and `Ok()`, and a pair for each other status that the operation documents, such as `IsPreconditionFailed` and `PreconditionFailed()`, which returns the `Problem`. A `304` sets `IsNotModified`. ```csharp using Microsoft.Extensions.DependencyInjection; using Omono.Api; using Omono.Client; using Omono.Extensions; using Omono.Model; var services = new ServiceCollection(); services.AddLogging(); services.AddApi(options => { options.AddTokens(new BearerToken(Environment.GetEnvironmentVariable("OMONO_API_KEY")!)); options.AddApiHttpClients(http => http.BaseAddress = new Uri("https://api-demo.omono.co/api/v1")); }); var provider = services.BuildServiceProvider(); var companies = provider.GetRequiredService(); // List every company, one page at a time. var page = (await companies.ListCompaniesAsync(limit: 200)).Ok()!; var everyone = new List(page.Data); while (page.HasMore) { page = (await companies.ListCompaniesAsync(limit: 200, cursor: page.NextCursor!)).Ok()!; everyone.AddRange(page.Data); } var id = everyone[0].Id; // Read one company and keep its ETag. var read = await companies.GetCompanyAsync(id); var etag = read.Headers.ETag!.ToString(); // Change it, unless someone else changed it first. var update = await companies.UpdateCompanyAsync(id, new CompanyUpdate(website: "https://example.com"), idempotencyKey: Guid.NewGuid().ToString(), ifMatch: etag); if (update.IsPreconditionFailed) { Problem problem = update.PreconditionFailed()!; // Someone changed the company first: read it again and retry. } // Add a contact. Send the same Idempotency-Key if you retry. var contacts = provider.GetRequiredService(); await contacts.CreateCompanyContactAsync(id, new ContactCreate(firstName: "Ada", lastName: "Lovelace", email: "ada@example.com"), idempotencyKey: Guid.NewGuid().ToString()); ``` Watch out for these: - **Send times with an offset.** The command above sets `useDateTimeOffset=true`, so times are `DateTimeOffset` values, which always carry an offset. Without it, times are `DateTime` values. A `DateTime` whose `Kind` isn't `Utc` goes out without an offset, and Omono refuses it with a `422` error. So build each `DateTime` with `DateTimeKind.Utc`, or use `DateTime.UtcNow`. - **Read a stock item body back as its kind.** Sending a `StockItemCreate` or `StockItemUpdate` works for every `kind`. To read one back from JSON that you stored, deserialise the type of its kind, such as `StockItemCreateNormal`, not the `StockItemCreate` wrapper. ## TypeScript with Kiota Omono generated this client with Kiota 1.35.0 and built it with TypeScript's strict checks, but hasn't used it against the API yet. Kiota's support for TypeScript is in preview, so its output can change from one version to the next. Generate the client into your project's source folder, then install the package it needs, at the version that Kiota prints: ```bash kiota generate -l typescript -d https://api-demo.omono.co/api/v1/openapi.json \ -o ./src/omono -c OmonoClient -n omono npm install @microsoft/kiota-bundle@1.0.0-preview.106 -SE ``` The client uses the global `fetch`. The example runs on Node.js 20 or later, as an ES module. ```typescript import { ApiKeyAuthenticationProvider, ApiKeyLocation, } from '@microsoft/kiota-abstractions'; import { DefaultRequestAdapter } from '@microsoft/kiota-bundle'; import { HeadersInspectionOptions } from '@microsoft/kiota-http-fetchlibrary'; import type { Company, Problem } from './omono/models/index.js'; import { createOmonoClient } from './omono/omonoClient.js'; const auth = new ApiKeyAuthenticationProvider( `Bearer ${process.env.OMONO_API_KEY}`, 'Authorization', ApiKeyLocation.Header, new Set(['api-demo.omono.co']), ); const adapter = new DefaultRequestAdapter(auth); adapter.baseUrl = 'https://api-demo.omono.co/api/v1'; const omono = createOmonoClient(adapter); // List every company, one page at a time. let page = await omono.companies.get({ queryParameters: { limit: 200 } }); const everyone: Company[] = [...(page?.data ?? [])]; while (page?.hasMore) { page = await omono.companies.get({ queryParameters: { limit: 200, cursor: page.nextCursor! }, }); everyone.push(...(page?.data ?? [])); } const id = everyone[0]!.id!; // Read one company and keep its ETag. const inspect = new HeadersInspectionOptions({ inspectResponseHeaders: true }); await omono.companies.byId(id).get({ options: [inspect] }); const etag = [...(inspect.getResponseHeaders().get('etag') ?? [])][0]!; // Change it, unless someone else changed it first. try { await omono.companies.byId(id).patch( { website: 'https://example.com' }, { headers: { 'If-Match': etag, 'Idempotency-Key': crypto.randomUUID() }, }, ); } catch (e) { if ((e as Problem).code !== 'precondition-failed') throw e; // Someone changed the company first: read it again and retry. } // Add a contact. Send the same Idempotency-Key if you retry. const contacts = omono.companies.byId(id).contacts; await contacts.post( { firstName: 'Ada', lastName: 'Lovelace', email: 'ada@example.com' }, { headers: { 'Idempotency-Key': crypto.randomUUID() } }, ); ``` Watch out for these: - **Send the key in the header.** Use `ApiKeyLocation.Header`, as in the example, and list only Omono's host. Never use `ApiKeyLocation.QueryParameter`: Omono revokes a key that it finds in a URL. - **An error throws the `Problem` itself.** Any status other than a `2xx` or a `304` throws the `Problem`, a plain object rather than an `Error`, with the HTTP status in `responseStatusCode`. Check its `code`. A `304` doesn't throw: the method returns `undefined`. - **Read headers with `HeadersInspectionOptions`.** Pass one in `options`, as the example does for the `ETag`, and read `getResponseHeaders()` after the call. Each header is a set of values. - **Kiota retries by itself.** It retries a request that gets a `429`, `503` or `504` up to three times, after the `Retry-After` delay, and that includes a `POST`. It sends the same headers each time, so send an `Idempotency-Key` with every create. - **Download a document's file with `sendPrimitive`.** `documents.byId(id).content.get()` follows the redirect but returns nothing. Send the request yourself instead: `adapter.sendPrimitive(omono.documents.byId(id).content.toGetRequestInformation(), 'ArrayBuffer', undefined)`. Kiota drops the `Authorization` header when it follows the redirect to the storage host. - **Give an upload its file name.** `documents.post()` takes a `MultipartBody`. Add the file last, with its name as the fifth argument: `body.addOrReplacePart('file', 'application/pdf', bytes, undefined, 'drawing.pdf')`. - **Unlink a task with `general`.** Kiota sends a `linkedEntityType` of `null` as the text `"null"`, which Omono refuses. To remove a task's link, send `linkedEntityType: 'general'` with `linkedEntityId: null`. ## Good to know - **Lists of values are strings in responses.** A response field that holds a value from a list, such as a `status`, is a plain string in a generated client, so a value that Omono adds later doesn't break it. Requests use the `Known` schemas, such as `KnownOrderStatus`. [Generate code from the OpenAPI document](/docs/ai#openapi) explains more. - **Send an ETag back exactly as you read it.** Keep its double quotes. A generated client sends a header value as you give it, so pass the value from the `ETag` header without changing it. --- # Recipes Each recipe walks you through one common integration job, step by step. It shows only the calls, fields and errors that the job needs. The [API reference](/docs) has every detail, and each recipe links to it where you need more. In the steps, paths such as `GET /companies` are relative to `https:///api/v1`, and the examples show the full path. Every request sends your API key in an `Authorization: Bearer ` header. Every `POST` and `PATCH` should also send an `Idempotency-Key` header. Use a new key for each new request, and send the same key again on every retry of that request, so that a retry after a timeout doesn't do the work twice. A `DELETE` doesn't need one. Learn more about [retrying requests safely](/docs/writing#idempotency). > **Note:** Most recipes use write operations, which are in beta: they can > change in any way, at any time, until they're marked stable. Mirroring > your data and keeping stock levels up to date only read stable > operations. Exporting invoices, reporting sales against target, matching > an email, checking supplier invoices and reporting margin only read too, > but each uses at least one operation in beta. Learn more about > [beta operations](/docs/compatibility#stable-and-beta-operations). ## Push orders into Omono Use this recipe when orders arrive somewhere else first, for example in a web shop, and you want them in Omono as sales orders. You look up a few IDs once, and then create each order, add its dispatch and activate it. [Read the recipe](/docs/recipes/push-orders) ## Mirror your data in another system Use this recipe to keep a copy of your Omono data somewhere else, such as a business intelligence (BI) tool, a CRM or a data warehouse. You load everything once, and then check for changes and deleted records every few minutes. Omono lists deleted records as events, in `GET /events`. [Keeping in sync](/docs/syncing) explains each rule in more depth. [Read the recipe](/docs/recipes/mirror-data) ## Ship and invoice a dispatch Use this recipe to ship a dispatch and raise its invoice from your own system. In Omono, a sales order ships in one or more dispatches, and each dispatch moves through your organisation's workflow statuses. The last one is the final status, which is the status whose type is `final`. Moving a dispatch to it ships the dispatch and invoices it. [Read the recipe](/docs/recipes/ship-and-invoice) ## Change a document's line items Use this recipe to add, change or delete line items on a quote, sales order, credit note or purchase order that already exists. The example uses a sales order, which needs the scopes `sales:read` and `sales:write`. [Read the recipe](/docs/recipes/change-line-items) ## Sync customers and contacts from a CRM Use this recipe when your customers live in a CRM first. You match each customer to an Omono company by its account number, create what's missing and change what's different, and find contacts by email address. [Read the recipe](/docs/recipes/sync-customers) ## Keep a web shop's stock levels up to date Use this recipe to show how many of each product you can sell. You work out the free quantity of normal items, assemblies and never-diminishing items, and read only the items that changed. [Read the recipe](/docs/recipes/stock-levels) ## Plan the dispatches for an order Use this recipe when another system plans how an order ships, for example in weekly parts. You add dispatches, move their dates and remove the ones you no longer need, before your staff allocate them. [Read the recipe](/docs/recipes/plan-dispatches) ## Raise a purchase order from another system Use this recipe when another system decides what to buy. You create the purchase order, add the deliveries you expect, and issue it. [Read the recipe](/docs/recipes/raise-purchase-order) ## Attach a file to a record Use this recipe to put a drawing, a certificate or another file on a company, quote, order or stock item, where your staff see it. [Read the recipe](/docs/recipes/attach-a-file) ## Turn an enquiry into a quote and follow it up Use this recipe when enquiries arrive somewhere else first. You create the quote and a follow-up task, then mark the quote as won or lost and complete the task. [Read the recipe](/docs/recipes/enquiry-to-quote) ## Export invoices to accounting or BI Use this recipe to copy the invoices Omono raises into another system, with the goods on each one. [Read the recipe](/docs/recipes/export-invoices) ## Report sales against target Use this recipe to show your sales and output against your targets in another system, such as a wallboard, with the figures from Omono's dashboard. [Read the recipe](/docs/recipes/sales-against-target) ## Match an incoming email to a customer Use this recipe when an email arrives and you want to show who sent it. You find the customer from the sender's address, by the exact address, then by its domain, then by the company's name, and read what they have open in Omono. [Read the recipe](/docs/recipes/match-an-email) ## Check supplier invoices Use this recipe to copy the supplier invoices that your staff record in Omono into another system, with their values in your base currency and the state of their sync to Xero. [Read the recipe](/docs/recipes/check-supplier-invoices) ## Report margin Use this recipe to report the margin on what you sell, from the cost and margin on each sales order line item and the cost and profit on each invoice. [Read the recipe](/docs/recipes/report-margin) --- # Push orders into Omono Use this recipe when orders arrive somewhere else first, for example in a web shop, and you want them in Omono as sales orders. You look up a few IDs once, and then create each order, add its dispatch and activate it with three calls. Every request in this recipe sends your API key in an `Authorization: Bearer ` header, and every `POST` and `PATCH` also sends an `Idempotency-Key`, so a prompt retry doesn't do the work twice. Paths are relative to `https:///api/v1`, and the examples show the full path. > **Note:** The sales order write operations are in beta, and you can use > this recipe once they appear in the [API reference](/docs#tag/sales-orders) > for your platform. You need the scopes `sales:read`, `sales:write`, `companies:read`, `stock:read` and `reference:read`. ## Before your first order Look up the IDs you need and cache them. Look them up again whenever your reference data changes. - **The customer.** Find the company with `GET /companies?accountNo=`, or with `companyName=`, and take its `id`. Note its `currencyId` too, for the exchange rate below. Learn more about [companies](/docs#tag/companies). - **The contact.** Choose one of the customer's contacts from `GET /companies/{id}/contacts`, for example the one whose `email` matches your shop's customer. - **The delivery address.** Omono addresses have no delivery flag, so match your shop's shipping address to one from `GET /companies/{id}/addresses`, for example by its `postcode` and `line1`. If none matches, you can deliver to the customer's accounts address, the one whose `accountsAddress` is `true`, and flag the order for your staff to check. Or, if your key also has `companies:write`, add the new address with `POST /companies/{id}/addresses` and use its `id`. - **Each product.** Find the stock item with `GET /stock-items?partNo=`. Only stock items with `canSell: true` can go on a sales order. - **The sales person.** Choose a user from `GET /users` whose `assignable` field is `true`, which means you can name that user on a record. Many integrations use a user that your staff set up in Omono for this, such as "Web shop", so that web orders are easy to find. - **The exchange rate.** Read your base currency from `GET /organisation`, in `baseCurrencyId`. If the customer's `currencyId` is the same, send an `exchangeRate` of 1. Otherwise, take the current `rate` for the customer's currency from `GET /currency-rates`. Learn more about [money and exchange rates](/docs/conventions#money). Your organisation can require a customer order number on every sales order. Read `salesOrders.customerOrderNoRequired` from `GET /settings` to find out. When it's required, send the reference your customer gave you, or your own order number if they gave none. ## For each order 1. **Give each order your own reference.** Send your web shop's order number in `externalRef`. It's unique among your organisation's sales orders, cancelled ones included, so Omono never creates the same order twice, even long after an `Idempotency-Key` has expired. If you send an order again, the create fails with a `409` error and the code `duplicate-external-ref`, and `conflictingId` is the order you created before: read it instead. Keep `customerOrderNo` for the reference that your customer gave you, because it prints on the order paperwork. Learn more about [external references](/docs/writing#external-references). 2. **Create the order and its line items in one call.** ```http POST /api/v1/sales-orders Idempotency-Key: shop-order-10452 Content-Type: application/json { "companyId": "…", "contactId": "…", "addressId": "…", "salesPersonId": "…", "exchangeRate": 1, "externalRef": "WEB-10452", "customerOrderNo": "PO-7731", "lineItems": [ { "stockItemId": "…", "quantity": 2, "price": 19.5, "externalRef": "WEB-10452-1" }, { "stockItemId": "…", "quantity": 1, "price": 120, "externalRef": "WEB-10452-2" } ] } ``` For each line item, you send only the stock item, the quantity and the price. Omono fills in the tax rate from the customer, and the sales analysis code and the description from the stock item. A sales analysis code is a category you use to analyse your sales. The `201` response returns the order with the status `draft`, its `ETag`, and `createdLineItems`, which gives the ID of the new line item made from each position in your array. Learn more about [creating a document with its line items](/docs/writing#creating-a-document-with-lines) and [the fields Omono fills in](/docs/writing#prefilled-fields). 3. **Add a dispatch.** A dispatch is a shipment that delivers the order. As in Omono, an order can only be activated once all of its line items are on dispatches, so add one dispatch that ships everything, using the line item IDs from `createdLineItems`: ```http POST /api/v1/sales-orders/{id}/dispatches Idempotency-Key: shop-order-10452-dispatch Content-Type: application/json { "dispatchDate": "2026-10-05", "deliveryNotes": "Gate code 1234. Deliver to the rear entrance.", "lineItems": [ { "salesOrderLineItemId": "…", "quantity": 2 }, { "salesOrderLineItemId": "…", "quantity": 1 } ] } ``` Put the customer's delivery instructions from your checkout in `deliveryNotes`. The delivery note prints them, so your warehouse and the carrier see them. Leave it out if there are none. To ship the order in parts, add one dispatch for each part. The quantities on the dispatches must add up to each line item's quantity. Creating a dispatch doesn't allocate stock, so it's safe to do on a draft. The `201` response returns the dispatch, and its `ETag` is the order's new `ETag`. Skip this step if the order is a call-off (`callOff: true`): a call-off can be activated without dispatches. 4. **Activate the order.** Call `POST /api/v1/sales-orders/{id}/activate`, with a new `Idempotency-Key` and the `ETag` from the dispatch's `201` response in an `If-Match` header. Send it without a body. It returns `200` with `{ "applied": true, "salesOrder": … }`. The order is now part of your workflow, and your staff allocate, pick and ship its dispatches in Omono. Learn more about [ETags](/docs/writing#etags) and [lifecycle actions](/docs/writing#lifecycle-actions). ## Errors to handle Each code links to its own page. The [Errors](/docs/errors) guide explains the format of every error, and [Retry requests safely](/docs/writing#idempotency) explains how keys work. | Status | Code | What to do | | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 422 | [`missing-required-field`](/docs/errors/missing-required-field) | You left out a field that's required, and `errors[].field` names it. For example, `addressId` is required unless `customerCollection` is `true`, and your organisation's settings can require `customerOrderNo`. The error also comes when the customer has no account manager. Nothing was written, and no order number was used. | | 422 | [`validation-failed`](/docs/errors/validation-failed), [`invalid-reference`](/docs/errors/invalid-reference) | A value is wrong, and `errors[].field` names it, for example `lineItems[1].stockItemId`. Fix the data instead of retrying the same request. Omono reports the first problem it finds, so a fixed request can name another field. | | 409 | [`duplicate-external-ref`](/docs/errors/duplicate-external-ref) | You sent this order before: `conflictingId` is the order Omono already has, so read it instead of creating it again. | | 409 | [`dispatches-incomplete`](/docs/errors/dispatches-incomplete) | On `/activate`, the order's dispatches don't cover all of its line items. Each entry in `errors` names a line item and how much of it is on dispatches. Add a dispatch for the rest, then retry `/activate` with the new `ETag`. | | 409 | [`no-line-items`](/docs/errors/no-line-items) | On `/activate`, the order has no line items, and `errors[].field` is `lineItems`. Add them with a `PATCH`, then retry `/activate` with the new `ETag`. | | 409 | [`company-archived`](/docs/errors/company-archived) | The customer is archived. Ask your staff whether to unarchive it. | | 412 | [`precondition-failed`](/docs/errors/precondition-failed) | On `/activate`, someone changed the draft after you created it. Read the order again, check it, and retry `/activate` with the new `ETag`. You can reuse the same `Idempotency-Key`, because Omono doesn't store a failed request. | | 409 | [`idempotency-in-progress`](/docs/errors/idempotency-in-progress) | A request with the same key is still running. Wait for the number of seconds in `Retry-After`, then retry. | | 409 | [`idempotency-key-reuse`](/docs/errors/idempotency-key-reuse) | You sent a key again to the same operation with a different body, so your integration is using one key for two orders. Give each shop order its own key, and send that same key only when you retry that order. | | 409 | [`create-incomplete`](/docs/errors/create-incomplete) | An earlier attempt with this key stopped part-way, and someone has changed the draft order it left. Don't create the order again, and don't switch to a new key. Read the draft that `keptDocument` names, and finish it with a `PATCH` or leave it to your staff. | | 429, 503 | [`rate-limited`](/docs/errors/rate-limited), [`temporarily-unavailable`](/docs/errors/temporarily-unavailable), [`request-timeout`](/docs/errors/request-timeout) | Retry the same request, with the same `Idempotency-Key`, after the number of seconds in `Retry-After`. If there's no `Retry-After` header, wait 60 seconds. | | 500 | [`internal-error`](/docs/errors/internal-error) | If the error names a draft order in `keptDocument`, don't retry and don't use a new key. Read that draft, add the line items that aren't in its `createdLineItems` with a `PATCH`, and then activate it. Otherwise, retry once with the same `Idempotency-Key`. [Recover from a failed create](/docs/writing#if-a-create-fails) explains both cases. | --- # Mirror your data in another system Use this recipe to keep a copy of your Omono data somewhere else, such as a business intelligence (BI) tool, a CRM or a data warehouse. You load everything once, and then check for changes and deleted records every few minutes. Omono lists deleted records as events, in `GET /events`. [Keeping in sync](/docs/syncing) explains each rule in more depth. Every request in this recipe sends your API key in an `Authorization: Bearer ` header. The recipe only reads, so it never needs an `Idempotency-Key`. Paths are relative to `https:///api/v1`, and the examples show the full path. You need the read scope of each kind of record you copy. A complete mirror needs `companies:read`, `sales:read`, `purchasing:read`, `stock:read`, `tasks:read`, `documents:read` and `reference:read`. ## Load everything once 1. **Note where the list of deleted records ends.** Call `GET /events?limit=1`, and store the `latestSequence` from the response as your saved sequence. Ignore the response's `data` and `hasMore`, because only `latestSequence` matters here. Because you do this first, a record that's deleted while your load runs is still caught. 2. **Read every record in each list you mirror**, starting from the beginning of time: ```http GET /api/v1/?updated_since=1970-01-01T00:00:00.000Z&sort=updated&limit=200 ``` Add the parameters each list needs, so that you get archived records and the related records that belong to each one: | List | Add | | ------------------ | ----------------------------------------- | | `/companies` | `archived=any&include=contacts,addresses` | | `/quotes` | `include=lineItems` | | `/sales-orders` | `include=lineItems,dispatches` | | `/credit-notes` | `include=lineItems` | | `/invoices` | Nothing more. | | `/purchase-orders` | `include=lineItems,deliveries` | | `/stock-items` | `archived=any` | | `/documents` | `archived=any` | | `/tasks` | Nothing more. | A company's contacts come with it, and a purchase order's deliveries come with it. If you mirror only part of your data, you can read them on their own instead: `GET /contacts` lists the contacts of all your companies (add `archived=any`), and `GET /deliveries` lists the deliveries of all your purchase orders, with each one's purchase order and supplier. Keep asking for the next page with `nextCursor` until `hasMore` is `false`. Upsert each record by its `id`: update your copy if you have one, and add the record if you don't. For each list, store the highest `updated` value you saw. If a list is empty, keep `1970-01-01T00:00:00.000Z` as its mark until a record arrives. 3. **Copy the reference lists.** Reference lists, such as tax rates, currencies, users and workflow statuses, have no `updated` time and don't take `updated_since` or `sort`. Read each one in full, with `archived=any` on the lists that take it, and read `GET /organisation` too. Replace your copy of each list with what you receive. ## Then, every few minutes 1. **Read what changed.** For each list, call: ```http GET /api/v1/?updated_since=&sort=updated&limit=200 ``` Add the same parameters as in your first load, from the table above. Page through the results, upsert each record by its `id`, and store the new highest `updated`. The 60-second overlap is deliberate, because a change can become visible a few seconds after the time in its `updated` field. It means you'll see some records twice, so always upsert, and never insert. 2. **Remove deleted records.** Call `GET /events?since=`. For each event whose `op` is `deleted`, delete your copy of the record that its `resource` and `resourceId` name, and skip any event with another `op`. Store `nextSince` as your new saved sequence, even when the page is empty, and call again while `hasMore` is `true`. Events about tasks are the one exception. Omono also writes a `tasks` event when someone makes a task private, which hides the task from the API. So for a `tasks` event, call `GET /tasks/{id}` first. Delete your copy only if you get a `404`. If you get a `200`, upsert the task instead. 3. **Refresh the reference lists now and then.** They change rarely, so read them again every hour or once a day, rather than on every poll. That keeps you well inside your daily request limit, which [Rate limits](/docs/limits) explains. Run the refresh at a random minute, not on the hour, as [Spread your polls over time](/docs/limits#spread-polls) explains. ## Keep your copy accurate - Each time you read a quote, sales order, credit note, purchase order, dispatch or delivery, replace all of its `lineItems` in your copy. Never merge them line by line. In the same way, replace a company's contacts and addresses, and a sales order's dispatches, each time the company or order comes back. - A dispatch's `legalTransitions`, and the `blockedBy` list in each of them, are worked out when you read the order. They can change without changing the order's `updated` time, for example when someone creates a task that blocks shipping. Don't act on your copy of them: read the order again just before you move a dispatch. - Deleting a document in Omono archives it, so it comes back in your poll with `archived` set to `true`, and it doesn't create an event. - For reports on line items, such as what you've sold of each stock item, `GET /sales-order-lines` lists the line items of all your sales orders, Draft and Cancelled orders included, with their order's number, customer, status, currency and exchange rate. A line item's prices and costs are in its order's currency. Don't mirror your orders from it: a line item that staff remove leaves the list, and no event tells you. Keep your orders in step with `GET /sales-orders`, which returns each changed order with all its line items. - A record can come back with no change that you can see. Compare it with your copy before you act on it. - Ignore fields you don't recognise, and accept values you don't recognise, such as a new status. Omono can add both at any time. ## Errors to handle | Status | Code | What to do | | -------- | ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 410 | `events-expired` | Your saved sequence is older than 30 days, or higher than `latestSequence`, for example because it comes from before a sandbox reset or a restore. Load everything again, and start reading events from the `latestSequence` in the `410` response. | | 422 | `validation-failed` | If `errors[].field` is `cursor`, Omono can't use the cursor you sent. On a list, start again without a cursor. On `GET /events`, poll again with `since` set to your saved sequence. | | 404 | `not-found` | On a `GET` of a single record by its own ID, such as `GET /tasks/{id}`, this means the record is gone. Remove your copy. A `404` from `GET /documents/{id}/content` can also mean that the document is archived, so read the document itself before you remove your copy. A `404` with the code `route-not-found` means the path is wrong, not that the record is gone, so keep your copy. | | 409 | `document-too-large` | A record on the page has more than 10,000 related records, or more than 32 MB of JSON with them, so retrying won't help. Send the same request again with the same `cursor` but without `include`, to get that page without related records, then carry on from its `nextCursor` with `include`. Read the related records of the other records on that page on their own, and ask your staff to look at the large record in Omono. | | 429, 503 | `rate-limited`, `temporarily-unavailable`, `request-timeout` | Wait for the number of seconds in `Retry-After`, then carry on from where you stopped. | --- # Ship and invoice a dispatch Use this recipe to ship a dispatch and raise its invoice from your own system. In Omono, a sales order ships in one or more dispatches, and each dispatch moves through your organisation's workflow statuses. The last one is the final status, which is the status whose type is `final`. Moving a dispatch to it ships the dispatch and invoices it. Every request in this recipe sends your API key in an `Authorization: Bearer ` header, and every `POST` and `PATCH` also sends an `Idempotency-Key`, so a prompt retry doesn't do the work twice. Paths are relative to `https:///api/v1`, and the examples show the full path. > **Note:** The sales order write operations are in beta, and you can use > this recipe once they appear in the [API reference](/docs#tag/dispatches) > for your platform. A dispatch can come from your staff in Omono, or from the API, as [Plan the dispatches for an order](/docs/recipes/plan-dispatches) shows. Your staff then pick it in Omono. Picking is when staff collect a dispatch's goods and record which stock they took. This recipe moves a dispatch to another status, including the final one. [Dispatches and invoicing](/docs/workflow) explains the rules in full. You need the scopes `sales:read`, `sales:write` and `reference:read`. The reference scope lets you look up courier IDs with `GET /couriers`. To find a task that stops a dispatch shipping, your key also needs `tasks:read`. ## Steps 1. **Wait until the dispatch can ship.** When staff save a dispatch's picking in Omono, the order's `updated` time changes. So you can find orders that may be ready by polling `GET /sales-orders?updated_since=