Перейти к содержанию

Клиент

cdekx.CdekClient

Asynchronous CDEK API client (v2).

The client owns the HTTP transport and authorisation; the methods are grouped by resources (orders, calculator, locations, etc.).

Example

async with CdekClient.from_env() as client: # doctest: +SKIP ... tariff = await client.calculator.tariff(TariffRequest(...)) # doctest: +SKIP

Manual initialisation::

client = CdekClient(client_id="...", client_secret="...", environment=Environment.SANDBOX)
...
await client.aclose()
Note

An instance is designed for a long lifetime and concurrent requests — do not create a client per request.

orders property

Orders: creation, modification, statuses, search.

calculator property

Calculation of the delivery cost and terms.

locations property

Directories of cities and regions.

delivery_points property

Offices, pickup points and parcel lockers.

intakes property

Courier pickup requests (intakes).

printing property

Print forms: waybills, barcodes, order copies.

webhooks property

Webhook subscriptions.

delivery_agreement property

Delivery agreement: intervals and date coordination.

misc property

Reverse, receipts, prealerts, document photos and the raw() escape hatch.

tariffs property

Alias of :attr:calculator.

points property

Alias of :attr:delivery_points.

courier property

Alias of :attr:intakes — the historical name of the section.

agreements property

Alias of :attr:delivery_agreement.

handbook property

Alias of :attr:misc (for compatibility with early cdekx versions).

http property

Access to the HTTP layer (debugging, non-standard requests).

environment property

The current API environment.

base_url property

The base API URL.

from_env(**overrides) classmethod

Create a client from environment variables.

CDEKX_CLIENT_ID/CDEK_CLIENT_ID, CDEKX_CLIENT_SECRET/CDEK_CLIENT_SECRET, CDEKX_ENVIRONMENT, CDEKX_BASE_URL, CDEKX_TIMEOUT are used.

Parameters:

Name Type Description Default
**overrides Any

client_id, client_secret, config and prefix override the values from the environment; the other arguments (environment, max_concurrency, http_client, timeouts, retry, extra_headers, auth, sandbox) are passed to the :class:CdekClient constructor.

{}
Example

client = CdekClient.from_env(max_concurrency=20) # doctest: +SKIP

sandbox(client_id=None, client_secret=None, **kwargs) classmethod

Create a client for the api.edu.cdek.ru sandbox.

Without arguments the publicly available CDEK test credentials are used (see apidoc.cdek.ru → "Connecting to the service"): orders in this environment are not delivered.

wait_order(uuid, *, timeout=60.0, interval=2.0) async

Wait for the order processing and return it.

CDEK answers POST /v2/orders with code 202 and the ACCEPTED state: that is the state of the request, not of the order. The usual processing time is 200–500 ms, up to 30–60 s under peak load.

Returns:

Type Description
Any

class:cdekx.models.Order after the request turns SUCCESSFUL.

Raises:

Type Description
ApiError

the order was rejected during processing (INVALID) — exc.errors will contain codes like v2_order_invalid.

TimeoutExceeded

the order stayed in processing.

with_concurrency_limit(coro) async

Run a coroutine respecting max_concurrency (if it is set).

aclose() async

Close the transport. Called automatically in async with.

cdekx.config.ClientConfig dataclass

Immutable configuration for :class:cdekx.CdekClient.

resolve_base_url()

Return the resolved base URL.

cdekx.config.Settings dataclass

Credentials and configuration assembled from arguments and the environment.

from_env(*, prefix=ENV_PREFIX, **overrides) classmethod

Build the settings from environment variables.

Recognized env vars

CDEKX_CLIENT_ID / CDEK_CLIENT_ID — the account identifier; CDEKX_CLIENT_SECRET / CDEK_CLIENT_SECRET — the password; CDEKX_ENVIRONMENT — production or sandbox; CDEKX_BASE_URL — overrides the base URL; CDEKX_TIMEOUT — request timeout in seconds.

Parameters:

Name Type Description Default
prefix str

prefix of the environment variables to read.

ENV_PREFIX
**overrides object

values with the highest priority.

{}

require_credentials()

Return (client_id, client_secret) or raise :class:ConfigError.

cdekx._http.HttpClient

A thin wrapper over httpx.AsyncClient with authentication and retries.

An instance keeps a single pooled connection for its whole lifetime, unlike the "new session per request" approach.

base_url property

Base URL of the API.

is_closed property

Whether the transport is closed.

aclose() async

Close the connection (only if we created the client ourselves).

request_raw(method, path, *, params=None, json_body=None, headers=None, auth=True) async

Perform a request and return the unparsed response.

This is the main path for typed responses: the bytes go straight into Model.model_validate_json() / TypeAdapter.validate_json(), so the JSON is parsed exactly once, inside pydantic's Rust parser. json.loads is never called here.

The error body is parsed lazily — only inside :func:raise_for_status.

Raises:

Type Description
ApiError

the API answered with a status >= 400.

TransportError

the network is unreachable or a timeout expired.

request_json(method, path, *, params=None, json_body=None, headers=None, auth=True) async

Perform a request and return the parsed JSON (dict/list).

For typed responses prefer :meth:request_raw + model_validate_json: this method additionally pays for json.loads. It is kept for escape hatches (misc.raw) and raw directory data.

Raises:

Type Description
ApiError

the API answered with a status >= 400.

TransportError

the network is unreachable or a timeout expired.

request_bytes(method, path, *, params=None, json_body=None, headers=None, auth=True) async

Perform a request and return the binary body (PDF, ZIP, XLSX).

cdekx._http.RetryPolicy dataclass

Retry policy with exponential backoff and jitter.

Retried: network errors, read/connect timeouts and the listed HTTP statuses. When the response carries a Retry-After header, it is respected.

max_attempts = 1 disables retries entirely.

none() classmethod

Return a policy that disables retries.

allows_retry(attempt, method, status)

Whether the request may be retried after attempt number attempt.

delay(attempt, retry_after=None)

Delay before attempt attempt + 1, in seconds.

cdekx._http.Timeouts dataclass

Request timeouts.

The defaults are tuned for CDEK: most methods answer quickly, but printing forms and tariff calculations can take seconds.

as_httpx()

Convert to an httpx.Timeout.

cdekx._auth.OAuth2ClientCredentials dataclass

OAuth2 client with an in-memory token cache.

cached_token property

The currently cached token (or None).

get_token(client) async

Return a valid token, fetching a new one when necessary.

invalidate() async

Drop the cached token.

cdekx._auth.StaticTokenProvider dataclass

Provider with a token known in advance.

Useful for tests, proxying services, and cases where the token is issued by another system.

get_token(client) async

Return the fixed token.

invalidate() async

Do nothing: the token is immutable.

cdekx.pagination.Paginator

Bases: Generic[ModelT]

Lazy asynchronous iterator over the pages of a list.

Example

async for order in client.orders.paginate(page_size=500): # doctest: +SKIP ... print(order.uuid) # doctest: +SKIP

Parameters:

Name Type Description Default
fetch PageFetcher

coroutine function that accepts the page query parameters.

required
model type[ModelT]

pydantic model class for a list item.

required
page_size int

page size (1..1000).

100
start_page int

first page number (0 by default).

0
params Mapping[str, Any] | None

base query parameters (filters).

None
max_pages int | None

cap on the number of pages to load (guards against infinity).

None

page_size property

Size of the page being requested.

pages_loaded property

Number of pages loaded so far.

items_seen property

Number of items yielded so far.

exhausted property

Whether the end of the list has been reached.

collect() async

Collect every item into memory (mind large result sets).

Ресурсы

cdekx.endpoints.orders.OrdersEndpoint

Bases: Endpoint

Order operations.

create(order) async

Register an order (POST /v2/orders, answer 202).

Args: order: an :class:OrderCreate model or a dict with the request body.

Returns: A task envelope. uuid is the order identifier in the CDEK system, state is ACCEPTED (the request was accepted but the order is not created yet).

Note: The ACCEPTED state describes the request, not the order, and does not guarantee creation. Learn the outcome via :meth:wait, :meth:get or the ORDER_STATUS webhook.

update(order) async

Update an order (PATCH /v2/orders, answer 202).

The identifier is passed in the body: uuid or cdek_number. Only orders in the CREATED/ACCEPTED statuses can be updated, otherwise CDEK returns the v2_update_forbidden error.

Example:

await client.orders.update( # doctest: +SKIP ... OrderUpdate(uuid="...", type=1, recipient=..., comment="address clarified") ... )

delete(uuid) async

Delete an order (DELETE /v2/orders/{uuid}, answer 202).

client_return(uuid, data) async

Register a client return (POST /v2/orders/{uuid}/clientReturn).

refuse(uuid, data=None) async

Register an order refusal (POST /v2/orders/{uuid}/refusal).

get(uuid) async

Order details by UUID (GET /v2/orders/{uuid}).

Returns: The order from the entity field of the response.

Raises: NotFoundError: the order was not found (error code v2_entity_not_found).

get_envelope(uuid) async

Full response envelope by UUID: order + requests + related_entities.

get_by_number(cdek_number) async

Order by CDEK number (GET /v2/orders?cdek_number=...).

get_by_client_number(im_number) async

Order by the number in your own system (GET /v2/orders?im_number=...).

get_envelope_by_number(cdek_number) async

Response envelope by CDEK number (including requests and related_entities).

intakes(order_uuid) async

All intakes of an order (GET /v2/orders/{orderUuid}/intakes).

The response is a "bare" array of IntakeInfoResponseEntity[] (no envelope). In the specification this schema is identical to IntakeInfoDto, so a list of :class:cdekx.models.IntakeInfo is returned.

Note: This is the only way to get a list of intakes: the API has no generic GET /v2/intakes method.

wait(uuid, *, timeout=60.0, interval=2.0, backoff=1.5) async

Wait for the asynchronous processing of an order to finish.

CDEK answers order creation with HTTP 202 and the ACCEPTED state, which only means "the request was accepted". Processing usually takes 200-500 ms, up to 30-60 s under peak load. The documentation recommends waiting 2-3 seconds before the first poll.

Returns: An envelope with an order whose state became SUCCESSFUL or INVALID, or which gained a cdek_number.

Raises: ApiError: the order was rejected during processing (carries errors). TimeoutExceeded: the state stayed ACCEPTED.

cdekx.endpoints.calculator.CalculatorEndpoint

Bases: Endpoint

Delivery cost and time calculation.

tariff(request) async

Calculate by tariff code (POST /v2/calculator/tariff).

Parameters:

Name Type Description Default
request TariffRequest | dict[str, Any]

a :class:TariffRequest model or a dict with the request body.

required

Returns:

Type Description
TariffCalculation

The calculation result: cost, delivery time (business and calendar

TariffCalculation

days), chargeable weight, extra services.

Note

The calculator may answer HTTP 200 with errors inside — check :attr:TariffCalculation.has_errors.

tariff_list(request) async

Calculate across all available tariffs (POST /v2/calculator/tarifflist).

Handy selections: :attr:TariffListResponse.viable, :meth:TariffListResponse.best, :meth:TariffListResponse.fastest.

tariff_and_service(request) async

Calculate for available tariffs together with extra services.

POST /v2/calculator/tariffAndService. Unlike tarifflist, it returns the cost including the extra services passed in, plus a success flag for each tariff.

available_tariffs(*, lang=None) async

Tariffs available under the contract (GET /v2/calculator/alltariffs).

Parameters:

Name Type Description Default
lang str | None

output language — sent in the X-User-Lang header (rus/eng/zho).

None

errors_of(payload) staticmethod

Parse errors out of a calculator response (returned with HTTP 200).

cdekx.endpoints.locations.LocationsEndpoint

Bases: Endpoint

Cities, regions, postal codes and location lookup.

cities(query=None) async

List of settlements (GET /v2/location/cities) — a single page.

By default CDEK returns up to 1000 records; the maximum size is 10000. Use :meth:paginate_cities to fetch everything.

paginate_cities(query=None, *, page_size=1000)

Iterate over all pages of the settlement list.

regions(query=None) async

List of regions (GET /v2/location/regions) — a single page.

paginate_regions(query=None, *, page_size=1000)

Iterate over all pages of the region list.

suggest_cities(name, *, country_code=None) async

Location lookup by city name (GET /v2/location/suggest/cities).

Handy for address autocompletion: it accepts a partial match (unlike cities, where city has to match exactly).

Parameters:

Name Type Description Default
name str

search string, for example "Novosib" (required).

required
country_code str | None

ISO 3166-1 alpha-2 country code.

None

city_by_coordinates(latitude, longitude) async

Resolve a settlement by coordinates (GET /v2/location/coordinates).

postalcodes(city_code) async

Postal codes of a city (GET /v2/location/postalcodes?code=...).

The API response is an object {"code": ..., "postal_codes": ["101000", ...]} (PostcodesResponseDto), not a list of entities: all the codes belong to a single city. Codes are strings; for some foreign cities the API returns [null] (see :attr:Postcodes.values).

cdekx.endpoints.delivery.DeliveryPointsEndpoint

Bases: Endpoint

CDEK pickup points, parcel lockers and warehouses.

list(filter=None) async

List offices by filter (GET /v2/deliverypoints) — a single page.

Parameters:

Name Type Description Default
filter DeliveryPointFilter | dict[str, Any] | None

selection criteria (city, type, payment, try-on, weight, dimensions).

None
Note

The response can be large: use city_code/type/size.

paginate(filter=None, *, page_size=500)

Iterate over the office list page by page (async for).

get(code) async

Fetch an office by code.

Raises:

Type Description
NotFoundError

no office with that code was found.

by_polygon(*, latitude_right_top, longitude_right_top, latitude_left_bottom, longitude_left_bottom, filter=None) async

Offices inside a bounding box (GET /v2/deliverypoints/byPolygons).

This is the standard way to find the nearest pickup points: define a box around the location and filter the result if needed. Coordinates carry up to 6 decimal places.

Note

This method supports fewer filters than the office list: only type, city_uuid, have_cashless, have_cash, allowed_cod, is_dressing_room, weight_max, weight_min and lang. There is no pagination — every office in the box is returned. Use :class:DeliveryPointPolygonFilter.

Parameters:

Name Type Description Default
latitude_right_top float

latitude of the top-right corner.

required
longitude_right_top float

longitude of the top-right corner.

required
latitude_left_bottom float

latitude of the bottom-left corner.

required
longitude_left_bottom float

longitude of the bottom-left corner.

required
filter DeliveryPointPolygonFilter | dict[str, Any] | None

extra criteria (type, city, payment, try-on, weight).

None

cdekx.endpoints.delivery_agreement.DeliveryAgreementEndpoint

Bases: Endpoint

Agreeing on a delivery date and time window.

create(agreement) async

Register a delivery agreement (POST /v2/delivery, 202).

Parameters:

Name Type Description Default
agreement DeliveryAgreement | dict[str, Any]

a :class:DeliveryAgreement model or a dict. The order is identified by cdek_number or order_uuid; date is required, and time_from/time_to only for "to the door" orders.

required

get(uuid) async

Agreement details (GET /v2/delivery/{uuid}).

get_envelope(uuid) async

Full response envelope for an agreement UUID.

intervals(*, cdek_number=None, order_uuid=None) async

Delivery intervals available for an existing order.

GET /v2/delivery/intervals?cdek_number=... or ?order_uuid=....

Parameters:

Name Type Description Default
cdek_number str | None

CDEK order number.

None
order_uuid str | None

order UUID (an alternative to the number).

None

estimated_intervals(request) async

Delivery intervals before an order is created.

POST /v2/delivery/estimatedIntervals. Lets you compute the slots available to the agreement widget in advance, based on the direction and tariff.

wait(uuid, *, timeout=60.0, interval=2.0, backoff=1.5) async

Wait for the asynchronous agreement registration to finish.

cdekx.endpoints.intakes.IntakesEndpoint

Bases: Endpoint

Courier pickup requests (intakes).

create(intake) async

Register an intake (POST /v2/intakes, answer 202).

Args: intake: an :class:Intake model or a dict with the request body.

Returns: A task envelope: the intake uuid and state = ACCEPTED.

get(uuid) async

Intake details by UUID (GET /v2/intakes/{uuid}).

get_envelope(uuid) async

Full response envelope for an intake UUID (with requests).

change_status(uuid, *, code, add_status) async

Change the intake status (PATCH /v2/intakes).

Args: uuid: identifier of the intake in the CDEK system. code: status code, for example CANCELLED (IntakeStatusCode). add_status: additional code, for example CANCELLED_BY_CLIENT.

delete(uuid) async

Delete an intake (DELETE /v2/intakes/{uuid}).

Note: An intake in a final status cannot be deleted — CDEK answers v2_entity_has_final_status.

available_days(request) async

Courier pickup dates available for a settlement.

POST /v2/intakes/availableDays.

Example:

days = await client.intakes.available_days({ # doctest: +SKIP ... "from_location": {"code": 44}, ... "date": "2026-06-30", ... })

wait(uuid, *, timeout=60.0, interval=2.0, backoff=1.5) async

Wait for the asynchronous intake processing to finish.

cdekx.endpoints.printing.PrintEndpoint

Bases: Endpoint

Order waybills and package barcodes.

waybill(orders, *, copy_count=2, type=None) async

Form an order waybill (POST /v2/print/orders, answer 202).

Args: orders: order UUIDs or CDEK numbers (plain strings are accepted for convenience). copy_count: number of copies per sheet. CDEK recommends >= 2: one for the cargo, one kept by the sender. type: waybill form type (tpl_russia, tpl_english, ... — see :class:cdekx.models.WaybillFormType). Defaults to the Russian form.

waybill_status(uuid) async

Waybill generation status (GET /v2/print/orders/{uuid}).

waybill_pdf(uuid) async

Download the finished waybill (GET /v2/print/orders/{uuid}.pdf).

barcodes(orders, *, copy_count=1, format=PrintFormat.A4, lang=None) async

Form package barcodes for an order (POST /v2/print/barcodes, answer 202).

Args: orders: order UUIDs or CDEK numbers. copy_count: number of copies (1 by default). format: print format — A4, A5, A6, A7. lang: form language in ISO 639-3 (RUS or ENG).

barcode_status(uuid) async

Barcode generation status (GET /v2/print/barcodes/{uuid}).

barcode_pdf(uuid) async

Download the finished barcode file (GET /v2/print/barcodes/{uuid}.pdf).

wait_waybill(uuid, *, timeout=90.0, interval=2.0, backoff=1.5) async

Wait until the waybill is ready (a url appears).

Raises: TimeoutExceeded: the file was not generated within the allotted time.

wait_barcode(uuid, *, timeout=90.0, interval=2.0, backoff=1.5) async

Wait until the package barcode file is ready.

Raises: TimeoutExceeded: the file was not generated within the allotted time.

download_waybill(orders, *, copy_count=2, timeout=90.0) async

End-to-end flow: form a waybill, wait for it and download the PDF.

download_barcodes(orders, *, format=PrintFormat.A4, copy_count=1, timeout=90.0) async

End-to-end flow: form package barcodes, wait for them and download the PDF.

cdekx.endpoints.webhooks.WebhooksEndpoint

Bases: Endpoint

Managing event subscriptions.

create(url, type=WebhookType.ORDER_STATUS) async

Add a subscription (POST /v2/webhooks).

Args: url: HTTPS address that receives the events. Including a secret path segment is recommended — CDEK does not sign the webhook body. type: event type (ORDER_STATUS, PRINT_FORM, ...).

Note: Per the specification a duplicate type is not rejected: "if the client already has a subscription with the given type, another subscription with the same type will be created" — but only until you hit the limit of two active subscriptions.

Raises: ApiError: the subscription limit was exceeded (HTTP 400, code v2_too_many_webhooks — see :data:cdekx.models.TOO_MANY_WEBHOOKS_ERROR) or the event type is invalid (v2_webhook_type_incorrect).

list() async

Subscriptions of the account (GET /v2/webhooks).

The response is an array of {uuid, type, url} objects, without an envelope.

get(uuid) async

Subscription details by UUID (GET /v2/webhooks/{uuid}).

get_envelope(uuid) async

Full response envelope for a subscription UUID.

delete(uuid) async

Delete a subscription (DELETE /v2/webhooks/{uuid}).

delete_all() async

Delete every subscription of the account.

Returns: UUIDs of the deleted subscriptions.

has_capacity() async

Whether a slot is free for a new subscription (the CDEK limit is 2).

The check is approximate: GET /v2/webhooks may return more than two records — for example a subscription marked for deletion in 24 hours is no longer counted as active by the API (three records were observed in the sandbox list while the error message reported two active ones). The server enforces the limit for real: POST /v2/webhooks answers HTTP 400 with code v2_too_many_webhooks — see :meth:is_limit_error.

is_limit_error(exc) staticmethod

Whether the error means "too many active subscriptions".

Example::

try: await client.webhooks.create(url) except ApiError as exc: if WebhooksEndpoint.is_limit_error(exc): await client.webhooks.delete_all() ...

The v2_too_many_webhooks code is not described in the OpenAPI specification but is really returned by the API (verified against api.edu.cdek.ru).

replace(url, type=WebhookType.ORDER_STATUS) async

Free up a slot and create a subscription (handy when moving a URL).

Deletes all existing subscriptions, then creates a new one.

Warning: Events are lost between the deletion and the creation — perform the operation at a time of minimal traffic.

cdekx.endpoints.misc.MiscEndpoint

Bases: Endpoint

Sporadic API methods: receipts, passports, registries, photos, prealerts, reverse.

reverse_availability(request) async

Check reverse availability before creating the forward order.

POST /v2/reverse/availability. The request carries the same data as order creation: direction, tariff, sender and recipient.

Parameters:

Name Type Description Default
request ReverseValidateRequest | dict[str, Any]

:class:cdekx.models.ReverseValidateRequest or a dict. tariff_code, sender and recipient are required; the direction is from_location/to_location or shipment_point/delivery_point.

required

Returns:

Type Description
None

None — reverse is available (the API answers with an empty body

None

and code 200).

Raises:

Type Description
ApiError

reverse is unavailable or the request is invalid (HTTP 400 with the reason described).

Example

await client.misc.reverse_availability({ # doctest: +SKIP ... "tariff_code": 136, ... "delivery_point": "MSK", ... "from_location": {"code": 44, "address": "1 Test Street"}, ... "sender": {"contragent_type": "INDIVIDUAL", "phones": ["+79001234567"]}, ... "recipient": {"contragent_type": "INDIVIDUAL", "phones": ["+79007654321"]}, ... })

checks(*, order_uuid=None, cdek_number=None, date=None) async

Fiscal receipt information (GET /v2/check).

Parameters:

Name Type Description Default
order_uuid str | None

order UUID in the CDEK information system.

None
cdek_number str | None

CDEK order number.

None
date str | None

receipt creation date, yyyy-MM-dd.

None

Returns:

Type Description
CheckResponse

class:cdekx.models.CheckResponse with the check_info list.

Raises:

Type Description
ValueError

none of the search parameters was given — the API answers HTTP 400 in that case, so the request is not sent at all.

Note

Per the documentation each parameter is "required unless the others are given", i.e. at least one of the three is needed.

passports(*, order_uuid=None, cdek_number=None, client=None) async

Passport data information (GET /v2/passport).

The method does not return the passport data itself — only a flag that the requirements for it are met (relevant for international orders).

Parameters:

Name Type Description Default
order_uuid str | None

order UUID.

None
cdek_number str | None

CDEK order number.

None
client PassportClientLike | None

whose data to return — SENDER, RECEIVER or ALL (see :class:cdekx.types.enums.PassportClient). If omitted, CDEK returns data for both the sender and the recipient.

None

registries(date) async

Cash-on-delivery payment registries for a date (GET /v2/registries).

Parameters:

Name Type Description Default
date str

date in yyyy-MM-dd format. The parameter is required (the only one of this method): registries whose cash-on-delivery payment was transferred on that day are returned.

required

photo_ready_orders(request) async

Orders with ready document photos (POST /v2/photoDocument).

Parameters:

Name Type Description Default
request PhotoRequest | dict[str, Any]

:class:cdekx.models.PhotoRequest or a dict — the period (period_begin/period_end in yyyy-MM-dd'T'HH:mm:ssZ format) and/or a list of orders.

required

Returns:

Type Description
PhotoResponse

class:cdekx.models.PhotoResponse; the archive is ready to be

PhotoResponse

downloaded when status == "DONE" (see PhotoResponse.ready).

photo_archive(uuid) async

Download the ready document photo archive (GET /v2/photoDocument/{uuid}).

Parameters:

Name Type Description Default
uuid str

archive identifier from PhotoReadyOrder.link (see :attr:cdekx.models.PhotoReadyOrder.archive_uuid).

required

Returns:

Type Description
bytes

ZIP archive content.

Raises:

Type Description
NotFoundError

the archive is not ready yet or does not exist (HTTP 404).

ApiError

access denied (403) or a gateway error (502).

prealert_create(prealert) async

Register a prealert (POST /v2/prealert, response 202).

A prealert is required for international shipments: it describes handing a group of orders over to a specific office on a specific date.

Parameters:

Name Type Description Default
prealert PrealertCreate | dict[str, Any]

:class:cdekx.models.PrealertCreate or a dict. planned_date, shipment_point and orders are required.

required

Returns:

Type Description
PrealertTaskEnvelope

Task envelope with the prealert uuid.

Raises:

Type Description
ApiError

the prealert was rejected during validation (requests[].state == INVALID) — for example, the handover date is earlier than the contract allows or the office is unknown.

prealert_get(uuid) async

Prealert information (GET /v2/prealert/{uuid}).

Once the prealert is closed, closed_date, fact_shipment_point and package statuses appear in the response — they reveal discrepancies (see :attr:cdekx.models.Prealert.discrepancies).

international_restrictions(request) async

Restrictions for international orders.

POST /v2/international/package/restrictions. Checks weight and size parameters and the composition of attachments for the direction.

Parameters:

Name Type Description Default
request RestrictionRequest | dict[str, Any]

:class:cdekx.models.RestrictionRequest or a dict.

required

Returns:

Type Description
RestrictionHintsResponse

class:cdekx.models.RestrictionHintsResponse; the quick verdict is

RestrictionHintsResponse

response.is_allowed and response.forbidden.

Note

The specification declares the response with content type */* (not application/json) — this does not affect parsing.

raw(method, path, *, params=None, json_body=None, headers=None) async

Perform an arbitrary API request (raw JSON).

Use it when the method you need is not covered by the library yet — and file an issue or add the endpoint so that coverage catches up with the documentation (see docs/API_COVERAGE.md).

Example

data = await client.misc.raw("GET", "/v2/location/cities") # doctest: +SKIP

Утилиты

cdekx.utils

Practical helpers that are commonly needed alongside the CDEK API.

These are conveniences rather than part of the wire protocol: unit conversion, dimensional weight, phone number normalisation. Every function is pure and free of side effects.

kg_to_grams(kg)

Kilograms to grams (the CDEK API takes weight in grams).

grams_to_kg(grams)

Grams to kilograms.

calc_volume_weight(length_cm, width_cm, height_cm, *, divisor=DIMENSIONAL_DIVISOR)

Dimensional weight in kilograms, from dimensions in centimetres.

normalize_phone(phone, *, default_country_code='7')

Normalise a phone number to the international +79001234567 format.

Useful before submitting an order: CDEK rejects numbers without a leading + and numbers in the domestic 8 (900) 123-45-67 form.

packages_summary(packages)

Summarise a list of packages: total weight, volume and chargeable weight.

Returns:

Type Description
dict[str, float | int]

A dict with the keys count, weight_g, volume_cm3,

dict[str, float | int]

volume_weight_g and chargeable_weight_g.