Currently it appears that the API does not accept data in the form of a JSON-stringified body. So, for example, in Node the following code does not work:
async function api({
route,
method = "get",
data,
}: {
route: string;
method?: "get" | "post" | "put" | "delete";
data?: Record<string, unknown>;
}) {
const result = await fetch(`${API_ROOT}${route}?auth_token=${API_KEY}`, {
method,
body: JSON.stringify(data),
});
if (!result.ok) {
throw new Error(`${result.status} ${result.statusText}`);
}
return result.json();
}
Whereas this code does work:
async function api({
route,
method = "get",
data,
}: {
route: string;
method?: "get" | "post" | "put" | "delete";
data?: Record<string, unknown>;
}) {
const form = new URLSearchParams();
if (data) {
Object.entries(data).forEach(([key, value]) => {
form.append(key, value as string);
});
}
const result = await fetch(`${API_ROOT}${route}?auth_token=${API_KEY}`, {
method,
body: data && form,
});
if (!result.ok) {
throw new Error(`${result.status} ${result.statusText}`);
}
return result.json();
}
I would prefer to use the former code since it’s easier both to read and to write, and requires less code. Could the API be modified to accept both URL-encoded form data (the second example) and JSON bodies (the first example)?