Async Python SDK for Avito OpenAPI (full endpoint coverage)
Project description
avito-python-sdk
Асинхронная 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:
- Поднимите публичный
HTTPSendpoint в вашей системе. - Подпишите URL через
client.messenger.post_webhook_v3(...). - На входящем endpoint быстро возвращайте
200 OKи обрабатывайте payload асинхронно. - Проверяйте подписки через
client.messenger.get_subscriptions(...). - При необходимости отключайте подписку
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.pyexamples/fastapi_app/main.pyexamples/django_app/avito_client.pyexamples/celery_app/tasks.pyexamples/webhooks/fastapi_receiver.pyexamples/webhooks/subscribe.pyexamples/webhooks/unsubscribe.pyexamples/.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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7622681b70bc364ebef3a031af9c7bc70d4b818f2a00a2b0b727836086133d96
|
|
| MD5 |
94a62e33d76ca629bb9b20f385d3490c
|
|
| BLAKE2b-256 |
b65ec91d012d84db31f123fcc8d3b607d1d3fb36d78784c118fd0d9ce7ccc722
|
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
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
avito_python_sdk-0.2.4.tar.gz -
Subject digest:
7622681b70bc364ebef3a031af9c7bc70d4b818f2a00a2b0b727836086133d96 - Sigstore transparency entry: 1037469377
- Sigstore integration time:
-
Permalink:
kozandlov/avito-python-sdk@f038574ac128360083808bce7d1db41105b3cbff -
Branch / Tag:
refs/tags/v0.2.4 - Owner: https://github.com/kozandlov
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-pypi.yml@f038574ac128360083808bce7d1db41105b3cbff -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file avito_python_sdk-0.2.4-py3-none-any.whl.
File metadata
- Download URL: avito_python_sdk-0.2.4-py3-none-any.whl
- Upload date:
- Size: 100.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2c08a357d5e642d0c6636435006ff23c3ae8eb764cace3595881b2e6aca8eef9
|
|
| MD5 |
bc374796e57d6f33012572ea0a25e928
|
|
| BLAKE2b-256 |
890e534d2e34f6150365ab075b0583f743c65c743426cc631ebc18f6f778cf19
|
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
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
avito_python_sdk-0.2.4-py3-none-any.whl -
Subject digest:
2c08a357d5e642d0c6636435006ff23c3ae8eb764cace3595881b2e6aca8eef9 - Sigstore transparency entry: 1037469437
- Sigstore integration time:
-
Permalink:
kozandlov/avito-python-sdk@f038574ac128360083808bce7d1db41105b3cbff -
Branch / Tag:
refs/tags/v0.2.4 - Owner: https://github.com/kozandlov
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-pypi.yml@f038574ac128360083808bce7d1db41105b3cbff -
Trigger Event:
workflow_dispatch
-
Statement type: