Skip to main content

avito-python-sdk

PyPI version Python versions CI License

Асинхронная Python SDK-библиотека для Avito API с typed response models.

  • Пакет в pip: avito-python-sdk
  • Импорт в коде: pyavitoapi
  • Лицензия: AGPL-3.0-only

Установка

Через pip

pip install avito-python-sdk

С фиксацией версии

pip install avito-python-sdk==0.2.3

Через requirements.txt

avito-python-sdk==0.2.3
pip install -r requirements.txt

Для разработки

pip install -e .[dev]

Быстрый старт (до 5 минут)

import asyncio
import os

from pyavitoapi import AvitoAsyncClient


async def main() -> None:
    async with AvitoAsyncClient(
        client_id=os.environ["AVITO_CLIENT_ID"],
        client_secret=os.environ["AVITO_CLIENT_SECRET"],
    ) as client:
        headers = await client.auth.auth_header()
        me = await client.user.get_user_info_self(path_params={}, headers=headers)
        print(me.model_dump(exclude_none=True))


if __name__ == "__main__":
    asyncio.run(main())

Готовые сценарии

1) Профиль пользователя

headers = await client.auth.auth_header()
me = await client.user.get_user_info_self(path_params={}, headers=headers)
print(me.id, me.name, me.email)

2) Чаты Avito Messenger

headers = await client.auth.auth_header()
chats = await client.messenger.get_chats_v2(
    path_params={"user_id": 123456789},
    query={"limit": 50, "offset": 0},
    headers=headers,
)
print(chats.model_dump(exclude_none=True))

3) Отправка сообщения

headers = await client.auth.auth_header()
result = await client.messenger.post_send_message(
    path_params={"user_id": 123456789, "chat_id": "CHAT_ID"},
    json_body={"type": "text", "message": {"text": "Здравствуйте!"}},
    headers=headers,
)
print(result.model_dump(exclude_none=True))

Webhooks Avito (быстрый старт)

Webhook flow:

  1. Поднимите публичный HTTPS endpoint в вашей системе.
  2. Подпишите URL через client.messenger.post_webhook_v3(...).
  3. На входящем endpoint быстро возвращайте 200 OK и обрабатывайте payload асинхронно.
  4. Проверяйте подписки через client.messenger.get_subscriptions(...).
  5. При необходимости отключайте подписку client.messenger.post_webhook_unsubscribe(...).

Пример подписки:

headers = await client.auth.auth_header()
response = await client.messenger.post_webhook_v3(
    json_body={"url": "https://your-domain.com/avito/webhook?token=secret123"},
    headers=headers,
)
print(response.model_dump(exclude_none=True))

Минимальный webhook endpoint (FastAPI):

from fastapi import FastAPI, HTTPException, Request

app = FastAPI()

@app.post("/avito/webhook")
async def avito_webhook(request: Request):
    if request.query_params.get("token") != "secret123":
        raise HTTPException(status_code=403, detail="forbidden")
    event = await request.json()
    # TODO: push event to queue and return quickly
    return {"ok": True}

Typed response models

headers = await client.auth.auth_header()
user = await client.user.get_user_info_self(path_params={}, headers=headers)

print(user.id, user.email)
print(user.model_dump(exclude_none=True))

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

from pyavitoapi.transport.errors import (
    AvitoApiError,
    AvitoAuthError,
    AvitoRateLimitError,
    AvitoTransportError,
    AvitoValidationError,
)

try:
    headers = await client.auth.auth_header()
    await client.user.get_user_info_self(path_params={}, headers=headers)
except AvitoRateLimitError as e:
    print("retry_after:", e.retry_after)
except AvitoValidationError as e:
    print("schema errors:", e.details)
except AvitoAuthError as e:
    print("auth error:", e)
except AvitoTransportError as e:
    print("network error:", e)
except AvitoApiError as e:
    print("api error:", e.status_code, e.payload)

Интеграционные примеры

Готовые шаблоны лежат в директории examples/:

  • examples/basic_user_info.py
  • examples/fastapi_app/main.py
  • examples/django_app/avito_client.py
  • examples/celery_app/tasks.py
  • examples/webhooks/fastapi_receiver.py
  • examples/webhooks/subscribe.py
  • examples/webhooks/unsubscribe.py
  • examples/.env.example

Перегенерация SDK

python tools/fetch_specs.py
python tools/patch_specs.py
python tools/generate_clients.py
python tools/build_coverage_report.py

Тесты и сборка

pytest -q
python -m build

Релиз и публикация

  • Release Bump And Tag:
    • автоматически увеличивает patch-версию,
    • создает commit и тег vX.Y.Z,
    • автоматически запускает Publish To PyPI.
  • Publish To PyPI:
    • собирает wheel/sdist,
    • публикует пакет в PyPI через Trusted Publishing (OIDC).

Поддержка и вклад

  • Bug/Feature шаблоны: .github/ISSUE_TEMPLATE/
  • PR шаблон: .github/pull_request_template.md
  • Руководство для контрибьюторов: CONTRIBUTING.md
  • Политика безопасности: SECURITY.md
  • FAQ: docs/FAQ.md
  • Troubleshooting: docs/TROUBLESHOOTING.md

Полезные ссылки

  • Примеры интеграции: examples/README.md
  • Growth metrics: docs/GROWTH_METRICS.md
  • Материалы для анонсов: docs/articles/
  • Руководство по использованию: docs/USAGE.md
  • Endpoint matrix: docs/endpoint-matrix.md
  • Known quirks: docs/known-quirks.md
  • Coverage report: docs/final-compliance-report.md
  • Typed response map: docs/typed-response-map.json
  • Release notes: RELEASE_NOTES.md

Metadata

Release files for avito-python-sdk 0.2.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for avito-python-sdk 0.2.4
File Size Uploaded
avito_python_sdk-0.2.4.tar.gz 534.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for avito-python-sdk 0.2.4
File Interpreter ABI Platform
avito_python_sdk-0.2.4-py3-none-any.whl Python 3 none any Details

Total release size: 634.3 kB

Release files / avito_python_sdk-0.2.4.tar.gz

Download URL avito_python_sdk-0.2.4.tar.gz
Size 534.0 kB
Tags Source
SHA-256 checksum
How to use checksums
7622681b70bc364ebef3a031af9c7bc70d4b818f2a00a2b0b727836086133d96
BLAKE2b-256 checksum
How to use checksums
b65ec91d012d84db31f123fcc8d3b607d1d3fb36d78784c118fd0d9ce7ccc722
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 5, 2026.

Transparency log

Release files / avito_python_sdk-0.2.4-py3-none-any.whl

Download URL avito_python_sdk-0.2.4-py3-none-any.whl
Size 100.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2c08a357d5e642d0c6636435006ff23c3ae8eb764cace3595881b2e6aca8eef9
BLAKE2b-256 checksum
How to use checksums
890e534d2e34f6150365ab075b0583f743c65c743426cc631ebc18f6f778cf19
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 5, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.2.4 This release

2 release files

0.2.3

2 release 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