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 simple baseline for 3d human pose estimation in PyTorch.

3d_pose_baseline_pytorch A PyTorch implementation of a simple baseline for 3d human pose estimation. You can check the original Tensorflow implementat

weigq 312 Jan 06, 2023
Stochastic Tensor Optimization for Robot Motion - A GPU Robot Motion Toolkit

STORM Stochastic Tensor Optimization for Robot Motion - A GPU Robot Motion Toolkit [Install Instructions] [Paper] [Website] This package contains code

NVIDIA Research Projects 101 Dec 12, 2022
Unofficial Implementation of RobustSTL: A Robust Seasonal-Trend Decomposition Algorithm for Long Time Series (AAAI 2019)

RobustSTL: A Robust Seasonal-Trend Decomposition Algorithm for Long Time Series (AAAI 2019) This repository contains python (3.5.2) implementation of

Doyup Lee 222 Dec 21, 2022
PyTorch implementation of Octave Convolution with pre-trained Oct-ResNet and Oct-MobileNet models

octconv.pytorch PyTorch implementation of Octave Convolution in Drop an Octave: Reducing Spatial Redundancy in Convolutional Neural Networks with Octa

Duo Li 273 Dec 18, 2022
A Python library for working with arbitrary-dimension hypercomplex numbers following the Cayley-Dickson construction of algebras.

Hypercomplex A Python library for working with quaternions, octonions, sedenions, and beyond following the Cayley-Dickson construction of hypercomplex

7 Nov 04, 2022
DI-smartcross - Decision Intelligence Platform for Traffic Crossing Signal Control

DI-smartcross DI-smartcross - Decision Intelligence Platform for Traffic Crossin

OpenDILab 213 Jan 02, 2023
The 2nd place solution of 2021 google landmark retrieval on kaggle.

Leaderboard, taxonomy, and curated list of few-shot object detection papers.

229 Dec 13, 2022
Official repository of the paper "GPR1200: A Benchmark for General-PurposeContent-Based Image Retrieval"

GPR1200 Dataset GPR1200: A Benchmark for General-Purpose Content-Based Image Retrieval (ArXiv) Konstantin Schall, Kai Uwe Barthel, Nico Hezel, Klaus J

Visual Computing Group 16 Nov 21, 2022
Human annotated noisy labels for CIFAR-10 and CIFAR-100.

Dataloader for CIFAR-N CIFAR-10N noise_label = torch.load('./data/CIFAR-10_human.pt') clean_label = noise_label['clean_label'] worst_label = noise_lab

<a href=[email protected]"> 117 Nov 30, 2022
CUda Matrix Multiply library.

cumm CUda Matrix Multiply library. cumm is developed during learning of CUTLASS, which use too much c++ template and make code unmaintainable. So I de

49 Dec 27, 2022
The dynamics of representation learning in shallow, non-linear autoencoders

The dynamics of representation learning in shallow, non-linear autoencoders The package is written in python and uses the pytorch implementation to ML

Maria Refinetti 4 Jun 08, 2022
A lightweight deep network for fast and accurate optical flow estimation.

FastFlowNet: A Lightweight Network for Fast Optical Flow Estimation The official PyTorch implementation of FastFlowNet (ICRA 2021). Authors: Lingtong

Tone 161 Jan 03, 2023
Self-Supervised Learning of Event-based Optical Flow with Spiking Neural Networks

Self-Supervised Learning of Event-based Optical Flow with Spiking Neural Networks Work accepted at NeurIPS'21 [paper, video]. If you use this code in

TU Delft 43 Dec 07, 2022
A check for whether the dependency jobs are all green.

alls-green A check for whether the dependency jobs are all green. Why? Do you have more than one job in your GitHub Actions CI/CD workflows setup? Do

Re:actors 33 Jan 03, 2023
NeuralDiff: Segmenting 3D objects that move in egocentric videos

NeuralDiff: Segmenting 3D objects that move in egocentric videos Project Page | Paper + Supplementary | Video About This repository contains the offic

Vadim Tschernezki 14 Dec 05, 2022
A generalized framework for prototyping full-stack cooperative driving automation applications under CARLA+SUMO.

OpenCDA OpenCDA is a SIMULATION tool integrated with a prototype cooperative driving automation (CDA; see SAE J3216) pipeline as well as regular autom

UCLA Mobility Lab 726 Dec 29, 2022
This is the code of NeurIPS'21 paper "Towards Enabling Meta-Learning from Target Models".

ST This is the code of NeurIPS 2021 paper "Towards Enabling Meta-Learning from Target Models". If you use any content of this repo for your work, plea

Su Lu 7 Dec 06, 2022
duralava is a neural network which can simulate a lava lamp in an infinite loop.

duralava duralava is a neural network which can simulate a lava lamp in an infinite loop. Example This is not a real lava lamp but a "fake" one genera

Maximilian Bachl 87 Dec 20, 2022
PyTorch implementation of UPFlow (unsupervised optical flow learning)

UPFlow: Upsampling Pyramid for Unsupervised Optical Flow Learning By Kunming Luo, Chuan Wang, Shuaicheng Liu, Haoqiang Fan, Jue Wang, Jian Sun Megvii

kunming luo 87 Dec 20, 2022
Memory Efficient Attention (O(sqrt(n)) for Jax and PyTorch

Memory Efficient Attention This is unofficial implementation of Self-attention Does Not Need O(n^2) Memory for Jax and PyTorch. Implementation is almo

Amin Rezaei 126 Dec 27, 2022