API Documentation¶
This part of the documentation covers the interfaces used to develop with amazon-orders.
Main Interface¶
- class amazonorders.orders.AmazonOrders(amazon_session, debug=None, config=None)[source]¶
Bases:
objectUsing an authenticated
AmazonSession, can be used to query Amazon for Order details and history.- amazon_session: AmazonSession¶
The session to use for requests.
- config: AmazonOrdersConfig¶
The config to use.
- get_invoice(order_id)[source]¶
Get the print-friendly invoice page for a given Amazon Order ID, returning the response (including its parsed HTML) so callers can render or print the page.
- Parameters:
order_id (
str) – The Amazon Order ID to lookup.- Return type:
- Returns:
The invoice page response.
- get_order_history(year=None, start_index=None, full_details=False, keep_paging=True, time_filter=None)[source]¶
Get the Amazon Order history for a given time period.
- Parameters:
year (
Optional[int]) – The year for which to get history. Ignored iftime_filteris provided. Defaults to the current year if neitheryearnortime_filteris specified.start_index (
Optional[int]) – The index of the Order from which to start fetching in the history. Seeindexto correlate, or if a call to this method previously errored out, seeindexin the exception’smetato continue paging where it left off.full_details (
bool) – Get the full details for each Order in the history. This will execute an additional request per Order.keep_paging (
bool) –Falseif only one page should be fetched.time_filter (
Optional[str]) – The time filter to use. Supported values are"last30"(last 30 days),"months-3"(past 3 months), or"year-YYYY"(specific year). If provided, this takes precedence over theyearparameter.
- Return type:
- Returns:
A list of the requested Orders.
- class amazonorders.transactions.AmazonTransactions(amazon_session, debug=None, config=None)[source]¶
Bases:
objectUsing an authenticated
AmazonSession, can be used to query Amazon for Transaction details and history.- amazon_session: AmazonSession¶
The session to use for requests.
- config: AmazonOrdersConfig¶
The config to use.
- get_transactions(days=365, next_page_data=None, keep_paging=True, order_id=None)[source]¶
Get Amazon Transaction history for a given number of days, or for a single Order.
- Parameters:
days (
int) – The number of days worth of Transactions to get. Ignored whenorder_idis given.next_page_data (
Optional[Dict[str,Any]]) – If a call to this method previously errored out, passing the exception’smetawill continue paging where it left off.keep_paging (
bool) –Falseif only one page should be fetched.order_id (
Optional[str]) – If given, only Transactions for this Amazon Order ID are returned, scoped server-side via Amazon’stransactionTagfilter (thedayswindow does not apply).
- Return type:
- Returns:
A list of the requested Transactions.
Session Management¶
- class amazonorders.session.IODefault[source]¶
Bases:
objectHandles input/output from the application. By default, this uses console commands, but this class exists so that it can be overridden when constructing an
AmazonSessionif input/output should be handled another way.
- class amazonorders.session.AmazonSession(username=None, password=None, debug=False, io=<amazonorders.session.IODefault object>, config=None, auth_forms=None, otp_secret_key=None, domain=None)[source]¶
Bases:
objectAn interface for interacting with Amazon and authenticating an underlying
requests.Session. Utilizing this class means session data is maintained between requests. Session data may also persisted after each request, so it can also be maintained between separate instantiations of the class or application.To get started, call the
loginfunction.- username: str | None¶
An Amazon username. Environment variable
AMAZON_USERNAMEwill override passed in or config value.
- password: str | None¶
An Amazon password. Environment variable
AMAZON_PASSWORDwill override passed in or config value.
- otp_secret_key: str | None¶
The secret key Amazon provides when manually adding a 2FA authenticator app. Setting this will allow one-time password challenges to be auto-solved. Environment variable
AMAZON_OTP_SECRET_KEYwill override passed in or config value.
- debug: bool¶
Setting logger to
DEBUGwill send output tostderrand write an HTML file for all requests made on the session.
- config: AmazonOrdersConfig¶
The config to use.
- auth_forms: List[AuthForm]¶
The list of form implementations to use with authentication. If a value is passed for this when instantiating an AmazonSession, ensure that list is populated with the default form implementations.
default_auth_formsreturns the default chain so callers can extend it instead of duplicating it.
- static default_auth_forms(config)[source]¶
Build the default ordered list of
AuthForminstances used byAmazonSession. Callers wishing to inject a custom form (e.g. a third-party WAF Captcha solver) can call this and insert their own handler before passing the list asauth_forms.- Parameters:
config (
AmazonOrdersConfig) – The config to bind to each form.- Return type:
- Returns:
The default ordered list of
AuthForminstances.
- request(method, url, persist_cookies=False, **kwargs)[source]¶
Execute the request against Amazon with base headers, parsing and storing the response.
- Parameters:
method (
str) – The request method to execute.url (
str) – The URL to executemethodon.persist_cookies (
bool) – IfTrue, cookies from the response will be persisted to a file.kwargs (
Any) – Remainingkwargswill be passed torequests.request.
- Return type:
- Returns:
The response from the executed request.
- get(url, **kwargs)[source]¶
Perform a
GETrequest.- Parameters:
url (
str) – The URL to request.kwargs (
Any) – Remainingkwargswill be passed toAmazonSession.request.
- Return type:
- Returns:
The response from the executed request.
- post(url, **kwargs)[source]¶
Perform a
POSTrequest.- Parameters:
url (
str) – The URL to request.kwargs (
Any) – Remainingkwargswill be passed toAmazonSession.request.
- Return type:
- Returns:
The response from the executed request.
- login()[source]¶
Execute an Amazon login process. This will include the sign-in page, and may also include OTP (if 2FA is enabled for your account), Captcha challenges, and any other forms in
auth_forms.If successful,
is_authenticatedwill be set toTrue.If existing session data is already persisted, calling this function will still attempt to reauthenticate to refresh it.
- Return type:
- check_response(amazon_session_response, meta=None)[source]¶
Check the response to ensure it appears to be returning a valid response, and that it is still authenticated. We detect if authentication has expired by checking for redirects to the login page. Raise an error if the response is not going to contain the requested data for parsing.
- class amazonorders.forms.AuthForm(config, selector, error_selector=None, critical=False)[source]¶
Bases:
ABCThe base class of an authentication
<form>that can be submitted.The base implementation will attempt to auto-solve Captcha when the optional
amazoncaptchadependency is installed (pip install amazon-orders[captcha], available on Python <=3.12 only). If auto-solve is unavailable or fails, it will use the default image view to show the Captcha prompt, and it will also pass the image URL topromptasimg_url.- config: AmazonOrdersConfig¶
The config to use.
- critical: bool¶
If
True, form submission failures will raiseAmazonOrdersAuthError.
- amazon_session: AmazonSession | None¶
The
AmazonSessionon which to submit the form.
- select_form(amazon_session, parsed)[source]¶
Using the
selectordefined on this instance, select the<form>for the givenTag.- Parameters:
amazon_session (
AmazonSession) – TheAmazonSessionon which to submit the form.parsed (
Tag) – TheTagfrom which to select the<form>.
- Return type:
- Returns:
Whether the
<form>selection was successful.
- fill_form(additional_attrs=None)[source]¶
Populate the
datafield with values from the<form>, including any additional attributes passed.
- class amazonorders.forms.SignInForm(config, selector=None, solution_attr_key='email')[source]¶
Bases:
AuthForm
- class amazonorders.forms.ClaimForm(config, selector=None, solution_attr_key='email')[source]¶
Bases:
AuthForm
- class amazonorders.forms.IntentForm(config, selector=None, error_selector=None)[source]¶
Bases:
AuthForm- submit(last_response)[source]¶
When we encounter this form, we can’t submit it, so we display its contents as the error message, since within the context of this library, it is a termination event for the auth flow.
- Parameters:
last_response (
Response) – The response of the request that fetched the form.- Return type:
- Returns:
The response from the executed request.
- class amazonorders.forms.MfaDeviceSelectForm(config, selector=None, solution_attr_key='otpDeviceContext')[source]¶
Bases:
AuthFormThis will first echo the
<form>device choices, then it will pass the list of choices topromptaschoices. The value passed topromptwill be alistof thevaluefrom each ofinputtag.
- class amazonorders.forms.MfaForm(config, selector=None, solution_attr_key='otpCode')[source]¶
Bases:
AuthForm
- class amazonorders.forms.CaptchaForm(config, selector=None, error_selector=None, solution_attr_key='cvf_captcha_input')[source]¶
Bases:
AuthForm
- class amazonorders.forms.AcicAuthBlocker(config)[source]¶
Bases:
AuthForm- select_form(amazon_session, parsed)[source]¶
Using the
selectordefined on this instance, select the<form>for the givenTag.- Parameters:
amazon_session (
AmazonSession) – TheAmazonSessionon which to submit the form.parsed (
Tag) – TheTagfrom which to select the<form>.
- Return type:
- Returns:
Whether the
<form>selection was successful.
- class amazonorders.forms.JSAuthBlocker(config, regex)[source]¶
Bases:
AuthForm- select_form(amazon_session, parsed)[source]¶
Using the
selectordefined on this instance, select the<form>for the givenTag.- Parameters:
amazon_session (
AmazonSession) – TheAmazonSessionon which to submit the form.parsed (
Tag) – TheTagfrom which to select the<form>.
- Return type:
- Returns:
Whether the
<form>selection was successful.
Configuration¶
- class amazonorders.conf.AmazonOrdersConfig(config_path=None, data=None)[source]¶
Bases:
objectAn object containing
amazon-orders’s configuration. The state of this object is populated from the config file, if present, when it is instantiated, and it is also persisted back to the config file whensaveis called.If overrides are passed in
dataparameter when this object is instantiated, they will be used to populate the new object, but not persisted to the config file untilsaveis called.Default values provisioned with the config can be found here.
- set_domain(domain)[source]¶
Set the active Amazon domain and rebuild
constantsso URL-derived attributes and region-sensitive headers reflect the change.
- amazonorders.constants._BROWSER_PRESETS: Dict[str, Dict[str, str | None]] = {'chromium': {}, 'firefox': {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Sec-Ch-Ua': None, 'Sec-Ch-Ua-Mobile': None, 'Sec-Ch-Ua-Platform': None, 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:146.0) Gecko/20100101 Firefox/146.0'}}¶
Browser-specific header overrides applied on top of the class-level
BASE_HEADERS(which already reflects the Chromium fingerprint). ANonevalue removes the key (used to strip headers absent in that engine).Accept-Languagehere is the browser default; domain-specific TLD overrides still apply on top via_apply_domain.
- amazonorders.constants._REGION_LANGUAGES = {'ca': 'en-CA,en;q=0.9,en-US;q=0.8', 'co.uk': 'en-GB,en;q=0.9,en-US;q=0.8', 'com.au': 'en-AU,en;q=0.9,en-US;q=0.8', 'in': 'en-IN,en;q=0.9,en-US;q=0.8', 'sg': 'en-SG,en;q=0.9,en-US;q=0.8'}¶
Accept-Languagevalues for English-locale Amazon sites, keyed by the TLD suffix that followsamazon.. Looked up dynamically from the user-supplied domain; unknown TLDs keep the baseen-USvalue. This map only governs theAccept-Languageheader — it is not a list of supported sites and does not affect any other authentication behavior.
- amazonorders.constants._REGION_CURRENCIES = {'co.uk': '£', 'in': '₹', 'sg': 'S$'}¶
CURRENCY_SYMBOLvalues for English-locale Amazon sites where the storefront actually prefixes prices with a non-$symbol. amazon.com.au and amazon.ca render prices as plain$(single-currency context), so they keep the default and are intentionally omitted here. Skipped whenAMAZON_CURRENCY_SYMBOLis set.
- class amazonorders.constants.Constants(config=None)[source]¶
Bases:
objectA class containing useful constants. Extend and override with
constants_classin the config:from amazonorders.conf import AmazonOrdersConfig config = AmazonOrdersConfig(data={"constants_class": "my_module.MyConstants"})
URLs and the URL-shaped headers (
Origin,Host,Referer) are derived from the active Amazon domain.Accept-LanguageandCURRENCY_SYMBOLare adjusted for a small set of English-locale TLDs (CURRENCY_SYMBOLonly whenAMAZON_CURRENCY_SYMBOLis unset). The domain is resolved in this precedence order:The
domainkey onAmazonOrdersConfig.The
AMAZON_BASE_URLenvironment variable.The default,
amazon.com.
Only the English,
.comsite is officially supported. Other domains may work, but values likeopenid.assoc_handleare not adjusted automatically — subclass and setconstants_classto override them if a non-.comsite requires it.
Entities¶
- class amazonorders.entity.parsable.Parsable(parsed, config)[source]¶
Bases:
objectA base class that contains a parsed representation of the entity, which can be extended to build an entity that utilizes the common the helper methods.
- config: AmazonOrdersConfig¶
The config to use.
- safe_parse(parse_function, **kwargs)[source]¶
Execute the given parse function on a field, handling any common parse exceptions and passing them as warnings to the logger (suppressing them as exceptions).
- simple_parse(selector, attr_name=None, text_contains=None, required=False, prefix_split=None, wrap_tag=None, parse_date=False, prefix_split_fuzzy=False, suffix_split=None, suffix_split_fuzzy=False)[source]¶
Will attempt to extract the text value of the given CSS selector(s) for a field, and is suitable for most basic functionality on a well-formed page.
The
selectorcan be either astror alist. If alistis given, each selector in the list will be tried.In most cases the selected tag’s text will be returned, but if
wrap_tagis given, the tag itself (wrapped in the class) will be returned.- Parameters:
selector (
Union[str,list]) – The CSS selector(s) for the field.attr_name (
Optional[str]) – If provided, return the value of this attribute on the selected field.text_contains (
Optional[str]) – Only select the field if this value is found in its text content.required (
bool) – If required, an exception will be thrown instead of returningNone.prefix_split (
Optional[str]) – Only select the field with the given prefix, returning the right side of the split if so.wrap_tag (
Optional[Type]) – Wrap the selected tag in this class before returning.parse_date (
bool) –Trueif the resulting value should be fuzzy parsed in to a date (returningNoneif parsing fails).prefix_split_fuzzy (
bool) –Trueif the value should still be used even ifprefix_splitis not found.suffix_split (
Optional[str]) – Only select the field with the given suffix, returning the left side of the split if so.suffix_split_fuzzy (
bool) –Trueif the value should still be used even ifsuffix_splitis not found.
- Return type:
- Returns:
The cleaned up return value from the parsed
selector.
- safe_simple_parse(selector, **kwargs)[source]¶
A helper function that uses
simple_parseas theparse_function()passed tosafe_parse.- Parameters:
selector (
Union[str,list]) – The CSS selector to pass tosimple_parse.kwargs (
Any) – Thekwargswill be passed toparse_function.
- Return type:
- Returns:
The return value from
simple_parse.
- to_currency(value)[source]¶
Clean up a currency, stripping non-numeric values and returning it as a primitive.
Recognizes the
$,£,€, and₹symbols (and leading currency-code letters such asA$orCDN$), accepts accounting-style negatives in parentheses (e.g.($1.99)), and treats a literalFREEas0.0.
- class amazonorders.entity.item.Item(parsed, config)[source]¶
Bases:
ParsableAn Item in an Amazon
Order. If desired fields are populated asNone, ensurefull_detailsisTruewhen retrieving the Order (for instance, withget_order_history), since by default it isFalse(it will slow down querying).
- class amazonorders.entity.order.Order(parsed, config, full_details=False, clone=None, index=None, order_number=None)[source]¶
Bases:
ParsableAn Amazon Order. If desired fields are populated as
None, ensurefull_detailsisTruewhen retrieving the Order (for instance, withget_order_history), since by default it isFalse(enabling slows down querying).- index: int | None¶
Where the Order appeared in the history when it was queried. This will inevitably change (ex. when a new Order is placed, all indexes will then be off by one), but is still captured as it may be applicable in various use-cases. Populated when the Order was fetched through
get_order_history(usestart_indexto correlate), or when theclonehas itsindexset.
- cancelled: bool¶
Trueif the Order was cancelled. WhenTrue, fields likegrand_totaland the totals on the details page may beNonebecause Amazon stops rendering them.
- order_number: str | None¶
The Order number. May be
Noneonly when the Order iscancelledand Amazon stripped the order number from the details page (theorder_numberparameter is used as a fallback in that case).
- payment_method_last_4: int | None¶
The Order payment method’s last 4 digits. Only populated when
full_detailsisTrue.
- promotion_applied: float | None¶
The Order promotion applied. Only populated when
full_detailsisTrue.
- subscription_discount: float | None¶
The Order Subscribe & Save discount. Only populated when
full_detailsisTrue.
- class amazonorders.entity.recipient.Recipient(parsed, config)[source]¶
Bases:
ParsableThe person receiving an Amazon
Order.
- class amazonorders.entity.seller.Seller(parsed, config)[source]¶
Bases:
ParsableAn Amazon Seller of an Amazon
Item.
- class amazonorders.entity.shipment.Shipment(parsed, config)[source]¶
Bases:
ParsableAn Amazon Shipment, which should contain one or more
Item’s.
Exceptions¶
- exception amazonorders.exception.AmazonOrdersError(error, meta=None)[source]¶
Bases:
ExceptionRaised when a general
amazon-orderserror has occurred.
- exception amazonorders.exception.AmazonOrdersNotFoundError(error, meta=None)[source]¶
Bases:
AmazonOrdersErrorRaised when an Amazon page is not found.
- exception amazonorders.exception.AmazonOrdersAuthError(error, meta=None)[source]¶
Bases:
AmazonOrdersErrorRaised when an
amazon-ordersauthentication error has occurred.
- exception amazonorders.exception.AmazonOrdersAuthRedirectError(error, meta=None)[source]¶
Bases:
AmazonOrdersAuthErrorRaised when an
amazon-orderssession that was previously authenticated redirects to login, indicating the likely need to reauthenticate.
- exception amazonorders.exception.AmazonOrdersEntityError(error, meta=None)[source]¶
Bases:
AmazonOrdersErrorRaised when an
amazon-ordersentity parsing error has occurred.
Utility Functions¶
- class amazonorders.util.AmazonSessionResponse(response, bs4_parser)[source]¶
Bases:
objectA wrapper for the
requests.Responseobject, which also contains the parsed HTML.
- amazonorders.util.select(parsed, selector)[source]¶
This is a helper function that extends BeautifulSoup’s select() method to allow for multiple selectors. The
selectorcan be either astror alist. If alistis given, each selector in the list will be tried until one is found to return a populated list ofTag’s, and that value will be returned.
- amazonorders.util.select_one(parsed, selector)[source]¶
This is a helper function that extends BeautifulSoup’s select_one() method to allow for multiple selectors. The
selectorcan be either astror alist. If alistis given, each selector in the list will be tried until one is found to return a populatedTag, and that value will be returned.
- amazonorders.util.to_type(value)[source]¶
Attempt to convert
valueto its primitive type ofint,float, orbool.If
valueis an empty string,Nonewill be returned.