### Install Perekrestok API Source: https://github.com/open-inflation/perekrestok_api/blob/main/docs/source/quick_start.rst Install the library using pip. ```console pip install perekrestok_api ``` -------------------------------- ### Example Output Source: https://github.com/open-inflation/perekrestok_api/blob/main/docs/source/quick_start.rst The expected output from the basic Perekrestok API usage example. ```console > Текущий город сессии Москва (81) > Список категорий: 31 > Категория: Встречаем Новый год (1692) > Первый товар: Икра Камчатское Море горбуши зернистой солёной, 320г (487063) ``` -------------------------------- ### Basic Perekrestok API Usage Example Source: https://github.com/open-inflation/perekrestok_api/blob/main/docs/source/quick_start.rst Demonstrates fetching current geolocation, catalog tree, and products using the Perekrestok API. Requires an active asynchronous context. ```python from perekrestok_api import PerekrestokAPI from perekrestok_api import abstraction import asyncio async def main(): async with PerekrestokAPI() as Api: geopos_handler = await Api.Geolocation.current() geopos = geopos_handler.json() print(f'Текущий город сессии {geopos["content"]["city"]["name"]} ({geopos["content"]["city"]["id"]})') # Получаем список категорий categories = await Api.Catalog.tree() cat = categories.json() print(f'Список категорий: {len(cat["content"]["items"])}') # Выводим первую категорию print(f'Категория: {cat["content"]["items"][0]["category"]["title"]} ({cat["content"]["items"][0]["category"]["id"]})') # Получаем список товаров filter = abstraction.CatalogFeedFilter() filter.CATEGORY_ID = cat["content"]["items"][0]["category"]["id"] filter.PROMO_LISTING = 27 products = await Api.Catalog.feed(filter=filter) prod = products.json() # Выводим первый товар print(f'Первый товар: {prod["content"]["items"][0]["title"]} ({prod["content"]["items"][0]["id"]})') # Запуск асинхронной функции main if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize PerekrestokAPI Client Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Initialize the main client as an asynchronous context manager. This automatically handles session setup, including obtaining cookies and authorization headers. Supports explicit proxy configuration. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): # Запуск с явным прокси async with PerekrestokAPI( timeout_ms=30000, headless=True, proxy="http://user:pass@proxy.example.com:8080" ) as Api: print("Сессия инициализирована") print("Нестандартные заголовки:", list(Api.unstandard_headers.keys())) # Явное закрытие (необязательно — __aexit__ закрывает сам) # await Api.close() asyncio.run(main()) ``` -------------------------------- ### Get Advertising Banners Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Fetches advertising banners for specified placements. Uses constants from the `BannerPlace` class for defining locations. ```python import asyncio from perekrestok_api import PerekrestokAPI from perekrestok_api.abstraction import BannerPlace async def main(): async with PerekrestokAPI() as Api: response = await Api.Advertising.banner([ BannerPlace.MAIN_BANNERS, BannerPlace.BRANDS, BannerPlace.SpecialCategory.TITLE, ]) data = response.json() for place, banners in data["content"].items(): print(f'{place}: {len(banners)} баннеров') asyncio.run(main()) ``` -------------------------------- ### Get Product Reviews by PLU Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Fetches a paginated list of reviews for a product identified by its PLU. Allows specifying page number and items per page. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.Catalog.Product.reviews(12345, page=1, limit=5) data = response.json() print(f'Отзывов на странице: {len(data["content"]["items"])}') for review in data["content"]["items"]: print(f' Оценка: {review["rating"]} — {review["text"][:60]}') asyncio.run(main()) ``` -------------------------------- ### Get Product Information by PLU Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieves detailed information for a product using its PLU (Product Listing Unique) identifier. The library automatically adds the 'plu' prefix if a number is provided. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: # Можно передать число — библиотека добавит префикс "plu" сама response = await Api.Catalog.Product.info(12345) data = response.json() product = data["content"] print(f'Название: {product["title"]}') print(f'Цена: {product["prices"]["regular"] / 100:.2f} руб.') print(f'Описание: {product.get("description", "—")[:100]}') asyncio.run(main()) ``` -------------------------------- ### PerekrestokAPI Client Initialization Source: https://context7.com/open-inflation/perekrestok_api/llms.txt The main client `PerekrestokAPI` is initialized as an asynchronous context manager. It handles session setup, including obtaining cookies and authorization headers, to mimic a real browser session. It supports parameters like `timeout_ms`, `headless`, and `proxy`. ```APIDOC ## PerekrestokAPI ### Description Main entry point to the library. Accepts `timeout_ms`, `headless`, `proxy`, and `browser_opts` parameters. Supports proxies via the `HTTPS_PROXY` environment variable. Contains submodules: `Geolocation`, `Catalog`, `Advertising`, `General`. ### Initialization Example ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): # Initialization with explicit proxy async with PerekrestokAPI( timeout_ms=30000, headless=True, proxy="http://user:pass@proxy.example.com:8080" ) as Api: print("Session initialized") print("Non-standard headers:", list(Api.unstandard_headers.keys())) # Explicit closing (optional - __aexit__ closes automatically) # await Api.close() asyncio.run(main()) ``` ### Output Example ``` Session initialized Non-standard headers: ['Auth', ...] ``` ``` -------------------------------- ### Get Promotional Booklets and View Content Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Fetches a list of current promotional booklets for a given city and retrieves the content of a specific booklet by its ID. Requires the city ID for listing booklets. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: # Список буклетов для Москвы response = await Api.Advertising.booklet(city=81) data = response.json() booklets = data["content"]["items"] print(f'Буклетов: {len(booklets)}') if booklets: booklet_id = booklets[0]["id"] detail = await Api.Advertising.view_booklet(booklet_id) detail_data = detail.json() pages = detail_data["content"].get("pages", []) print(f'Страниц в буклете: {len(pages)}') asyncio.run(main()) ``` -------------------------------- ### Get Flat Product Feed with Filters Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Fetches a flat list of products with filtering (promo, category, price) and sorting. Ideal for promotional feeds and search results. Uses CatalogFeedFilter and CatalogFeedSort. ```python import asyncio from perekrestok_api import PerekrestokAPI from perekrestok_api import abstraction async def main(): async with PerekrestokAPI() as Api: f = abstraction.CatalogFeedFilter() f.CATEGORY_ID = 1389 # Фрукты и овощи f.ONLY_DISCOUNT = True # Только товары со скидкой f.set_price_range(100, 50000) # Цена 1–500 руб (в копейках) response = await Api.Catalog.feed( filter=f, sort=abstraction.CatalogFeedSort.Price.ASC, page=1, limit=20, ) data = response.json() for product in data["content"]["items"][:3]: print(f'{product["title"]} — {product["prices"]["regular"] / 100:.2f} руб.') asyncio.run(main()) ``` -------------------------------- ### Get Current User Information Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Fetches data for the currently authenticated user or guest information if not logged in. Useful for personalizing user experience. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.General.current_user() data = response.json() user = data["content"] print(f'Тип пользователя: {user.get("type", "guest")}') asyncio.run(main()) ``` -------------------------------- ### Get Address Suggestions Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieve a list of address suggestions based on a search query. Useful for autocompleting address input fields. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.Geolocation.suggests("Тверская 10") data = response.json() for item in data["content"]["items"]: print(item["address"]) asyncio.run(main()) ``` -------------------------------- ### Api.General.qualifier() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Get the status of various API features (A/B tests, loyalty, reviews, etc.) using `qualifier()`. Feature keys are listed in `QualifierFeatureKey`. ```APIDOC ## `Api.General.qualifier()` - API Feature Configuration Returns the status of enabled/disabled API features such as A/B tests, loyalty programs, reviews, and more. The available feature keys are defined in `QualifierFeatureKey`. ### Parameters - **selections** (list[QualifierFeatureKey], optional) - A list of specific feature keys to retrieve status for. If not provided, the status for all features is returned. ### Request Example ```python import asyncio from perekrestok_api import PerekrestokAPI from perekrestok_api.abstraction import QualifierFeatureKey async def main(): async with PerekrestokAPI() as Api: # Request all keys at once response = await Api.General.qualifier() data = response.json() for key, value in list(data["content"].items())[:5]: print(f'{key}: {value}') # Or request only specific keys response2 = await Api.General.qualifier(selections=[ QualifierFeatureKey.PRODUCT_REVIEW, QualifierFeatureKey.LOYALTY_LEVELS, ]) print(response2.json()["content"]) asyncio.run(main()) ``` ``` -------------------------------- ### Get Main Slider Elements Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieves promotional slider items from the main page. Supports pagination with `page` and `limit` parameters. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.Advertising.main_slider(page=1, limit=5) data = response.json() for slide in data["content"]["items"]: print(f'{slide["title"]} → {slide.get("url", "—")}') asyncio.run(main()) ``` -------------------------------- ### Get Category Information Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Fetches detailed information about a category by its ID, including its subcategories. Requires `asyncio` and `PerekrestokAPI`. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.Catalog.category_info(1389) data = response.json() cat = data["content"] print(f'Категория: {cat["title"]}') print(f'Дочерних категорий: {len(cat.get("children", []))}') asyncio.run(main()) ``` -------------------------------- ### Api.Catalog.tree() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieves the complete tree of top-level catalog categories. This method is used to get a hierarchical view of all product categories. ```APIDOC ## `Api.Catalog.tree()` — дерево категорий Возвращает полное дерево категорий каталога верхнего уровня. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.Catalog.tree() data = response.json() items = data["content"]["items"] print(f'Всего категорий верхнего уровня: {len(items)}') for item in items[:3]: cat = item["category"] print(f' {cat["title"]} (ID: {cat["id"]})') # Всего категорий верхнего уровня: 31 # Фрукты и овощи (ID: 1389) # Молоко, сыр, яйца (ID: 1390) # Мясо и птица (ID: 1391) asyncio.run(main()) ``` ``` -------------------------------- ### Api.Geolocation.address_from_position() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Performs reverse geocoding to get an address from coordinates. Accepts a `Geoposition` object. ```APIDOC ## Api.Geolocation.address_from_position() ### Description Performs reverse geocoding to return an address from coordinates. Accepts a `Geoposition` object. ### Method POST ### Endpoint /geolocation/address_from_position ### Parameters #### Request Body - **position** (Geoposition) - Required - An object representing geographical coordinates. - `latitude` (float) - The latitude. - `longitude` (float) - The longitude. - `coordinates` (list of float) - A list containing longitude and latitude, in that order. ### Request Example ```python import asyncio from perekrestok_api import PerekrestokAPI from perekrestok_api.abstraction import Geoposition async def main(): async with PerekrestokAPI() as Api: # Method 1: named parameters (latitude/longitude) pos = Geoposition(latitude=55.7558, longitude=37.6173) # Method 2: two float arguments [latitude, longitude] pos = Geoposition(55.7558, 37.6173) # Method 3: list [longitude, latitude] (Perekrestok format) pos = Geoposition(coordinates=[37.6173, 55.7558]) response = await Api.Geolocation.address_from_position(pos) data = response.json() print(data["content"]["address"]) asyncio.run(main()) ``` ### Response #### Success Response (200) - **content** (object) - **address** (string) - The formatted address string. #### Response Example ```json { "content": { "address": "ул. Тверская, Москва" } } ``` ``` -------------------------------- ### Get Catalog Category Tree Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieves the complete top-level category tree of the catalog. Useful for understanding catalog structure. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.Catalog.tree() data = response.json() items = data["content"]["items"] print(f'Всего категорий верхнего уровня: {len(items)}') for item in items[:3]: cat = item["category"] print(f' {cat["title"]} (ID: {cat["id"]})') # Всего категорий верхнего уровня: 31 # Фрукты и овощи (ID: 1389) # Молоко, сыр, яйца (ID: 1390) # Мясо и птица (ID: 1391) asyncio.run(main()) ``` -------------------------------- ### Get Current Session City Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieve information about the city currently selected for the browser session. Requires the `PerekrestokAPI` client to be initialized. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.Geolocation.current() data = response.json() city = data["content"]["city"] print(f'Город: {city["name"]} (ID: {city["id"]})') # Город: Москва (ID: 81) asyncio.run(main()) ``` -------------------------------- ### Get Catalog Filters and Price Range Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieves available filters (brands, countries, price range) for a given category. Used before constructing a `CatalogFeedFilter`. ```python import asyncio from perekrestok_api import PerekrestokAPI from perekrestok_api import abstraction async def main(): async with PerekrestokAPI() as Api: f = abstraction.CatalogFeedFilter() f.CATEGORY_ID = 1389 response = await Api.Catalog.form(filter=f) data = response.json() content = data["content"] print(f'Цена от: {content["priceFrom"] / 100:.0f} руб.') print(f'Цена до: {content["priceTo"] / 100:.0f} руб.') # Доступные бренды for feat in content.get("features", [])[:2]: print(f'Фильтр: {feat["title"]}') for val in feat.get("enumList", [])[:3]: print(f' {val["title"]}') asyncio.run(main()) ``` -------------------------------- ### Get Products Grouped by Subcategories Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieves products grouped by subcategories, primarily used for browsing the catalog. Requires subcategory IDs. Uses CatalogFeedFilter and CatalogFeedSort. ```python import asyncio from perekrestok_api import PerekrestokAPI from perekrestok_api import abstraction async def main(): async with PerekrestokAPI() as Api: f = abstraction.CatalogFeedFilter() f.CATEGORY_ID = 1392 # Подкатегория «Молоко» response = await Api.Catalog.grouped_feed( filter=f, sort=abstraction.CatalogFeedSort.Popularity.DESC, limit=50, ) data = response.json() groups = data["content"]["items"] print(f'Групп: {len(groups)}') for group in groups[:2]: print(f' {group["category"]["title"]}: {len(group["products"])} товаров') asyncio.run(main()) ``` -------------------------------- ### Api.Catalog.grouped_feed() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Returns products grouped by subcategories, serving as the primary way to get the catalog. This method accepts only subcategories, not root categories. ```APIDOC ## `Api.Catalog.grouped_feed()` — товары по подкатегориям Основной способ получения каталога: возвращает товары, сгруппированные по подкатегориям. Принимает **только подкатегории** (не корневые). ```python import asyncio from perekrestok_api import PerekrestokAPI from perekrestok_api import abstraction async def main(): async with PerekrestokAPI() as Api: f = abstraction.CatalogFeedFilter() f.CATEGORY_ID = 1392 # Подкатегория «Молоко» response = await Api.Catalog.grouped_feed( filter=f, sort=abstraction.CatalogFeedSort.Popularity.DESC, limit=50, ) data = response.json() groups = data["content"]["items"] print(f'Групп: {len(groups)}') for group in groups[:2]: print(f' {group["category"]["title"]}: {len(group["products"])} товаров') asyncio.run(main()) ``` ``` -------------------------------- ### Get Product Availability Count by PLU Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieves the stock count for a specific product (by PLU) across different stores. Requires `asyncio` and `PerekrestokAPI`. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.Catalog.Product.available_count(12345) data = response.json() print(f'Доступно в магазинах: {data["content"]["count"]}') asyncio.run(main()) ``` -------------------------------- ### Custom Pytest Parameters and Hooks Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Example of defining custom parameters and hooks for pytest tests using the `autotest_params` and `autotest_hook` decorators. This allows for specific test data generation and response validation. ```python # tests/endpoints/conftest.py — пример кастомных параметров теста from human_requests import autotest_params, autotest_hook @autotest_params("Catalog.Product.info") def params_product_info(): return {"product_plu": 12345} @autotest_hook("Catalog.Product.info") def hook_product_info(response): data = response.json() assert data["content"]["id"] is not None ``` -------------------------------- ### Get API Feature Configuration Status Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieves the status of various API features, such as A/B tests, loyalty programs, and reviews. Can fetch all feature keys at once or specific keys using `QualifierFeatureKey`. ```python import asyncio from perekrestok_api import PerekrestokAPI from perekrestok_api.abstraction import QualifierFeatureKey async def main(): async with PerekrestokAPI() as Api: # Запросить все ключи сразу response = await Api.General.qualifier() data = response.json() for key, value in list(data["content"].items())[:5]: print(f'{key}: {value}') # Или только нужные ключи response2 = await Api.General.qualifier(selections=[ QualifierFeatureKey.PRODUCT_REVIEW, QualifierFeatureKey.LOYALTY_LEVELS, ]) print(response2.json()["content"]) asyncio.run(main()) ``` -------------------------------- ### Api.Catalog.Product.reviews() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Fetches a paginated list of reviews for a product, identified by its PLU. ```APIDOC ## Api.Catalog.Product.reviews() ### Description Fetches a paginated list of reviews for a product, identified by its PLU. ### Method `Api.Catalog.Product.reviews(plu, page, limit)` ### Parameters #### Path Parameters - **plu** (string or integer) - Required - The PLU identifier of the product. #### Query Parameters - **page** (integer) - Optional - The page number for the reviews. - **limit** (integer) - Optional - The number of reviews to return per page. ``` -------------------------------- ### Api.Advertising.booklet() and Api.Advertising.view_booklet() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieve a list of current promotional booklets for a city using `booklet()` and view the content of a specific booklet by its ID using `view_booklet()`. ```APIDOC ## `Api.Advertising.booklet(city)` and `Api.Advertising.view_booklet(booklet_id)` - Promotional Booklets `booklet()` returns a list of current promotional booklets for a specified city. `view_booklet()` retrieves the content of a specific booklet using its ID. ### Parameters #### `booklet(city)` - **city** (int) - Required - The ID of the city for which to retrieve booklets. #### `view_booklet(booklet_id)` - **booklet_id** (int) - Required - The ID of the booklet to view. ### Request Example ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: # List of booklets for Moscow response = await Api.Advertising.booklet(city=81) data = response.json() booklets = data["content"]["items"] print(f'Booklets found: {len(booklets)}') if booklets: booklet_id = booklets[0]["id"] detail = await Api.Advertising.view_booklet(booklet_id) detail_data = detail.json() pages = detail_data["content"].get("pages", []) print(f'Pages in booklet: {len(pages)}') asyncio.run(main()) ``` ``` -------------------------------- ### Api.Catalog.Product.info() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieves detailed information about a product using its PLU (Product Location Unique) identifier. ```APIDOC ## Api.Catalog.Product.info() ### Description Retrieves detailed information about a product using its PLU (Product Location Unique) identifier. The library automatically adds the 'plu' prefix if a number is provided. ### Method `Api.Catalog.Product.info(plu)` ### Parameters #### Path Parameters - **plu** (string or integer) - Required - The PLU identifier of the product (e.g., 'plu12345' or 12345). ``` -------------------------------- ### Api.Advertising.main_slider() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Fetches elements for the main promotional slider displayed on the website's homepage. ```APIDOC ## Api.Advertising.main_slider() ### Description Fetches elements for the main promotional slider from the website's homepage. ### Method `Api.Advertising.main_slider(page, limit)` ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number for the slider items. - **limit** (integer) - Optional - The number of slider items to return per page. ``` -------------------------------- ### Select Pickup Store Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Set a specific store as the pickup point for the current session. This action affects the product availability displayed in the catalog. Requires the store ID. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: # Сначала получим список магазинов shops_resp = await Api.Geolocation.Shop.on_map(city_id=81, limit=3) shops = shops_resp.json()["content"]["items"] shop_id = shops[0]["id"] # Устанавливаем магазин result = await Api.Geolocation.Selection.shop_point(shop_id) print(result.status) # 200 asyncio.run(main()) ``` -------------------------------- ### Api.Catalog.feed() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Provides a flat feed of products with filtering (promotions, category, price) and sorting. This is the primary method for promotional feeds and search results. ```APIDOC ## `Api.Catalog.feed()` — плоская лента товаров с фильтрами Основной метод для получения списка товаров с фильтрацией (промо, категория, цена) и сортировкой. Используется для промо-лент и поиска. ```python import asyncio from perekrestok_api import PerekrestokAPI from perekrestok_api import abstraction async def main(): async with PerekrestokAPI() as Api: f = abstraction.CatalogFeedFilter() f.CATEGORY_ID = 1389 # Фрукты и овощи f.ONLY_DISCOUNT = True # Только товары со скидкой f.set_price_range(100, 50000) # Цена 1–500 руб (в копейках) response = await Api.Catalog.feed( filter=f, sort=abstraction.CatalogFeedSort.Price.ASC, page=1, limit=20, ) data = response.json() for product in data["content"]["items"][:3]: print(f'{product["title"]} — {product["prices"]["regular"] / 100:.2f} руб.') asyncio.run(main()) ``` ``` -------------------------------- ### Api.Advertising.banner() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieves advertising banners for specified placement locations. Placement constants are available in the `BannerPlace` class. ```APIDOC ## Api.Advertising.banner() ### Description Retrieves advertising banners for specified placement locations. Constants for placement are available in the `BannerPlace` class. ### Method `Api.Advertising.banner(places)` ### Parameters #### Request Body - **places** (list of BannerPlace constants) - Required - A list of banner placement identifiers. ``` -------------------------------- ### Api.Catalog.form() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieves available filters (brands, countries, price range) for the current category context. This is used before forming a CatalogFeedFilter. ```APIDOC ## Api.Catalog.form() ### Description Retrieves available filters (brands, countries, price range) for the current category context. Used before forming a `CatalogFeedFilter`. ### Method `Api.Catalog.form(filter)` ### Parameters #### Request Body - **filter** (`CatalogFeedFilter`) - Required - The filter object to specify the category context. ``` -------------------------------- ### Api.Geolocation.suggests() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Provides address suggestions based on a search string. ```APIDOC ## Api.Geolocation.suggests() ### Description Returns a list of address suggestions based on a search string. ### Method GET ### Endpoint /geolocation/suggests ### Parameters #### Query Parameters - **query** (string) - Required - The search string for address suggestions. ### Request Example ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.Geolocation.suggests("Тверская 10") data = response.json() for item in data["content"]["items"]: print(item["address"]) asyncio.run(main()) ``` ### Response #### Success Response (200) - **content** (object) - **items** (array) - **address** (string) - A suggested address string. #### Response Example ```json { "content": { "items": [ { "address": "Тверская ул., 10, Москва" } ] } } ``` ``` -------------------------------- ### Api.General.current_user() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieve information about the currently authenticated user or guest data using `current_user()`. ```APIDOC ## `Api.General.current_user()` - Current User Information Returns data for the authenticated user or guest information if no user is logged in. ### Request Example ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.General.current_user() data = response.json() user = data["content"] print(f'User type: {user.get("type", "guest")}') asyncio.run(main()) ``` ``` -------------------------------- ### Api.Geolocation.Selection.shop_point() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Sets a specific store as the pickup point for the session. This affects product availability displayed in the catalog. ```APIDOC ## Api.Geolocation.Selection.shop_point() ### Description Sets the store as the pickup point. This changes the session state, and the catalog will start reflecting product availability in the selected store. ### Method POST ### Endpoint /geolocation/selection/shop_point ### Parameters #### Query Parameters - **shop_id** (integer) - Required - The ID of the store to set as the pickup point. ### Request Example ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: # First, get a list of stores shops_resp = await Api.Geolocation.Shop.on_map(city_id=81, limit=3) shops = shops_resp.json()["content"]["items"] shop_id = shops[0]["id"] # Set the store result = await Api.Geolocation.Selection.shop_point(shop_id) print(result.status) asyncio.run(main()) ``` ### Response #### Success Response (200) - **status** (integer) - Indicates the success of the operation (e.g., 200 for success). #### Response Example ```json { "status": 200 } ``` ``` -------------------------------- ### Api.Catalog.Product.available_count() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Returns the stock availability count for a product, identified by its PLU. ```APIDOC ## Api.Catalog.Product.available_count() ### Description Returns the stock availability count for a product, identified by its PLU. ### Method `Api.Catalog.Product.available_count(plu)` ### Parameters #### Path Parameters - **plu** (string or integer) - Required - The PLU identifier of the product. ``` -------------------------------- ### Search Products and Categories Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Performs a text search across products and categories. The `entity_types` parameter specifies whether to search for 'product', 'category', or both. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.Catalog.search( "молоко ультрапастеризованное", entity_types=["product"] ) data = response.json() products = data["content"]["products"]["items"] print(f'Найдено товаров: {len(products)}') for p in products[:3]: print(f' {p["title"]} (ID: {p["id"]})') asyncio.run(main()) ``` -------------------------------- ### Pytest Configuration for API Testing Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Configuration settings for pytest to enable automated API testing with the Perekrestok API library. Includes settings for `anyio_mode`, `autotest_start_class`, and `autotest_typecheck`. ```ini # pyproject.toml [tool.pytest.ini_options] anyio_mode = "auto" autotest_start_class = "perekrestok_api.PerekrestokAPI" autotest_typecheck = "strict" ``` -------------------------------- ### Search for City by Name Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Search for cities based on a text query. The `limit` parameter can restrict the number of results returned. Requires the `PerekrestokAPI` client to be initialized. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.Geolocation.search("Санкт", limit=5) data = response.json() for city in data["content"]["items"]: print(f'{city["name"]} (ID: {city["id"]})') # Санкт-Петербург (ID: 2) asyncio.run(main()) ``` -------------------------------- ### Api.General.download_image() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Download an image from a given URL with automatic retries on errors. Returns a `BytesIO` object. ```APIDOC ## `Api.General.download_image(url, retry_attempts=5, timeout=30)` - Image Download Downloads an image from the specified URL. It includes automatic retry mechanisms for transient errors and a configurable timeout. The function returns the image data as a `BytesIO` object. ### Parameters - **url** (str) - Required - The URL of the image to download. - **retry_attempts** (int, optional) - Defaults to 5. The number of times to retry the download if it fails. - **timeout** (int, optional) - Defaults to 30. The timeout in seconds for the download request. ### Request Example ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: # First, get the image URL of a product product = await Api.Catalog.Product.info(12345) image_url = product.json()["content"]["images"][0]["url"] image = await Api.General.download_image( image_url, retry_attempts=3, timeout=10 ) with open(image.name, "wb") as f: f.write(image.read()) print(f'Saved image to: {image.name}') asyncio.run(main()) ``` ``` -------------------------------- ### Running Pytest and Updating Snapshots Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Commands to run all automated API tests using pytest and to update the snapshot test data when necessary. ```bash # Запуск всех тестов pytest # Обновление эталонных снапшотов pytest --snapshot-update ``` -------------------------------- ### Api.Catalog.search() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Performs a text search across the catalog for products and categories. The `entity_types` parameter allows specifying whether to search for 'product', 'category', or both. ```APIDOC ## `Api.Catalog.search()` — поиск товаров и категорий Текстовый поиск по каталогу. Параметр `entity_types` выбирает, что искать: `"product"`, `"category"` или оба. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.Catalog.search( "молоко ультрапастеризованное", entity_types=["product"] ) data = response.json() products = data["content"]["products"]["items"] print(f'Найдено товаров: {len(products)}') for p in products[:3]: print(f' {p["title"]} (ID: {p["id"]})') asyncio.run(main()) ``` ``` -------------------------------- ### Set Delivery Point by Coordinates Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Sets the delivery point for courier delivery using geographical coordinates. Requires Geoposition object. ```python import asyncio from perekrestok_api import PerekrestokAPI from perekrestok_api.abstraction import Geoposition async def main(): async with PerekrestokAPI() as Api: pos = Geoposition(latitude=55.7558, longitude=37.6173) response = await Api.Geolocation.Selection.delivery_point(pos) print(response.status) # 200 asyncio.run(main()) ``` -------------------------------- ### Download Image with Retries Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Downloads an image from a given URL with automatic retry attempts on errors and a specified timeout. Returns the image data as a `BytesIO` object. ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: # Сначала получим URL изображения товара product = await Api.Catalog.Product.info(12345) image_url = product.json()["content"]["images"][0]["url"] image = await Api.General.download_image( image_url, retry_attempts=3, timeout=10 ) with open(image.name, "wb") as f: f.write(image.read()) print(f'Сохранено: {image.name}') asyncio.run(main()) ``` -------------------------------- ### Api.Catalog.category_info() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Fetches detailed information about a category by its ID, including its child categories. ```APIDOC ## Api.Catalog.category_info() ### Description Fetches detailed information about a category by its ID, including child categories. ### Method `Api.Catalog.category_info(category_id)` ### Parameters #### Path Parameters - **category_id** (integer) - Required - The ID of the category to retrieve information for. ``` -------------------------------- ### Api.Geolocation.Shop.on_map() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Searches for stores on the map with filtering by city, coordinates, features, and sorting by distance. This is useful for finding nearby stores. ```APIDOC ## `Api.Geolocation.Shop.on_map()` — поиск магазинов на карте Ищет магазины с фильтрацией по городу, координатам, особенностям и сортировкой по расстоянию. ```python import asyncio from perekrestok_api import PerekrestokAPI from perekrestok_api.abstraction import Geoposition, GeolocationPointSort async def main(): async with PerekrestokAPI() as Api: pos = Geoposition(latitude=55.7558, longitude=37.6173) response = await Api.Geolocation.Shop.on_map( position=pos, city_id=81, limit=5, sort=GeolocationPointSort.Distance.ASC, ) data = response.json() for shop in data["content"]["items"]: print(f'{shop["address"]} — {shop["distance"]} м') asyncio.run(main()) ``` ``` -------------------------------- ### Api.Geolocation.current() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Retrieves information about the city currently selected for the browser session. ```APIDOC ## Api.Geolocation.current() ### Description Returns information about the city selected for the current browser session. ### Method GET ### Endpoint /geolocation/current ### Parameters None ### Request Example ```python import asyncio from perekrestok_api import PerekrestokAPI async def main(): async with PerekrestokAPI() as Api: response = await Api.Geolocation.current() data = response.json() city = data["content"]["city"] print(f'City: {city["name"]} (ID: {city["id"]})') asyncio.run(main()) ``` ### Response #### Success Response (200) - **content** (object) - Contains city information. - **city** (object) - **id** (integer) - The unique identifier of the city. - **name** (string) - The name of the city. #### Response Example ```json { "content": { "city": { "id": 81, "name": "Москва" } } } ``` ``` -------------------------------- ### Search Stores on Map Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Searches for stores on the map, allowing filtering by city, coordinates, features, and sorting by distance. Requires Geoposition and GeolocationPointSort. ```python import asyncio from perekrestok_api import PerekrestokAPI from perekrestok_api.abstraction import Geoposition, GeolocationPointSort async def main(): async with PerekrestokAPI() as Api: pos = Geoposition(latitude=55.7558, longitude=37.6173) response = await Api.Geolocation.Shop.on_map( position=pos, city_id=81, limit=5, sort=GeolocationPointSort.Distance.ASC, ) data = response.json() for shop in data["content"]["items"]: print(f'{shop["address"]} — {shop["distance"]} м') asyncio.run(main()) ``` -------------------------------- ### Api.Geolocation.Selection.delivery_point() Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Sets the delivery point for courier delivery using coordinates. This method allows users to specify a delivery address by providing latitude and longitude. ```APIDOC ## `Api.Geolocation.Selection.delivery_point()` — установка точки курьерской доставки Задаёт адрес курьерской доставки по координатам. ```python import asyncio from perekrestok_api import PerekrestokAPI from perekrestok_api.abstraction import Geoposition async def main(): async with PerekrestokAPI() as Api: pos = Geoposition(latitude=55.7558, longitude=37.6173) response = await Api.Geolocation.Selection.delivery_point(pos) print(response.status) # 200 asyncio.run(main()) ``` ``` -------------------------------- ### Catalog Feed Filtering Source: https://context7.com/open-inflation/perekrestok_api/llms.txt Utilizes `CatalogFeedFilter` to construct and validate filtering parameters for catalog requests. Supports filtering by category, discount status, private label, price range, and custom features. ```python from perekrestok_api.abstraction import CatalogFeedFilter f = CatalogFeedFilter() # Установка категории f.CATEGORY_ID = 1389 # Только товары со скидкой f.ONLY_DISCOUNT = True # Только СТМ (собственная торговая марка Перекрёстка) f.FROM_PEREKRESTOK = True # Диапазон цен (в копейках: 100 руб. = 10000 коп.) f.set_price_range(10000, 100000) # Фильтрация по особенностям (бренд, страна и т.п.) f.FEATURES.add("brand", "ВкусВилл") f.FEATURES.add("country", "Россия") f.FEATURES.remove("brand", "ВкусВилл") # удаление # Проверка итогового словаря фильтра print(f.as_dict()) # {'category': 1389, 'onlyDiscount': True, 'privateLabel': True, # 'priceRange': {'from': 10000, 'to': 100000}, # 'features': [{'key': 'country', 'value': 'Россия'}]} ```