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://<host>/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 explains.
Generate your client again when the API changes. The 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 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 |
7.26.0 |
| Python | openapi-python-client | 0.29.1 |
| TypeScript | openapi-generator, typescript-fetch |
7.26.0 |
| TypeScript | openapi-typescript with openapi-fetch | 7.13 and 0.17 |
| Java | openapi-generator, java |
7.26.0 |
| C# | openapi-generator, 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 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:
- It lists every company, one page at a time. It sends
nextCursorascursoruntilhasMoreisfalse, as Page through a list explains. - It retrieves one company and keeps the
ETagfrom the response. - It changes the company's
website, and sends theETaginIf-Match. If someone changed the company after the example read it, the change fails with a412error, as Avoid overwriting changes with ETags explains. - It handles that error. Every error has a body in the same format, which
the OpenAPI document calls a
Problem, and the example checks itscode. What an error looks like describes the format. - It adds a contact to the company, with an
Idempotency-Key, so a retry can't add the contact twice, as Retry requests safely explains.
The examples change data, so they call the demo platform. Run them on a
sandbox organisation. 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:
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.
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
PATCHbody with the model's constructor.CompanyUpdate(website=...)sends only the fields you set. Don't build aPATCHbody withfrom_dict()orfrom_json(). They sendnullfor each field you leave out that can be cleared, such as a company'seoriNumber, andnullclears the field. - Read headers with the
_with_http_infomethods.get_company()returns only the company.get_company_with_http_info()also returnsheaders, a plain dictionary whose names are case-sensitive. Omono sends header names in lower case, so readheaders["etag"], notheaders["ETag"]. - Use datetimes with a time zone. A naive
datetimegoes out without an offset, and Omono refuses it with a422error. Send one with a time zone, such asdatetime(2026, 9, 1, tzinfo=timezone.utc). - Read an error's field as
var_field. The generator renames thefieldof each entry inerrors[], so reade.data.errors[0].var_field. The JSON still saysfield.
Python with openapi-python-client#
Generate the client, then install it:
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.
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, aProblemorNone. A read that can answer304is typedAnyas well, and its result isNoneon a304, because a304has no body. So check the type before you use a result.
TypeScript with typescript-fetch#
Generate the client into your project's source folder:
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.
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
Rawmethods.getCompany()returns only the company.getCompanyRaw()returnsraw, which is the fetchResponse, soraw.headers.get('ETag')works, andvalue()returns the company. - Any status other than a
2xxthrowsResponseError, and so does a304. Read theProblemwithProblemFromJSON(await e.response.json()). A304has no body, so checke.response.statusbefore you read the body. - A line item's
deletefield is_deletein 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:
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.
import createClient from 'openapi-fetch';
import type { paths } from './omono';
const omono = createClient<paths>({
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
304yourself. On a304,dataisundefinedanderrorholds noProblem. So when you sendIf-None-Match, checkresponse.status === 304before you use either of them.
Java#
Generate the client with Docker:
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.
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<Company> 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<Company> 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
WithHttpInfomethods.getCompanyWithHttpInfo()returns anApiResponse, and itsgetHeaders()holds theETag.getCompany()returns only the company. - Any status other than a
2xxthrowsApiException, and so does a304. Read theProblemfrome.getResponseBody()withJSON.getGson().fromJson(body, Problem.class). A304has an empty body, so checke.getCode()first. - A list method returns a request builder. Chain the filters you use,
such as
.limit(200).cursor(...), then callexecute().executeWithHttpInfo()also gives you the headers. - Keep
containerDefaultToNull=truein the command. Without it, every list in a request body starts as an empty list. An update then sendslineItems,lineItemOrderorbomas[]although you never set them, and Omono refuses the request with a422error. - To clear a field, use the jersey3 library. okhttp-gson leaves every
field that's
nullout of the request, so it can't clear a field such as a company'seoriNumber. To clear fields, add--library jersey3 --additional-properties=openApiNullable=true,containerDefaultToNull=trueto the command, in place of the--additional-propertiesabove. Thennew 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-UNNAMEDto send aPATCH. With jersey3, header names are case-sensitive, so readgetHeaders().get("etag"), ande.getErrorEntity()returns theProblem.
C##
Generate the client with Docker:
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.
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<ICompaniesApi>();
// List every company, one page at a time.
var page = (await companies.ListCompaniesAsync(limit: 200)).Ok()!;
var everyone = new List<Company>(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<IContactsApi>();
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 areDateTimeOffsetvalues, which always carry an offset. Without it, times areDateTimevalues. ADateTimewhoseKindisn'tUtcgoes out without an offset, and Omono refuses it with a422error. So build eachDateTimewithDateTimeKind.Utc, or useDateTime.UtcNow. - Read a stock item body back as its kind. Sending a
StockItemCreateorStockItemUpdateworks for everykind. To read one back from JSON that you stored, deserialise the type of its kind, such asStockItemCreateNormal, not theStockItemCreatewrapper.
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:
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.
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 useApiKeyLocation.QueryParameter: Omono revokes a key that it finds in a URL. - An error throws the
Problemitself. Any status other than a2xxor a304throws theProblem, a plain object rather than anError, with the HTTP status inresponseStatusCode. Check itscode. A304doesn't throw: the method returnsundefined. - Read headers with
HeadersInspectionOptions. Pass one inoptions, as the example does for theETag, and readgetResponseHeaders()after the call. Each header is a set of values. - Kiota retries by itself. It retries a request that gets a
429,503or504up to three times, after theRetry-Afterdelay, and that includes aPOST. It sends the same headers each time, so send anIdempotency-Keywith 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<ArrayBuffer>(omono.documents.byId(id).content.toGetRequestInformation(), 'ArrayBuffer', undefined). Kiota drops theAuthorizationheader when it follows the redirect to the storage host. - Give an upload its file name.
documents.post()takes aMultipartBody. 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 alinkedEntityTypeofnullas the text"null", which Omono refuses. To remove a task's link, sendlinkedEntityType: 'general'withlinkedEntityId: 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 theKnownschemas, such asKnownOrderStatus. Generate code from the OpenAPI document 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
ETagheader without changing it.