Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

MoyskladAPI

Асинхронная библиотека для работы с API МойСклад

PyPI version Downloads Tests Coverage Checked with mypy API Version Python

Установка

Требуется Python 3.12+.

pip install moyskladapi

Примеры использования

Создание, обновление и удаление товара

import asyncio

from moyskladapi import MoyskladAPI
from moyskladapi.types import Product


async def main():
    async with MoyskladAPI(token="your_token_here") as api:
        product = await api.create_product(Product(name="Тестовый товар"))
        print(f"Создан: {product.name} [{product.id}]")

        product = await api.update_product(product.id, Product(description="Описание товара"))
        print(f"Описание: {product.description}")

        await api.delete_product(product.id)
        print("Удалён")


asyncio.run(main())

Фильтрация товаров

import asyncio

from moyskladapi import MoyskladAPI, F


async def main():
    async with MoyskladAPI(token="your_token_here") as api:
        results = await api.get_products(
            filters=[F.archived == False, F.weight > 1.0],
            expand="supplier",
            limit=10,
        )
        for p in results.rows:
            print(f"{p.name}  |  поставщик: {p.supplier.name if p.supplier else '—'}")


asyncio.run(main())

Остатки

import asyncio

from moyskladapi import MoyskladAPI


async def main():
    async with MoyskladAPI(token="your_token_here") as api:
        stock = await api.get_stock_current()
        low = [s for s in stock.rows if s.quantity and s.quantity < 5]
        print(f"Заканчиваются: {len(low)} позиций")


asyncio.run(main())

Постраничный обход

Методы iter_* обходят выборку лениво: страницы подгружаются по мере необходимости, а обработанные — освобождаются. Память не растёт с размером каталога, поэтому это способ по умолчанию.

import asyncio

from moyskladapi import MoyskladAPI


async def main():
    async with MoyskladAPI(token="your_token_here") as api:
        async for product in api.iter_products():
            print(product.name)


asyncio.run(main())

Если нужен готовый список, у методов get_* есть параметр auto_paginate — он проходит все страницы и возвращает их одним MetaArray:

everything = await api.get_products(auto_paginate=True)
print(f"Всего: {len(everything.rows)}")

Пользуйтесь им только для небольших выборок: все записи остаются в памяти одновременно. На каталоге в 20 000 товаров это около 23 МБ против 2 МБ у iter_products(), и дальше разница растёт линейно. Список из iter_* собирается одной строкой, если он действительно нужен:

everything = [product async for product in api.iter_products()]

Лента событий документа

import asyncio

from moyskladapi import MoyskladAPI
from moyskladapi.types import Note


async def main():
    async with MoyskladAPI(token="your_token_here") as api:
        order_id = "e4609c69-00bc-11ef-ac12-00120000001a"

        note = await api.create_note("customerorder", order_id, Note(description="Согласовано"))
        feed = await api.get_notes("customerorder", order_id)
        print(f"Событий: {len(feed.rows)}")

        await api.delete_note("customerorder", order_id, note.id)


asyncio.run(main())

Обработка ошибок

import asyncio

from moyskladapi import MoyskladAPI, MoyskladAPIError
from moyskladapi.types import Product


async def main():
    async with MoyskladAPI(token="your_token_here") as api:
        try:
            await api.create_product(Product())
        except MoyskladAPIError as exc:
            print(f"HTTP {exc.http_status}: {exc}")
            for error in exc.errors:
                print(f"  код {error.code}: {error.error_message or error.error}")


asyncio.run(main())

Ответы с кодом 429 повторяются автоматически с учётом заголовка X-Lognex-Retry-TimeInterval (до BaseSession.MAX_RETRIES попыток).

Лицензия

MIT

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

moyskladapi-1.0.0rc1.tar.gz (125.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

moyskladapi-1.0.0rc1-py3-none-any.whl (416.5 kB view details)

Uploaded Python 3

File details

Details for the file moyskladapi-1.0.0rc1.tar.gz.

File metadata

  • Download URL: moyskladapi-1.0.0rc1.tar.gz
  • Upload date:
  • Size: 125.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for moyskladapi-1.0.0rc1.tar.gz
Algorithm Hash digest
SHA256 2561e16280588420eea9755c8e569e6a03e35961a33b43a9ed1a1fa23e4a9912
MD5 d831bbf61e65d389d637f0b808a53fca
BLAKE2b-256 c235e851d91a1ab6440e4df39341eb4dd8ec8bf40390126d8c216b4e8fa8a5e3

See more details on using hashes here.

Provenance

The following attestation bundles were made for moyskladapi-1.0.0rc1.tar.gz:

Publisher: pypi_release.yml on serdukow/moyskladapi

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file moyskladapi-1.0.0rc1-py3-none-any.whl.

File metadata

  • Download URL: moyskladapi-1.0.0rc1-py3-none-any.whl
  • Upload date:
  • Size: 416.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for moyskladapi-1.0.0rc1-py3-none-any.whl
Algorithm Hash digest
SHA256 2e25307af6f4f1e2bf383ba6ae625d93c16a2e8d512c13329fac4a27dbde1859
MD5 edadf061f0a06bd57e5e7134ae13f907
BLAKE2b-256 5259124f14b1e2e18f480d9e8ee17ef04f676113c21006f3628f551b8822124e

See more details on using hashes here.

Provenance

The following attestation bundles were made for moyskladapi-1.0.0rc1-py3-none-any.whl:

Publisher: pypi_release.yml on serdukow/moyskladapi

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

1.0.0rc1 This release

2 files

0.14.0

2 files

0.13.0

2 files

0.12.0

2 files

0.11.0

2 files

0.10.1

2 files

0.10.0

2 files

0.9.3

2 files

0.9.2

2 files

0.9.1

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page