How AnkiConnect's RESTful API works
masterAnkiConnect exposes Anki features via a RESTful API. When Anki is running, the plugin initializes a minimal HTTP server on port 8765. External applications communicate with it by sending HTTP POST requests to http://127.0.0.1:8765.
Request Format
Every request must be a JSON-encoded object containing:
action: The name of the API method to execute.version: The API version number (use5for current features).params: (Optional) A set of contextual parameters required by the specific action.
Response Format
AnkiConnect responds with a JSON object containing:
result: The return value of the executed API (can be any valid JSON type).error: A description of any exception thrown during execution. If the execution was successful, this value isnull.
Network Binding
By default, the server only binds to 127.0.0.1 (localhost). To allow access over a network, set the environment variable ANKICONNECT_BIND_ADDRESS to 0.0.0.0 to bind to all network interfaces.
// Example of a modern JavaScript invocation
function ankiConnectInvoke(action, version, params={}) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.addEventListener('error', () => reject('failed to connect to AnkiConnect'));
xhr.addEventListener('load', () => {
try {
const response = JSON.parse(xhr.responseText);
if (response.error) {
throw response.error;
} else {
if (response.hasOwnProperty('result')) {
resolve(response.result);
} else {
reject('failed to get results from AnkiConnect');
}
}
} catch (e) {
reject(e);
}
});
xhr.open('POST', 'http://127.0.0.1:8765');
xhr.send(JSON.stringify({action, version, params}));
});
}