Skip to main content

Async Python SDK for Avito OpenAPI (full endpoint coverage)

Project description

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

Project details


Download files

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

Source Distribution

avito_python_sdk-0.2.4.tar.gz (534.0 kB view details)

Uploaded Source

Built Distribution

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

avito_python_sdk-0.2.4-py3-none-any.whl (100.3 kB view details)

Uploaded Python 3

File details

Details for the file avito_python_sdk-0.2.4.tar.gz.

File metadata

  • Download URL: avito_python_sdk-0.2.4.tar.gz
  • Upload date:
  • Size: 534.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for avito_python_sdk-0.2.4.tar.gz
Algorithm Hash digest
SHA256 7622681b70bc364ebef3a031af9c7bc70d4b818f2a00a2b0b727836086133d96
MD5 94a62e33d76ca629bb9b20f385d3490c
BLAKE2b-256 b65ec91d012d84db31f123fcc8d3b607d1d3fb36d78784c118fd0d9ce7ccc722

See more details on using hashes here.

Provenance

The following attestation bundles were made for avito_python_sdk-0.2.4.tar.gz:

Publisher: publish-pypi.yml on kozandlov/avito-python-sdk

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

File details

Details for the file avito_python_sdk-0.2.4-py3-none-any.whl.

File metadata

File hashes

Hashes for avito_python_sdk-0.2.4-py3-none-any.whl
Algorithm Hash digest
SHA256 2c08a357d5e642d0c6636435006ff23c3ae8eb764cace3595881b2e6aca8eef9
MD5 bc374796e57d6f33012572ea0a25e928
BLAKE2b-256 890e534d2e34f6150365ab075b0583f743c65c743426cc631ebc18f6f778cf19

See more details on using hashes here.

Provenance

The following attestation bundles were made for avito_python_sdk-0.2.4-py3-none-any.whl:

Publisher: publish-pypi.yml on kozandlov/avito-python-sdk

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

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page