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)
A CNN model to detect hand gestures.

Software Used python - programming language used, tested on v3.8 miniconda - for managing virtual environment Libraries Used opencv - pip install open

Shivanshu 6 Jul 14, 2022
Official implementation of "Towards Good Practices for Efficiently Annotating Large-Scale Image Classification Datasets" (CVPR2021)

Towards Good Practices for Efficiently Annotating Large-Scale Image Classification Datasets This is the official implementation of "Towards Good Pract

Sanja Fidler's Lab 52 Nov 22, 2022
Real-Time High-Resolution Background Matting

Real-Time High-Resolution Background Matting Official repository for the paper Real-Time High-Resolution Background Matting. Our model requires captur

Peter Lin 6.1k Jan 03, 2023
TimeSHAP explains Recurrent Neural Network predictions.

TimeSHAP TimeSHAP is a model-agnostic, recurrent explainer that builds upon KernelSHAP and extends it to the sequential domain. TimeSHAP computes even

Feedzai 90 Dec 18, 2022
A basic implementation of Layer-wise Relevance Propagation (LRP) in PyTorch.

Layer-wise Relevance Propagation (LRP) in PyTorch Basic unsupervised implementation of Layer-wise Relevance Propagation (Bach et al., Montavon et al.)

Kai Fabi 28 Dec 26, 2022
A rough implementation of the paper "A Steering Algorithm for Redirected Walking Using Reinforcement Learning"

A rough implementation of the paper "A Steering Algorithm for Redirected Walking Using Reinforcement Learning"

Somnus `Chen 2 Jun 09, 2022
Program your own vulkan.gpuinfo.org query in Python. Used to determine baseline hardware for WebGPU.

query-gpuinfo-data License This software is not presently released under a license. The data in data/ is obtained under CC BY 4.0 as specified there.

Kai Ninomiya 5 Jul 18, 2022
Official code for our EMNLP2021 Outstanding Paper MindCraft: Theory of Mind Modeling for Situated Dialogue in Collaborative Tasks

MindCraft Authors: Cristian-Paul Bara*, Sky CH-Wang*, Joyce Chai This is the official code repository for the paper (arXiv link): Cristian-Paul Bara,

Situated Language and Embodied Dialogue (SLED) Research Group 14 Dec 29, 2022
Deep Learning Algorithms for Hedging with Frictions

Deep Learning Algorithms for Hedging with Frictions This repository contains the Forward-Backward Stochastic Differential Equation (FBSDE) solver and

Xiaofei Shi 3 Dec 22, 2022
A tensorflow implementation of an HMM layer

tensorflow_hmm Tensorflow and numpy implementations of the HMM viterbi and forward/backward algorithms. See Keras example for an example of how to use

Zach Dwiel 283 Oct 19, 2022
Computer Vision application in the web

Computer Vision application in the web Preview Usage Clone this repo git clone https://github.com/amineHY/WebApp-Computer-Vision-streamlit.git cd Web

Amine Hadj-Youcef. PhD 35 Dec 06, 2022
Implement some metaheuristics and cost functions

Metaheuristics This repot implement some metaheuristics and cost functions. Metaheuristics JAYA Implement Jaya optimizer without constraints. Cost fun

Adri1G 1 Mar 23, 2022
Unofficial PyTorch Implementation for HifiFace (https://arxiv.org/abs/2106.09965)

HifiFace — Unofficial Pytorch Implementation Image source: HifiFace: 3D Shape and Semantic Prior Guided High Fidelity Face Swapping (figure 1, pg. 1)

MINDs Lab 218 Jan 04, 2023
Bare bones use-case for deploying a containerized web app (built in streamlit) on AWS.

Containerized Streamlit web app This repository is featured in a 3-part series on Deploying web apps with Streamlit, Docker, and AWS. Checkout the blo

Collin Prather 62 Jan 02, 2023
QuALITY: Question Answering with Long Input Texts, Yes!

QuALITY: Question Answering with Long Input Texts, Yes! Authors: Richard Yuanzhe Pang,* Alicia Parrish,* Nitish Joshi,* Nikita Nangia, Jason Phang, An

ML² AT CILVR 61 Jan 02, 2023
An example of Scatterbrain implementation (combining local attention and Performer)

An example of Scatterbrain implementation (combining local attention and Performer)

HazyResearch 97 Jan 02, 2023
(Personalized) Page-Rank computation using PyTorch

torch-ppr This package allows calculating page-rank and personalized page-rank via power iteration with PyTorch, which also supports calculation on GP

Max Berrendorf 69 Dec 03, 2022
FCAF3D: Fully Convolutional Anchor-Free 3D Object Detection

FCAF3D: Fully Convolutional Anchor-Free 3D Object Detection This repository contains an implementation of FCAF3D, a 3D object detection method introdu

SamsungLabs 153 Dec 29, 2022