Python wrapper to access the amazon selling partner API

Overview

PYTHON-AMAZON-SP-API

CodeQL Tests

Maintainability Tech Coverage

Amazon Selling-Partner API

If you have questions, please join on slack

slack

Contributions very welcome!


Installation

Badge

pip install python-amazon-sp-api

Usage

# orders API
try:
    res = Orders().get_orders(CreatedAfter=(datetime.utcnow() - timedelta(days=7)).isoformat())
    print(res.payload)  # json data
except SellingApiException as ex:
    print(ex)


# report request     
createReportResponse = Reports().create_report(reportType='GET_FLAT_FILE_OPEN_LISTINGS_DATA')

# submit feed
# feeds can be submitted like explained in Amazon's docs, or simply by calling submit_feed

Feeds().submit_feed(self, <feed_type>, <file_or_bytes_io>, content_type='text/tsv', **kwargs)

Documentation

Documentation is available here

Documentation Status

DISCLAIMER

We are not affiliated with Amazon

LICENSE

License

Comments
  • 'message': 'Access to requested resource is denied.',    'code': 'Unauthorized' issue

    'message': 'Access to requested resource is denied.', 'code': 'Unauthorized' issue

    I have been getting this error for every request. I currently have a Seller Central account and I am trying to gain access to the api. I have followed the documentation provided by amazon to set up the necessary credentials, but still receive the 'Access to requested resource is denied.' error message. I have checked in on the access_token that is being generated and it matches the 'Atza|xxxxxx' format, so I do not believe that is the issue.

    Additionally, I have been following the Self Authorization guidelines to get the refresh token used here, so I am unsure as to why I am getting the error.

    I have searched through the issues here and under the Seller-partner-api-docs and found no solution.

    from sp_api.api.orders.orders import Orders
    
    os.environ["SP_API_REFRESH_TOKEN"] = "Atzr|xxxxxxxx"
    os.environ["LWA_APP_ID"] = "amzn1.application-oa2-client.xxxxxxxx"
    os.environ["LWA_CLIENT_SECRET"] = "xxxxxxxx"
    os.environ["SP_API_SECRET_KEY"] = "xxxxxxxx"
    os.environ["SP_API_ACCESS_KEY"] = "xxxxxxxx"
    os.environ["SP_API_ROLE_ARN"] = "arn:aws:iam::xxxxxxxx:role/SellerPartnerAPIRole"
    os.environ["SP_AWS_REGION"] = "us-east-1"
    
    try:
        res = Orders().get_orders(CreatedAfter=(datetime.datetime.utcnow() - datetime.timedelta(days=7)).isoformat())
        print(res.payload)  # json data
    except SellingApiException as ex:
        print(ex)
    

    output {'Date': 'Wed, 27 Jan 2021 15:22:51 GMT', 'Content-Type': 'application/json', 'Content-Length': '141', 'Connection': 'keep-alive', 'x-amzn-RequestId': '387bf5b0-58c6-4dee-93a0-47c3da1fadc0', 'x-amzn-ErrorType': 'AccessDeniedException', 'x-amz-apigw-id': 'Z0HDvHjOoAMF0Aw='} {'errors': [{'message': 'Access to requested resource is denied.', 'code': 'Unauthorized', 'details': ''}]} [{'message': 'Access to requested resource is denied.', 'code': 'Unauthorized', 'details': ''}]

    Any help will be greatly appreciated!

    opened by The-Geology-Guy 34
  • Request headers are not editable, causing problem with RDT

    Request headers are not editable, causing problem with RDT

    Orders

    To get more information about ShippingAddress and BuyerInfo from getOrders calls we have to pass restricted data token to request headers. Instead of using access token for x-amz-access-token, we need to pass RDT.

    As far as I see there is no way to reach request headers to edit it.

    My Suggestion

    response = Orders(**credentials).get_orders(**params, restricted_data_token="Atz.r|...")

    Restricted data token is special for order endpoints. So I believe we can implement a usage like above.

    I can work on it and open a pull request next 1 or 2 days.

    What do you think?

    enhancement hacktoberfest 
    opened by ethemguner 15
  • Getting error from sample code. Need clear documentation to run that at least.

    Getting error from sample code. Need clear documentation to run that at least.

    Describe the bug When I run the sample code in the readme.md, it doesn't succeed.

    To Reproduce Steps to reproduce the behavior:

    1. Go to '...'
    2. Click on '....'
    3. Scroll down to '....'
    4. See error

    Expected behavior A clear and concise description of what you expected to happen.

    Desktop (please complete the following information):

    • OS: Ubuntu 20
    • Browser:
    • Version [e.g. 22]

    Smartphone (please complete the following information):

    • Device: [e.g. iPhone6]
    • OS: [e.g. iOS8.1]
    • Browser [e.g. stock browser, safari]
    • Version [e.g. 22]

    Additional context Add any other context about the problem here.

    question 
    opened by fkhjoy 14
  • Force user SKU quote

    Force user SKU quote

    ProductFees() api does not encript SKU containing forward slash as described here #431

    As SKU is part of URL some of the chars in SKU could yield issue with URL formatting so we get SellingApiForbiddenException due invalid URL

    Fix should handle this behavior.
    Also there is option to disable this conversion if needed as I imagine there will be cases where this will be problematic.

    Currently it will default to True so all SKU will be quoted.

    opened by abrihter 12
  • UnicodeEncodeError when downloading/decrypting using Reports().get_report_document()

    UnicodeEncodeError when downloading/decrypting using Reports().get_report_document()

    Describe the bug Python throws a UnicodeEncodeError exception when using Reports().get_report_document().

    To Reproduce Steps to reproduce the behavior:

    # report request
    createReportResponse = Reports(credentials=credentials
        ,marketplace=marketplaces.Marketplaces.CA).create_report(
            reportType="GET_BRAND_ANALYTICS_SEARCH_TERMS_REPORT",
            reportOptions={"reportPeriod": "WEEK"},
            dataStartTime="2021-10-03",
            dataEndTime="2021-10-09"
            )
    
    # report id
    report_id = createReportResponse.payload['reportId']
    print("Report ID: ", report_id)
    
    # get report (loop)
    getReportResponse = Reports(credentials=credentials, marketplace=marketplaces.Marketplaces.CA).get_report(report_id=report_id)
    while getReportResponse.payload['processingStatus'] != 'DONE':
        print("Report status is: %s. Sleeping for 10 seconds..." % getReportResponse.payload['processingStatus'])
        time.sleep(10)
        getReportResponse = Reports(credentials=credentials, marketplace=marketplaces.Marketplaces.CA).get_report(report_id=report_id)
    
    # report document id
    report_document_id = getReportResponse.payload['reportDocumentId']
    print("Report document ID: ", report_document_id)
    
    # create filename
    output_file = report_document_id + ".json"
    
    # get report document
    getReportDocumentResponse = Reports(credentials=credentials,
        marketplace=marketplaces.Marketplaces.CA).get_report_document(
            document_id=report_document_id,
            decrypt=True,
            file=output_file,
            character_code='utf-8'
            )
    

    Expected behavior Report download, decrypts, and decompresses without throwing an exception.

    Desktop (please complete the following information):

    • OS: Windows 10

    Additional context I've tried specifying different values for character_code such as iso-8859-1 but I still get an exception.

    bug 
    opened by Guerri114 11
  • Problem with request

    Problem with request

    Hi, we have communication problem with amazon. Our client logs in to our service where he clicks button "Log in Amazon". He is then redirected to url https://sellercentral.amazon.pl/apps/authorize/consent?application_id=amzn1.sellerapps.app.xxxx-xxxx-xxx-xxx-xxx&state=here_is_unique_uid. On this page our partner accepts the usage for our application and is redirected back, from that action we get selling_partner_id and spapi_oauth_code. After that we send request on https://api.amazon.com/auth/o2/token with data: {'grant_type': "authorization_code", 'code': spapi_oauth_code, 'redirect_uri': redirect_url, 'client_id': AMAZON_CLIENT_ID,
    'client_secret': AMAZON_SECRET } where AMAZON_CLIENT_ID and AMAZON_SECRET are LWA credentials of app. In response we receive access_token and refresh token. Till this point everything works fine.

    Now we try to get orders data: 1. We request Login with Amazon access token on /auth/o2/token with params: client_id, client_secret (LWA credentials of app) grant_type=refresh_token, refresh_token=refresh token we have from previous step. In response we receive new access_token and refresh_token.

    We create assume role request on sts.amazonaws.com using AWS_ACCESS from AWS for credential and AWS_SECRET from AWS for computing signature. From that response we get SessionToken and accesskeyid.

    Final request for orders: GET on sellingpartnerapi-eu.amazon.com/orders/v0/orders in Authorization header for credential we use accesskeyid from assume role request, for X-Amz-Access-Token header we use access token from 1st request, and for X-Amz-Security-Token we send sessiontoken received from assumrole request for that data we receive 403 forbidden error HTTP/2.0 403 Forbidden Content-Length: 141 Content-Type: application/json Date: Wed, 07 Apr 2021 13:33:57 GMT X-Amz-Apigw-Id: daku6GYXDoEFQPw= X-Amzn-Errortype: AccessDeniedException X-Amzn-Requestid: 55ff0680-a7c1-412d-830d-cc3b018ea1b9

    { "errors": [ { "message": "Access to requested resource is denied.", "code": "Unauthorized", "details": "" } ] }

    We don't have idea what is wrong. Our app have a access permission to get order.

    bug 
    opened by sw69 11
  • getListingsItem doesn't work if there are white spaces in SKU Param

    getListingsItem doesn't work if there are white spaces in SKU Param

    When calling ListingItems.get_listing_item() passing in a SKU that contains whitespaces results in a NOT FOUND error. It seems like the whitespaces are being encoded/ encoded improperly? Can't fully tell what is causing the issue but it is returning

    [{'code': 'NOT_FOUND', 'message': "SKU 'XXXX%20YYY%20ZZZ' not found in marketplace ATVPDKIKX0DER"}]

    bug 
    opened by DanielLanger 9
  • AttributeError: 'list' object has no attribute 'get'

    AttributeError: 'list' object has no attribute 'get'

    I am calling the get_order endpoint like this, api_response = orders_api.get_orders( CreatedAfter=created_after, CreatedBefore=created_before, NextToken=next_token, ) and it was working very well recently, but now when I call it, I get this error File "/mnt/c/Users/ayubz/Documents/Amazing Brand/amazon-due-diligence/logic/get_orders.py", line 49, in get_orders api_response = orders_api.get_orders( File "/home/zakir/.local/lib/python3.8/site-packages/sp_api/base/helpers.py", line 21, in wrapper return function(*args, **kwargs) File "/home/zakir/.local/lib/python3.8/site-packages/sp_api/api/orders/orders.py", line 51, in get_orders return self._request(kwargs.pop('path'), params={**kwargs}) File "/home/zakir/.local/lib/python3.8/site-packages/sp_api/base/client.py", line 114, in _request return self._check_response(res) File "/home/zakir/.local/lib/python3.8/site-packages/sp_api/base/client.py", line 118, in _check_response error = res.json().get('errors', None) AttributeError: 'list' object has no attribute 'get' Any idea why this might be happening?

    bug 
    opened by Zakir-Ayub 9
  • restrictedResources only works if not is an array

    restrictedResources only works if not is an array

    Describe the bug When I call create_restricted_data_token only works when restrictedResources is called like and object, not as array.

    To Reproduce

    This not works: token_res = Tokens().create_restricted_data_token(restrictedResources=[{ "method": "GET", "path": "/orders/v0/orders", "dataElements": ["buyerInfo", "shippingAddress"] } ])

    This works: token_res = Tokens().create_restricted_data_token(restrictedResources={ "method": "GET", "path": "/orders/v0/orders", "dataElements": ["buyerInfo", "shippingAddress"] } )

    I don't know if it is a documentation mistake o a bug in the api.

    bug 
    opened by ximo1984 9
  • def get_product_fees_estimate(self, estimate_requests: list[dict]) -> ApiResponse:

    def get_product_fees_estimate(self, estimate_requests: list[dict]) -> ApiResponse:

    I'm testing it for the first time today. I am getting this error even though I have everything set up correctly.

    What is the reason for this error?

    File "D:\anaconda3\lib\site-packages\sp_api\api\product_fees\product_fees.py", line 99, in ProductFees def get_product_fees_estimate(self, estimate_requests: list[dict]) -> ApiResponse: TypeError: 'type' object is not subscriptable

    from sp_api.base import Marketplaces
    from sp_api.api import Orders
    
    credentials = dict(
        refresh_token='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',  # From Seller central under Authorise -> Refresh Token
        lwa_app_id='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',  # From Seller Central, named CLIENT IDENTIFIER on website.
        lwa_client_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',  # From Seller Central, named CLIENT SECRET on website.
        aws_access_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',  # From AWS IAM Setup
        aws_secret_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',  # From AWS IAM Setup
        role_arn='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  #arn:aws:iam::1234567890:role/SellingPartnerAPIRole
    )
    
    order_client = Orders(credentials=credentials, marketplace=Marketplaces.AU)
    order = order_client.get_order('111-4412524-0850212')
    print(order) # `order` is an `ApiResponse`
    print(order.payload) # `payload` contains the original response
    

    Thank you

    bug 
    opened by cnr91 8
  • Inventory API not working...

    Inventory API not working...

    I'm requesting by following code. inventoryClient = api.Inventories(credentials=self.credentials, marketplace=Marketplaces.JP) res = inventoryClient.get_inventory_summary_marketplace(sellerSkus=['sku1', 'sku2']) Then I'm getting error.

    sp_api.base.exceptions.SellingApiForbiddenException: [{'message': 'Access to requested resource is denied.', 'code': 'Unauthorized', 'details': ''}]

    However my credentials is correct. Other API(feed, report...) is working. Please help me.

    opened by kstar0101 8
Releases(v0.17.5)
OpenFace – a state-of-the art tool intended for facial landmark detection, head pose estimation, facial action unit recognition, and eye-gaze estimation.

OpenFace 2.2.0: a facial behavior analysis toolkit Over the past few years, there has been an increased interest in automatic facial behavior analysis

Tadas Baltrusaitis 5.8k Dec 31, 2022
PyTorch Implementation of VAENAR-TTS: Variational Auto-Encoder based Non-AutoRegressive Text-to-Speech Synthesis.

VAENAR-TTS - PyTorch Implementation PyTorch Implementation of VAENAR-TTS: Variational Auto-Encoder based Non-AutoRegressive Text-to-Speech Synthesis.

Keon Lee 67 Nov 14, 2022
Pytorch cuda extension of grid_sample1d

Grid Sample 1d pytorch cuda extension of grid sample 1d. Since pytorch only supports grid sample 2d/3d, I extend the 1d version for efficiency. The fo

lyricpoem 24 Dec 03, 2022
Resilience from Diversity: Population-based approach to harden models against adversarial attacks

Resilience from Diversity: Population-based approach to harden models against adversarial attacks Requirements To install requirements: pip install -r

0 Nov 23, 2021
A certifiable defense against adversarial examples by training neural networks to be provably robust

DiffAI v3 DiffAI is a system for training neural networks to be provably robust and for proving that they are robust. The system was developed for the

SRI Lab, ETH Zurich 202 Dec 13, 2022
Non-Vacuous Generalisation Bounds for Shallow Neural Networks

This package requires jax, tensorflow, and numpy. Either tensorflow or scikit-learn can be used for loading data. To run in a nix-shell with required

Felix Biggs 0 Feb 04, 2022
Official pytorch implementation of paper "Image-to-image Translation via Hierarchical Style Disentanglement".

HiSD: Image-to-image Translation via Hierarchical Style Disentanglement Official pytorch implementation of paper "Image-to-image Translation

364 Dec 14, 2022
Open-sourcing the Slates Dataset for recommender systems research

FINN.no Recommender Systems Slate Dataset This repository accompany the paper "Dynamic Slate Recommendation with Gated Recurrent Units and Thompson Sa

FINN.no 48 Nov 28, 2022
A Kitti Road Segmentation model implemented in tensorflow.

KittiSeg KittiSeg performs segmentation of roads by utilizing an FCN based model. The model achieved first place on the Kitti Road Detection Benchmark

Marvin Teichmann 890 Jan 04, 2023
Geometry-Free View Synthesis: Transformers and no 3D Priors

Geometry-Free View Synthesis: Transformers and no 3D Priors Geometry-Free View Synthesis: Transformers and no 3D Priors Robin Rombach*, Patrick Esser*

CompVis Heidelberg 293 Dec 22, 2022
StocksMA is a package to facilitate access to financial and economic data of Moroccan stocks.

Creating easier access to the Moroccan stock market data What is StocksMA ? StocksMA is a package to facilitate access to financial and economic data

Salah Eddine LABIAD 28 Jan 04, 2023
Personal thermal comfort models using digital twins: Preference prediction with BIM-extracted spatial-temporal proximity data from Build2Vec

Personal thermal comfort models using digital twins: Preference prediction with BIM-extracted spatial-temporal proximity data from Build2Vec This repo

Building and Urban Data Science (BUDS) Group 5 Dec 02, 2022
PyBullet CartPole and Quadrotor environments—with CasADi symbolic a priori dynamics—for learning-based control and reinforcement learning

safe-control-gym Physics-based CartPole and Quadrotor Gym environments (using PyBullet) with symbolic a priori dynamics (using CasADi) for learning-ba

Dynamic Systems Lab 300 Dec 28, 2022
Implementation of ETSformer, state of the art time-series Transformer, in Pytorch

ETSformer - Pytorch Implementation of ETSformer, state of the art time-series Transformer, in Pytorch Install $ pip install etsformer-pytorch Usage im

Phil Wang 121 Dec 30, 2022
a dnn ai project to classify which food people are eating on audio recordings

Deep Learning - EAT Challenge About This project is part of an AI challenge of the DeepLearning course 2021 at the University of Augsburg. The objecti

Marco Tröster 1 Oct 24, 2021
Face Mesh is a face geometry solution that estimates 468 3D face landmarks in real-time even on mobile devices

Face-Mesh Face Mesh is a face geometry solution that estimates 468 3D face landmarks in real-time even on mobile devices. It employs machine learning

Farnam Javadi 9 Dec 21, 2022
VID-Fusion: Robust Visual-Inertial-Dynamics Odometry for Accurate External Force Estimation

VID-Fusion VID-Fusion: Robust Visual-Inertial-Dynamics Odometry for Accurate External Force Estimation Authors: Ziming Ding , Tiankai Yang, Kunyi Zhan

ZJU FAST Lab 86 Nov 18, 2022
Source code related to the article submitted to the International Conference on Computational Science ICCS 2022 in London

POTHER: Patch-Voted Deep Learning-based Chest X-ray Bias Analysis for COVID-19 Detection Source code related to the article submitted to the Internati

Tomasz Szczepański 1 Apr 29, 2022
Efficient and intelligent interactive segmentation annotation software

Efficient and intelligent interactive segmentation annotation software

294 Dec 30, 2022
COCO Style Dataset Generator GUI

A simple GUI-based COCO-style JSON Polygon masks' annotation tool to facilitate quick and efficient crowd-sourced generation of annotation masks and bounding boxes. Optionally, one could choose to us

Hans Krupakar 142 Dec 09, 2022