https://github.com/kitschpatrol/yanki-connect
A fully-typed Anki-Connect API client.
https://github.com/kitschpatrol/yanki-connect
anki anki-connect api client flashcards npm-package spaced-repetition yanki
Last synced: 3 months ago
JSON representation
A fully-typed Anki-Connect API client.
- Host: GitHub
- URL: https://github.com/kitschpatrol/yanki-connect
- Owner: kitschpatrol
- License: mit
- Created: 2024-05-30T08:23:19.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2025-03-26T05:17:15.000Z (3 months ago)
- Last Synced: 2025-04-04T04:32:35.450Z (3 months ago)
- Topics: anki, anki-connect, api, client, flashcards, npm-package, spaced-repetition, yanki
- Language: TypeScript
- Homepage:
- Size: 1.84 MB
- Stars: 18
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
- License: license.txt
Awesome Lists containing this project
README
# yanki-connect
[](https://npmjs.com/package/yanki-connect)
[](https://opensource.org/licenses/MIT)**A fully-typed Anki-Connect API client.**
## Overview
Yanki Connect exists to streamline development of JavaScript and TypeScript applications that use Alex Yatskov's [Anki-Connect](https://ankiweb.net/shared/info/2055492159) add-on to interface with the [Anki](https://apps.ankiweb.net) spaced repetition flashcard software. The library provides extensive type annotations for the Anki-Connect API, and includes a turn-key client implementation.
The "Y" prefix in "Yanki" is in the "Yet another" naming tradition; a nod to Anki's robust and occasionally duplicative ecosystem of third-party tools. (Also, appropriately, Yankī are a variety of [truant youth](https://en.wikipedia.org/wiki/Yankee#/media/File:ヤンキー.jpg).)
This library is used in the [`yanki`](https://github.com/kitschpatrol/yanki) CLI tool, which in turn powers the [`yanki-obsidian`](https://github.com/kitschpatrol/yanki-obsidian) [Obsidian](https://obsidian.md/) plugin.
## Features
- **Action method organization + convenience methods**\
Instead of putting all 115 methods in a single namespace, action convenience methods are organized into the same groups used in the [Anki-Connect documentation](https://git.sr.ht/~foosoft/anki-connect/tree/ab4d964d96712788889eb35d79471966aaf17ef6/item/README.md#supported-actions), to simplify auto-complete discoverability.- **Low-level access through the provided `invoke` method**\
If you don't want to use the convenience methods, an `invoke(action, params)` method is also exposed on the YankiConnect class for direct interaction with the Anki-Connect API.- **Inline documentation and full type annotations**\
The action method types are annotated with JSDoc-style comments to provide documentation and links in your IDE's auto-complete pop-over.- **Errors from the API are thrown**\
Instead of returning an object with `result` and `error` keys, Yanki Connect's convenience methods checks for errors in responses from the Anki-Connect API, and throws them as errors. This gives more convenient access to the result, but means you'll need to do your own error handling._Note that this only applies to the convenience methods (`client.card.*`, etc.) the `invoke(action, params)` method returns the Anki-Connect API's raw `{"result": ..., "error": null}` responses._
- **Anki desktop app auto-launch**\
Perhaps the most precarious aspect of the Anki-Connect add-on is that the Anki desktop application _must_ be running for any of the API calls to work. Yanki Connect tries to sand down this rough edge by (optionally) automatically launching the Anki desktop app if it's not running already.You can enable this behavior by passing a configuration option when the class is instantiated:
```ts
const client = new YankiConnect({ autoLaunch: true })
```_Warning: This feature is experimental, and is currently only supported in a Node environment on macOS._
## Getting started
### Dependencies
Yanki Connect is isomorphic: it runs in the browser and Node 18+ compatible environments (specifically Node `^18.19.0 || >=20.5.0`). The exported APIs are ESM-only. It's implemented in TypeScript and bundles extensive type definitions.
The Anki desktop app (>=2.1.45, released 2021-07-30) with the Anki-Connect add-on installed and configured is also required to do anything useful with the library.
The API calls are written against version [25.2.25.0](https://git.sr.ht/~foosoft/anki-connect/tree/ab4d964d96712788889eb35d79471966aaf17ef6/item/README.md) of the Anki-Connect add-on, released 2025-02-25. You must use either this or a newer version of the Anki-Connect add-on for compatibility with all available calls. A majority of the calls are compatible with older version of the Anki-Connect add-on, but this is at your own risk.
### Installation
Add the library to your project:
```sh
npm install yanki-connect
```## Usage
Yanki Connect aims to be discoverable and self-documenting when used in an environment with a robust autocompletion / language service implementation. (VS Code, for example.)
The library exports the `YankiConnect` class, which groups methods into the same structure of "supported actions" used in the official [Anki-Connect documentation](https://git.sr.ht/~foosoft/anki-connect/tree/ab4d964d96712788889eb35d79471966aaf17ef6/item/README.md#supported-actions).
Here's a simple example:
```ts
import { YankiConnect } from 'yanki-connect'const client = new YankiConnect()
const decks = await client.deck.deckNames()
console.log(decks) // ["Your", "Deck", "Names", "Here"]
```All 115 Anki-Connect actions are exposed under their respective groups, with type data for both parameters and return types:
```ts
client.card.answerCards
client.card.areDue
client.card.areSuspended
client.card.cardsInfo
client.card.cardsModTime
client.card.cardsToNotes
client.card.findCards
client.card.forgetCards
client.card.getEaseFactors
client.card.getIntervals
client.card.relearnCards
client.card.setDueDate
client.card.setEaseFactors
client.card.setSpecificValueOfCard
client.card.suspend
client.card.suspended
client.card.unsuspendclient.deck.changeDeck
client.deck.cloneDeckConfigId
client.deck.createDeck
client.deck.deckNames
client.deck.deckNamesAndIds
client.deck.deleteDecks
client.deck.getDeckConfig
client.deck.getDeckStats
client.deck.getDecks
client.deck.removeDeckConfigId
client.deck.saveDeckConfig
client.deck.setDeckConfigIdclient.graphical.guiAddCards
client.graphical.guiAnswerCard
client.graphical.guiBrowse
client.graphical.guiCheckDatabase
client.graphical.guiCurrentCard
client.graphical.guiDeckBrowser
client.graphical.guiDeckOverview
client.graphical.guiDeckReview
client.graphical.guiEditNote
client.graphical.guiExitAnki
client.graphical.guiImportFile
client.graphical.guiSelectCard
client.graphical.guiSelectNote
client.graphical.guiSelectedNotes
client.graphical.guiShowAnswer
client.graphical.guiShowQuestion
client.graphical.guiStartCardTimer
client.graphical.guiUndoclient.media.deleteMediaFile
client.media.getMediaDirPath
client.media.getMediaFilesNames
client.media.retrieveMediaFile
client.media.storeMediaFileclient.miscellaneous.apiReflect
client.miscellaneous.exportPackage
client.miscellaneous.getActiveProfile
client.miscellaneous.getProfiles
client.miscellaneous.importPackage
client.miscellaneous.loadProfile
client.miscellaneous.multi
client.miscellaneous.reloadCollection
client.miscellaneous.requestPermission
client.miscellaneous.sync
client.miscellaneous.versionclient.model.createModel
client.model.findAndReplaceInModels
client.model.findModelsById
client.model.findModelsByName
client.model.modelFieldAdd
client.model.modelFieldDescriptions
client.model.modelFieldFonts
client.model.modelFieldNames
client.model.modelFieldRemove
client.model.modelFieldRename
client.model.modelFieldReposition
client.model.modelFieldSetDescription
client.model.modelFieldSetFont
client.model.modelFieldSetFontSize
client.model.modelFieldsOnTemplates
client.model.modelNames
client.model.modelNamesAndIds
client.model.modelStyling
client.model.modelTemplateAdd
client.model.modelTemplateRemove
client.model.modelTemplateRename
client.model.modelTemplateReposition
client.model.modelTemplates
client.model.updateModelStyling
client.model.updateModelTemplatesclient.note.addNote
client.note.addNotes
client.note.addTags
client.note.canAddNotes
client.note.canAddNotesWithErrorDetail
client.note.clearUnusedTags
client.note.deleteNotes
client.note.findNotes
client.note.getNoteTags
client.note.getTags
client.note.notesInfo
client.note.notesModTime
client.note.removeEmptyNotes
client.note.removeTags
client.note.replaceTags
client.note.replaceTagsInAllNotes
client.note.updateNote
client.note.updateNoteFields
client.note.updateNoteModel
client.note.updateNoteTagsclient.statistic.cardReviews
client.statistic.getCollectionStatsHTML
client.statistic.getLatestReviewID
client.statistic.getNumCardsReviewedByDay
client.statistic.getNumCardsReviewedToday
client.statistic.getReviewsOfCards
client.statistic.insertReviews
```Note that at the moment, only the latest Anki-Connect API version 6 is supported, and Anki-Connect release >24.7.25.0 is required for compatibility with all features.
### API
#### Configuration
The `YankiConnect` class features sensible defaults that should work fine for most configurations of Anki-Connect, but if you'd like to customize the client, you can pass an argument of type `YankiConnectOptions` with any of the following:
| Key | Type | Description | Default |
| ------------ | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| `host` | `string` | Host where the Anki-Connect service is running. | `'http://127.0.0.1'` |
| `port` | `number` | Port where the Anki-Connect service is running. | `8765` |
| `version` | `AnkiConnectVersion` | Anki-Connect API version. Only API version 6 is supported. | `6` |
| `key` | `string` | Anki-Connect security key. Usually not required. | `undefined` |
| `autoLaunch` | `boolean \| 'immediately'` | Attempt to launch the Anki desktop application if it's not already running.
- `true` will always attempt to open Anki _when a request is made_. This might introduce significant latency on the first launch.
- `false` will never attempt to open Anki. Requests will fail until something or someone opens the Anki app.
- `'immediately'` is a special option that will open Anki when the client is instantiated.
Currently supported on macOS only. | `false` |
### Bundling for the browser
If you're using a build tool like [Vite](https://vite.dev/) to include Yanki Connect in your browser-based project, you'll need to externalize Node-specific dependencies.
Add the following to your Vite config:
```ts
import { defineConfig } from 'vite'
export default defineConfig({
build: {
minify: false,
rollupOptions: {
external: ['open'],
},
},
})
```
### Examples
#### Creating a note
```ts
import { YankiConnect } from 'yanki-connect'
const client = new YankiConnect()
// Assumes 'Default' deck and 'Basic' model exist!
const note = {
note: {
deckName: 'Default',
fields: {
Back: "
I'm the back of the card
\n",Front: "
I'm the front of the card
\n",},
modelName: 'Basic',
tags: ['yanki'],
},
}
const noteId = await client.note.addNote(note)
console.log(noteId) // E.g. 1716968687679
```
#### Listing decks
```ts
import { YankiConnect } from 'yanki-connect'
const client = new YankiConnect()
const decks = await client.deck.deckNames()
console.log(decks) // ["Your", "Deck", "Names", "Here"]
```
#### Direct invocation
```ts
import { YankiConnect } from 'yanki-connect'
const client = new YankiConnect()
const decks = await client.invoke('deckNames')
console.log(decks) // ["Your", "Deck", "Names", "Here"]
```
## Background
### Similar projects
Chen Lijun's [autoanki](https://github.com/chenlijun99/autoanki) also implements a nicely typed Anki-Connect wrapper.
## Maintainers
[@kitschpatrol](https://github.com/kitschpatrol)
## Acknowledgments
Thanks to Alex Yatskov for creating [Anki-Connect](https://ankiweb.net/shared/info/2055492159).
All of the embedded action descriptions in Yanki Connect are directly from the [Anki-Connect project readme](https://git.sr.ht/~foosoft/anki-connect/tree/ab4d964d96712788889eb35d79471966aaf17ef6/item/README.md).
## Contributing
[Issues](https://github.com/kitschpatrol/yanki-connect/issues) and pull requests are welcome.
## License
[MIT](license.txt) © Eric Mika