AnkiConnect

repository·master·Indexed 41 days ago

https://github.com/amikey/anki-connect

A plugin that enables external applications to communicate with Anki via a RESTful API. It allows developers to programmatically manage decks, notes, and cards, handle media files, and trigger Anki GUI actions using JSON-encoded HTTP POST requests on port 8765.

Tokens
3K
Snippets
8
Records
13
Agent score
3%

What's inside AnkiConnect

  1. How AnkiConnect's RESTful API works

    master

    AnkiConnect 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 (use 5 for 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 is null.

    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}));
        });
    }
  2. Install AnkiConnect

    master

    AnkiConnect is installed as an Anki add-on. Follow these steps:

    1. In Anki, navigate to Tools > Add-ons > Browse & Install.
    2. Enter the code 2055492159 into the Code text box and click OK.
    3. Restart Anki when prompted.

    Important: Anki must remain running in the background for external applications to communicate with it via the network interface.

    Code: 2055492159
  3. Verify AnkiConnect is running

    master
    To confirm that the AnkiConnect server is active and listening, open your web browser and navigate to http://localhost:8765. If successful, you will see a message displaying the version number (e.g., AnkiConnect v.5).
    http://localhost:8765
  4. Disable App Nap for Anki on macOS

    master

    On macOS, the 'App Nap' feature can suspend Anki when it is not the active window, which causes AnkiConnect to stop responding. To prevent this, disable App Nap for Anki using the Terminal:

    1. Open the Terminal application.
    2. Run the following command: defaults write net.ichi2.anki NSAppSleepDisabled -bool true
    3. Restart Anki.
    defaults write net.ichi2.anki NSAppSleepDisabled -bool true
  5. Configure Windows Firewall for AnkiConnect

    master
    When starting Anki with AnkiConnect, Windows may trigger a firewall dialog. You must allow/unblock the Anki application to permit the local server to host the network interface required for external communication.
  6. Manage Media Files

    master

    Actions for interacting with Anki's media folder:

    • storeMediaFile: Saves a base64-encoded file to the media folder. To prevent Anki from cleaning up the file, prefix the filename with an underscore (e.g., _filename.ext).
    • retrieveMediaFile: Returns the base64-encoded contents of a file. Returns false if not found.
    • deleteMediaFile: Deletes a file from the media folder.
    // Example of 'storeMediaFile'
    {
        "action": "storeMediaFile",
        "version": 5,
        "params": {
            "filename": "_hello.txt",
            "data": "SGVsbG8sIHdvcmxkIQ=="
        }
    }
  7. Manage Anki Decks

    master

    Actions for interacting with Anki's deck structure:

    • deckNames: Returns a list of all deck names.
    • deckNamesAndIds: Returns an object mapping deck names to their IDs.
    • getDecks: Accepts an array of card IDs and returns an object where keys are deck names and values are arrays of card IDs belonging to those decks.
    • changeDeck: Moves specified card IDs to a target deck (creates the deck if it doesn't exist).
    • deleteDecks: Deletes decks by name. Use params.cardsToo: true to also delete the cards within them; otherwise, cards are moved to the default deck.
    • getDeckConfig: Returns the configuration object for a specific deck.
    • saveDeckConfig: Saves a configuration object for a deck. Returns true on success.
    • setDeckConfigId: Assigns a specific configuration group ID to a list of decks.
    • cloneDeckConfigId: Clones an existing configuration group to create a new one. Returns the new ID.
    • removeDeckConfigId: Removes a configuration group by ID.
  8. Invoke Anki Graphical User Interface (GUI) actions

    master

    These actions trigger UI elements within the Anki application:

    • guiBrowse: Opens the Card Browser with a specific query.
    • guiAddCards: Opens the Add Cards dialog.
    • guiCurrentCard: Returns info about the card currently being reviewed (returns null if not in review mode).
    • guiStartCardTimer: Starts/resets the timer for the current card.
    • guiShowQuestion / guiShowAnswer: Shows the question or answer text for the current card.
    • guiAnswerCard: Answers the current card with a specific ease (e.g., params.ease: 1). Note: the answer must be displayed before calling this.
    • guiDeckOverview / guiDeckBrowser: Opens the Deck Overview or Deck Browser dialogs.
    • guiDeckReview: Starts a review session for a specific deck.
    • guiExitAnki: Schedules Anki to close gracefully (asynchronous).

    Note: Most GUI actions return true on success or null if no specific return value is applicable.

  9. Manage Anki Cards

    master

    Actions for interacting with individual cards:

    • suspend: Suspends specified card IDs.
    • unsuspend: Unsuspends specified card IDs.
    • areSuspended: Returns an array of booleans indicating the suspension status of the provided card IDs.
    • areDue: Returns an array of booleans indicating if cards are due. Note: cards in learning queues with intervals > 20 mins are treated as not due.
    • getIntervals: Returns an array of recent intervals for card IDs. If params.complete is true, returns a 2D array of all intervals.
    • findCards: Returns an array of card IDs matching a query (high performance version of guiBrowse).
    • cardsToNotes: Returns an unordered array of unique note IDs for the provided card IDs.
    • cardsInfo: Returns detailed information (fields, CSS, deck, interval, etc.) for a list of card IDs.
  10. Miscellaneous AnkiConnect actions

    master

    These actions handle API metadata and batch processing.

    • version: Gets the current API version. Use this first to verify connectivity. Returns an integer.
    • upgrade: Displays a confirmation dialog in Anki to upgrade AnkiConnect from the GitHub master branch. Returns a boolean.
    • multi: Performs multiple actions in a single request. The params object should contain an actions array of request objects. Returns an array of results in the same order.
    // Example of 'multi' action
    {
        "action": "multi",
        "version": 5,
        "params": {
            "actions": [
                {"action": "deckNames"},
                {
                    "action": "browse",
                    "params": {"query": "deck:current"}
                }
            ]
        }
    }
  11. Create and Update Notes

    master

    Actions for managing Anki notes:

    • addNote: Creates a single note. Supports optional audio parameter to download and embed files. audio requires url, filename, and optionally skipHash. The fields member of the audio object specifies which field should play the audio.
    • addNotes: Creates multiple notes in one request. Returns an array of note IDs (or null for failed notes).
    • canAddNotes: Validates an array of note parameters and returns an array of booleans indicating if they are valid for creation.
    • updateNoteFields: Modifies the field values of an existing note using its ID.
    • addTags: Adds tags to a list of note IDs.
    • removeTags: Removes tags from a list of note IDs.
    • getTags: Returns a list of all tags used by the user.
    • findNotes: Returns an array of note IDs matching a query string (uses guiBrowse syntax).
    • notesInfo: Returns detailed information (fields, tags, model, cards) for a list of note IDs.
    // Example of 'addNote' with audio
    {
        "action": "addNote",
        "version": 5,
        "params": {
            "note": {
                "deckName": "Default",
                "modelName": "Basic",
                "fields": {
                    "Front": "front content",
                    "Back": "back content"
                },
                "tags": ["yomichan"],
                "audio": {
                    "url": "https://example.com/audio.mp3",
                    "filename": "audio.mp3",
                    "skipHash": "7e2c2f954ef6051373ba916f000168dc",
                    "fields": "Front"
                }
            }
        }
    }