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, output_dir=None)[source]

Bases: object

Using an authenticated AmazonSession, can be used to query Amazon for Order details and history.

amazon_session: AmazonSession

The AmazonSession to use for requests.

debug: bool

Set logger DEBUG and send output to stderr.

output_dir

The directory where any output files will be produced, defaults to conf.DEFAULT_OUTPUT_DIR.

get_order_history(year=2024, start_index=None, full_details=False)[source]

Get the Amazon order history for the given year.

Parameters:
  • year (int) – The year for which to get history.

  • start_index (Optional[int]) – The index to start at within the history.

  • full_details (bool) – Will execute an additional request per Order in the retrieved history to fully populate it.

Return type:

List[Order]

Returns:

A list of the requested Orders.

get_order(order_id)[source]

Get the Amazon order represented by the ID.

Parameters:

order_id (str) – The Amazon Order ID to lookup.

Return type:

Order

Returns:

The requested Order.

Session Management

class amazonorders.session.IODefault[source]

Bases: object

Handles input/output from the application. By default, this uses console commands, but this class exists so that it can be overriden when constructing an AmazonSession if input/output should be handled another way.

echo(msg, **kwargs)[source]

Echo a message to the console.

Parameters:
  • msg (str) – The data to send to output.

  • kwargs (Any) – Unused by the default implementation.

prompt(msg, type=None, **kwargs)[source]

Prompt to the console for user input.

Parameters:
  • msg (str) – The data to use as the input prompt.

  • type (Optional[str]) – Unused by the default implementation.

  • kwargs (Any) – Unused by the default implementation.

Returns:

The user input result.

class amazonorders.session.AmazonSession(username, password, debug=False, max_auth_attempts=10, cookie_jar_path=None, io=<amazonorders.session.IODefault object>, output_dir=None)[source]

Bases: object

An interface for interacting with Amazon and authenticating an underlying requests.Session. Utilizing this class means session data is maintained between requests. Session data is also persisted after each request, meaning it will also be maintained between separate instantiations of the class or application.

To get started, call the login function.

username: str

An Amazon username.

password: str

An Amazon password.

debug: bool

Set logger DEBUG, send output to stderr, and write an HTML file for requests made on the session.

max_auth_attempts: int

Will continue in login’s auth flow this many times (successes and failures).

cookie_jar_path: str

The path to persist session cookies, defaults to conf.DEFAULT_COOKIE_JAR_PATH.

io: IODefault

The I/O handler for echoes and prompts.

output_dir

The directory where any output files will be produced, defaults to conf.DEFAULT_OUTPUT_DIR.

session: Session

The shared session to be used across all requests.

last_response: Optional[Response]

The last response executed on the Session.

last_response_parsed: Optional[Tag]

A parsed representation of the last response executed on the Session.

is_authenticated: bool

If login has been executed and successfully logged in the session.

request(method, url, **kwargs)[source]

Execute the request against Amazon with base headers, parsing and storing the response and persisting response cookies.

Parameters:
  • method (str) – The request method to execute.

  • url (str) – The URL to execute method on.

  • kwargs (Any) – Remaining kwargs will be passed to requests.request.

Return type:

Response

Returns:

The Response from the executed request.

get(url, **kwargs)[source]

Perform a GET request.

Parameters:
Returns:

The Response from the executed GET request.

post(url, **kwargs)[source]

Perform a POST request.

Parameters:
Return type:

Response

Returns:

The Response from the executed POST request.

login()[source]

Execute an Amazon login process. This will include the sign-in page, and may also include Captcha challenges and OTP pages (of 2FA authentication is enabled on your account).

If successful, is_authenticated will be set to True.

Session cookies are persisted, and if existing session data is found during this auth flow, it will be skipped entirely and flagged as authenticated.

Return type:

None

logout()[source]

Logout and close the existing Amazon session and clear cookies.

Return type:

None

class amazonorders.forms.AuthForm(selector, error_selector='div#auth-error-message-box', critical=False)[source]

Bases: ABC

The base class of an authentication <form> that can be submitted.

The base implementation will attempt to auto-solve Captcha. If this fails, it will use the default image view to show the Captcha prompt, and it will also pass the image URL to prompt as img_url.

selector: str

The CSS selector for the <form>.

error_selector: str

The CSS selector for the error div when form submission fails.

critical: bool

If critical, form submission failures will raise AmazonOrdersAuthError.

amazon_session

The AmazonSession on which to submit the form.

form: Optional[Tag]

The selected <form>.

data: Optional[Dict[Any]]

The <form> data that will be submitted.

select_form(amazon_session, parsed)[source]

Using the selector defined on this instance, select the <form> for the given Tag.

Parameters:
  • amazon_session – The AmazonSession on which to submit the form.

  • parsed (Tag) – The Tag from which to select the <form>.

Return type:

bool

Returns:

Whether the <form> selection was successful.

fill_form(additional_attrs=None)[source]

Populate the data field with values from the <form>, including any additional attributes passed.

Parameters:

additional_attrs (Optional[Dict[str, Any]]) – Additional attributes to add to the <form> data for submission.

Return type:

None

submit()[source]

Submit the populated <form>.

Return type:

None

clear_form()[source]

Clear the populated <form> so this class can be reused.

Return type:

None

class amazonorders.forms.SignInForm(selector="form[name='signIn']", solution_attr_key='email')[source]

Bases: AuthForm

fill_form(additional_attrs=None)[source]

Populate the data field with values from the <form>, including any additional attributes passed.

Parameters:

additional_attrs (Optional[Dict[str, Any]]) – Additional attributes to add to the <form> data for submission.

Return type:

None

class amazonorders.forms.MfaDeviceSelectForm(selector='form#auth-select-device-form', solution_attr_key='otpDeviceContext')[source]

Bases: AuthForm

This will first echo the <form> device choices, then it will pass the list of choices to prompt as choices. The value passed to prompt will be a list of the value from each of input tag.

fill_form(additional_attrs=None)[source]

Populate the data field with values from the <form>, including any additional attributes passed.

Parameters:

additional_attrs (Optional[Dict[str, Any]]) – Additional attributes to add to the <form> data for submission.

Return type:

None

class amazonorders.forms.MfaForm(selector='form#auth-mfa-form', solution_attr_key='otpCode')[source]

Bases: AuthForm

fill_form(additional_attrs=None)[source]

Populate the data field with values from the <form>, including any additional attributes passed.

Parameters:

additional_attrs (Optional[Dict[str, Any]]) – Additional attributes to add to the <form> data for submission.

Return type:

None

class amazonorders.forms.CaptchaForm(selector='form.cvf-widget-form-captcha', error_selector='div.cvf-widget-alert', solution_attr_key='cvf_captcha_input')[source]

Bases: AuthForm

fill_form(additional_attrs=None)[source]

Populate the data field with values from the <form>, including any additional attributes passed.

Parameters:

additional_attrs (Optional[Dict[str, Any]]) – Additional attributes to add to the <form> data for submission.

Return type:

None

Entities

class amazonorders.entity.parsable.Parsable(parsed)[source]

Bases: object

A base class that contains a parsed representation of the entity, and can be extended to be made up of the entities fields utilizing the helper methods.

parsed: Tag

Parsed HTML data that can be used to populate the fields of the entity.

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.

Parameters:
  • parse_function (Callable[..., Any]) – The parse function to attempt safe execution.

  • kwargs (Any) – The kwargs will be passed to parse_function.

Return type:

Any

Returns:

The return value from parse_function.

simple_parse(selector, link=False, return_type=None, text_contains=None, required=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 selector can be either a str or a list. If a list is given, each selector in the list will be tried.

Parameters:
  • selector (Union[str, list]) – The CSS selector(s) for the field.

  • link (bool) – If a link, the value of src or href will be returned.

  • return_type (Optional[Type]) – Specify int or float to return a value other than str.

  • 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 returning None.

Return type:

Any

Returns:

The cleaned up return value from the parsed selector.

safe_simple_parse(selector, **kwargs)[source]

A helper function that uses simple_parse as the parse_function() passed to safe_parse.

Parameters:
  • selector (Union[str, list]) – The selector to pass to simple_parse.

  • kwargs – The kwargs will be passed to parse_function.

Return type:

Any

Returns:

The return value from simple_parse.

with_base_url(url)[source]

If the given URL is relative, the BASE_URL will be prepended.

Parameters:

url – The URL to check.

Returns:

The fully qualified URL.

class amazonorders.entity.item.Item(parsed)[source]

Bases: Parsable

An Item in an Amazon Order.

title: str

The Item title.

The Item link.

price: Optional[float]

The Item price.

seller: Optional[Seller]

The Item Seller.

condition: Optional[str]

The Item condition.

return_eligible_date: Optional[date]

The Item return eligible date.

The Item image URL.

quantity: Optional[int]

The Item quantity.

class amazonorders.entity.order.Order(parsed, full_details=False, clone=None)[source]

Bases: Parsable

An Amazon Order.

full_details: bool

If the Orders full details were populated from its details page.

shipments: List[Shipment]

The Order Shipments.

items: List[Item]

The Order Items.

order_number: str

The Order number.

The Order details link.

grand_total: float

The Order grand total.

order_placed_date: date

The Order placed date.

recipient: Recipient

The Order Recipients.

payment_method: Optional[str]

The Order payment method. Only populated when full_details is True.

payment_method_last_4: Optional[str]

The Order payment method’s last 4 digits. Only populated when full_details is True.

subtotal: Optional[float]

The Order subtotal. Only populated when full_details is True.

shipping_total: Optional[float]

The Order shipping total. Only populated when full_details is True.

subscription_discount: Optional[float]

The Order Subscribe & Save discount. Only populated when full_details is True.

total_before_tax: Optional[float]

The Order total before tax. Only populated when full_details is True.

estimated_tax: Optional[float]

The Order estimated tax. Only populated when full_details is True.

refund_total: Optional[float]

The Order refund total. Only populated when full_details is True.

order_shipped_date: Optional[date]

The Order shipped date. Only populated when full_details is True.

refund_completed_date: Optional[date]

The Order refund total. Only populated when full_details is True.

class amazonorders.entity.recipient.Recipient(parsed)[source]

Bases: Parsable

The person receiving an Amazon Order.

name: str

The Recipient name.

address: Optional[str]

The Recipient address.

class amazonorders.entity.seller.Seller(parsed)[source]

Bases: Parsable

An Amazon Seller of an Amazon Item.

name: str

The Seller name.

The Seller link.

class amazonorders.entity.shipment.Shipment(parsed)[source]

Bases: Parsable

An Amazon Shipment, which should contain one or more Item’s.

items: List[Item]

The Shipment Items.

delivery_status: Optional[str]

The Shipment delivery status.

The Shipment tracking link.

Exceptions

exception amazonorders.exception.AmazonOrdersError[source]

Bases: Exception

Raised when a general amazon-orders error has occurred.

exception amazonorders.exception.AmazonOrdersAuthError[source]

Bases: AmazonOrdersError

Raised when an amazon-orders authentication error has occurred.

exception amazonorders.exception.AmazonOrderEntityError[source]

Bases: AmazonOrdersError

Raised when an amazon-orders entity parsing error has occurred.